예제 #1
0
        public static void VerifyAccountProperties(CognitiveServicesAccount account, bool useDefaults, string kind = DefaultKind, string skuName = DefaultSkuName, string location = "westus")
        {
            Assert.NotNull(account); // verifies that the account is actually created
            Assert.NotNull(account.Id);
            Assert.NotNull(account.Location);
            Assert.NotNull(account.Name);
            Assert.NotNull(account.Etag);
            Assert.NotNull(account.Kind);

            Assert.NotNull(account.Sku);
            Assert.NotNull(account.Sku.Name);

            Assert.NotNull(account.Properties.Endpoint);
            Assert.Equal(ProvisioningState.Succeeded, account.Properties.ProvisioningState);

            if (useDefaults)
            {
                Assert.Equal(CognitiveServicesManagementTestUtilities.DefaultLocation, account.Location);
                Assert.Equal(CognitiveServicesManagementTestUtilities.DefaultSkuName, account.Sku.Name);
                Assert.Equal(CognitiveServicesManagementTestUtilities.DefaultKind.ToString(), account.Kind);

                Assert.NotNull(account.Tags);
                Assert.Equal(2, account.Tags.Count);
                Assert.Equal("value1", account.Tags["key1"]);
                Assert.Equal("value2", account.Tags["key2"]);
            }
            else
            {
                Assert.Equal(skuName, account.Sku.Name);
                Assert.Equal(kind, account.Kind);
                Assert.Equal(location, account.Location);
            }
        }
        public void CognitiveServicesAccountMinMaxNameLengthTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient             = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                var parameters = new CognitiveServicesAccount
                {
                    Sku = new Sku {
                        Name = "S0"
                    },
                    Kind       = "Face",
                    Location   = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new CognitiveServicesAccountProperties(),
                };

                var minName = "zz";
                var maxName = "AcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcadAcad";

                var minAccount = cognitiveServicesMgmtClient.Accounts.Create(rgname, minName, parameters);
                var maxAccount = cognitiveServicesMgmtClient.Accounts.Create(rgname, maxName, parameters);

                Assert.Equal(minName, minAccount.Name);
                Assert.Equal(maxName, maxAccount.Name);
            }
        }
예제 #3
0
        public void CognitiveServicesAccountListBySubscriptionTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var resourcesClient             = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);


                // Create resource group and cognitive services account
                var    rgname1      = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);
                string accountName1 = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname1);

                // Create different resource group and cognitive account
                var    rgname2      = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);
                string accountName2 = CognitiveServicesManagementTestUtilities.CreateCognitiveServicesAccount(cognitiveServicesMgmtClient, rgname2);

                var accounts = cognitiveServicesMgmtClient.Accounts.List();

                Assert.True(accounts.Count() >= 2);

                CognitiveServicesAccount account1 = accounts.First(
                    t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName1));
                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(account1, true);

                CognitiveServicesAccount account2 = accounts.First(
                    t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName2));
                CognitiveServicesManagementTestUtilities.VerifyAccountProperties(account2, true);
            }
        }
        public void CognitiveServicesCreateAccountErrorTest()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient             = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                var accountName = TestUtilities.GenerateName("csa");
                var parameters  = new CognitiveServicesAccount
                {
                    Sku = new Sku {
                        Name = "F0"
                    },
                    Kind       = "ComputerVision",
                    Location   = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new CognitiveServicesAccountProperties(),
                };

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create("NotExistedRG", accountName, parameters),
                    "ResourceGroupNotFound");

                parameters.Location = "BLA";
                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, parameters),
                    "LocationNotAvailableForResourceType");
            }
        }
예제 #5
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            RunCmdLet(() =>
            {
                CognitiveServicesAccountCreateParameters createParameters = new CognitiveServicesAccountCreateParameters()
                {
                    Location   = Location,
                    Kind       = Type, // must have value, mandatory parameter
                    Sku        = new Sku(SkuName),
                    Tags       = TagsConversionHelper.CreateTagDictionary(Tag),
                    Properties = string.IsNullOrWhiteSpace(CustomSubdomainName) ?
                                 new object():
                                 JToken.Parse(string.Format(
                                                  CultureInfo.InvariantCulture,
                                                  "{{\"customSubDomainName\":\"{0}\"}}",
                                                  CustomSubdomainName))
                };

                if (ShouldProcess(
                        Name, string.Format(CultureInfo.CurrentCulture, Resources.NewAccount_ProcessMessage, Name, Type, SkuName, Location)))
                {
                    if (Type.StartsWith("Bing.", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (Force.IsPresent)
                        {
                            WriteWarning(Resources.NewAccount_Notice);
                        }
                        else
                        {
                            bool yesToAll = false, noToAll = false;
                            if (!ShouldContinue(Resources.NewAccount_Notice, "Notice", true, ref yesToAll, ref noToAll))
                            {
                                return;
                            }
                        }
                    }
                    try
                    {
                        CognitiveServicesAccount createAccountResponse = CognitiveServicesClient.Accounts.Create(
                            ResourceGroupName,
                            Name,
                            createParameters);
                    }
                    catch (Exception ex)
                    {
                        // Give users a specific message says `Failed to create Cognitive Services account.`
                        // Details should able be found in the exception.
                        throw new Exception("Failed to create Cognitive Services account.", ex);
                    }

                    CognitiveServicesAccount cognitiveServicesAccount = CognitiveServicesClient.Accounts.GetProperties(ResourceGroupName, Name);
                    WriteCognitiveServicesAccount(cognitiveServicesAccount);
                }
            });
        }
예제 #6
0
        static void create_resource(CognitiveServicesManagementClient client, string resource_name, string kind, string account_tier, string location)
        {
            Console.WriteLine("Creating resource: " + resource_name + "...");
            // The parameter "properties" must be an empty object.
            CognitiveServicesAccount parameters =
                new CognitiveServicesAccount(null, null, kind, location, resource_name, new CognitiveServicesAccountProperties(), new Sku(account_tier));
            var result = client.Accounts.Create(resource_group_name, account_tier, parameters);

            Console.WriteLine("Resource created.");
            Console.WriteLine("ID: " + result.Id);
            Console.WriteLine("Kind: " + result.Kind);
            Console.WriteLine();
        }
예제 #7
0
        public static CognitiveServicesAccount GetDefaultCognitiveServicesAccountParameters()
        {
            CognitiveServicesAccount account = new CognitiveServicesAccount
            {
                Location = DefaultLocation,
                Tags     = DefaultTags,
                Sku      = new Microsoft.Azure.Management.CognitiveServices.Models.Sku {
                    Name = DefaultSkuName
                },
                Kind       = DefaultKind,
                Properties = new CognitiveServicesAccountProperties(),
            };

            return(account);
        }
예제 #8
0
        // </snippet_list>

        // <snippet_create>
        static void create_resource(CognitiveServicesManagementClient client, string resource_name, string kind, string account_tier, string location)
        {
            Console.WriteLine("Creating resource: " + resource_name + "...");

            /* NOTE If you do not want to use a custom subdomain name, remove the customSubDomainName
             * property from CognitiveServicesAccountProperties. */
            CognitiveServicesAccount parameters =
                new CognitiveServicesAccount(null, null, kind, location, resource_name, new CognitiveServicesAccountProperties(customSubDomainName: subdomain_name), new Sku(account_tier));
            var result = client.Accounts.Create(resource_group_name, resource_name, parameters);

            Console.WriteLine("Resource created.");
            Console.WriteLine("ID: " + result.Id);
            Console.WriteLine("Kind: " + result.Kind);
            Console.WriteLine();
        }
예제 #9
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            RunCmdLet(() =>
            {
                CognitiveServicesAccountCreateParameters createParameters = new CognitiveServicesAccountCreateParameters()
                {
                    Location   = Location,
                    Kind       = Type, // must have value, mandatory parameter
                    Sku        = new Sku(SkuName),
                    Tags       = TagsConversionHelper.CreateTagDictionary(Tag),
                    Properties = string.IsNullOrWhiteSpace(CustomSubdomainName) ?
                                 new object():
                                 JToken.Parse(string.Format(
                                                  CultureInfo.InvariantCulture,
                                                  "{{\"customSubDomainName\":\"{0}\"}}",
                                                  CustomSubdomainName))
                };

                if (ShouldProcess(
                        Name, string.Format(CultureInfo.CurrentCulture, Resources.NewAccount_ProcessMessage, Name, Type, SkuName, Location)))
                {
                    if (Force.IsPresent)
                    {
                        WriteWarning(Resources.NewAccount_Notice);
                    }
                    else
                    {
                        bool yesToAll = false, noToAll = false;
                        if (!ShouldContinue(Resources.NewAccount_Notice, "Notice", true, ref yesToAll, ref noToAll))
                        {
                            return;
                        }
                    }

                    CognitiveServicesAccount createAccountResponse = CognitiveServicesClient.Accounts.Create(
                        ResourceGroupName,
                        Name,
                        createParameters);
                    CognitiveServicesAccount cognitiveServicesAccount = CognitiveServicesClient.Accounts.GetProperties(ResourceGroupName, Name);
                    WriteCognitiveServicesAccount(cognitiveServicesAccount);
                }
            });
        }
        public void CognitiveServicesCreateAccountErrorTest2()
        {
            var handler = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                var resourcesClient             = CognitiveServicesManagementTestUtilities.GetResourceManagementClient(context, handler);
                var cognitiveServicesMgmtClient = CognitiveServicesManagementTestUtilities.GetCognitiveServicesManagementClient(context, handler);

                // Create resource group
                var rgname = CognitiveServicesManagementTestUtilities.CreateResourceGroup(resourcesClient);

                var accountName     = TestUtilities.GenerateName("csa");
                var nonExistApiPara = new CognitiveServicesAccount
                {
                    Sku = new Sku {
                        Name = "F0"
                    },
                    Kind       = "NonExistAPI",
                    Location   = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new CognitiveServicesAccountProperties(),
                };

                var nonExistSkuPara = new CognitiveServicesAccount
                {
                    Sku = new Sku {
                        Name = "N0"
                    },
                    Kind       = "Face",
                    Location   = CognitiveServicesManagementTestUtilities.DefaultLocation,
                    Properties = new CognitiveServicesAccountProperties(),
                };

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, nonExistApiPara),
                    "InvalidApiSetId");

                CognitiveServicesManagementTestUtilities.ValidateExpectedException(
                    () => cognitiveServicesMgmtClient.Accounts.Create(rgname, accountName, nonExistSkuPara),
                    "InvalidSkuId");
            }
        }
예제 #11
0
        public static CognitiveServicesAccount CreateAndValidateAccountWithOnlyRequiredParameters(CognitiveServicesManagementClient cognitiveServicesMgmtClient, string rgName, string skuName, string accountType = "TextAnalytics", string location = null)
        {
            // Create account with only required params
            var accountName = TestUtilities.GenerateName("csa");
            var parameters  = new CognitiveServicesAccount
            {
                Sku = new Microsoft.Azure.Management.CognitiveServices.Models.Sku {
                    Name = skuName
                },
                Kind       = accountType,
                Location   = location ?? DefaultLocation,
                Properties = new CognitiveServicesAccountProperties(),
            };
            var account = cognitiveServicesMgmtClient.Accounts.Create(rgName, accountName, parameters);

            VerifyAccountProperties(account, false, accountType, skuName, location ?? DefaultLocation);

            return(account);
        }
예제 #12
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            bool hasPropertiesChange = false;
            var  properties          = new CognitiveServicesAccountProperties();

            if (!string.IsNullOrWhiteSpace(CustomSubdomainName))
            {
                hasPropertiesChange            = true;
                properties.CustomSubDomainName = CustomSubdomainName;
            }
            if (NetworkRuleSet != null)
            {
                hasPropertiesChange    = true;
                properties.NetworkAcls = NetworkRuleSet.ToNetworkRuleSet();
            }

            Sku sku = null;

            if (!string.IsNullOrWhiteSpace(this.SkuName))
            {
                sku = new Sku(this.SkuName);
            }

            Dictionary <string, string> tags = null;

            if (this.Tag != null)
            {
                Dictionary <string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(Tag);
                tags = tagDictionary ?? new Dictionary <string, string>();
            }

            CognitiveServicesAccount updateParameters = new CognitiveServicesAccount()
            {
                Sku        = sku,
                Tags       = tags,
                Properties = properties
            };

            if (!string.IsNullOrEmpty(PublicNetworkAccess))
            {
                hasPropertiesChange = true;
                updateParameters.Properties.PublicNetworkAccess = PublicNetworkAccess;
            }

            if (AssignIdentity.IsPresent)
            {
                hasPropertiesChange       = true;
                updateParameters.Identity = new Identity(Microsoft.Azure.Management.CognitiveServices.Models.IdentityType.SystemAssigned);
            }

            if (this.IsParameterBound(c => c.IdentityType))
            {
                hasPropertiesChange       = true;
                updateParameters.Identity = new Identity(this.IdentityType);
            }

            if (CognitiveServicesEncryption.IsPresent)
            {
                hasPropertiesChange = true;
                updateParameters.Properties.Encryption = new Encryption(null, KeySource.MicrosoftCognitiveServices);
            }

            if (ParameterSetName == KeyVaultEncryptionParameterSet)
            {
                hasPropertiesChange = true;
                updateParameters.Properties.Encryption = new Encryption(
                    new KeyVaultProperties()
                {
                    KeyName     = KeyName,
                    KeyVersion  = KeyVersion,
                    KeyVaultUri = KeyVaultUri
                },
                    KeySource.MicrosoftKeyVault);
            }

            if (StorageAccountId != null && StorageAccountId.Length > 0)
            {
                hasPropertiesChange = true;
                updateParameters.Properties.UserOwnedStorage = new List <UserOwnedStorage>();
                foreach (var storageAccountId in StorageAccountId)
                {
                    updateParameters.Properties.UserOwnedStorage.Add(new UserOwnedStorage(storageAccountId));
                }
            }

            string processMessage = string.Empty;

            if (sku != null && tags != null)
            {
                processMessage = string.Format(CultureInfo.CurrentCulture, Resources.SetAccount_ProcessMessage_UpdateSkuAndTags, this.Name, sku.Name);
            }
            else if (sku != null)
            {
                processMessage = string.Format(CultureInfo.CurrentCulture, Resources.SetAccount_ProcessMessage_UpdateSku, this.Name, sku.Name);
            }
            else if (tags != null)
            {
                processMessage = string.Format(CultureInfo.CurrentCulture, Resources.SetAccount_ProcessMessage_UpdateTags, this.Name);
            }
            else
            {
                if (!hasPropertiesChange)
                {
                    // Not updating anything (this is allowed) - just return the account, no need for approval.
                    var cognitiveServicesAccount = this.CognitiveServicesClient.Accounts.GetProperties(this.ResourceGroupName, this.Name);
                    WriteCognitiveServicesAccount(cognitiveServicesAccount);
                    return;
                }
                else
                {
                    processMessage = string.Format(CultureInfo.CurrentCulture, Resources.SetAccount_ProcessMessage, this.Name);
                }
            }

            if (ShouldProcess(
                    this.Name, processMessage)
                ||
                Force.IsPresent)
            {
                RunCmdLet(() =>
                {
                    var updatedAccount = this.CognitiveServicesClient.Accounts.Update(
                        this.ResourceGroupName,
                        this.Name,
                        updateParameters
                        );

                    WriteCognitiveServicesAccount(updatedAccount);
                });
            }
        }
예제 #13
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            RunCmdLet(() =>
            {
                var properties = new CognitiveServicesAccountProperties();
                if (!string.IsNullOrWhiteSpace(CustomSubdomainName))
                {
                    properties.CustomSubDomainName = CustomSubdomainName;
                }

                if (NetworkRuleSet != null)
                {
                    properties.NetworkAcls = NetworkRuleSet.ToNetworkRuleSet();
                }

                if (ApiProperty != null)
                {
                    properties.ApiProperties = ApiProperty;
                }

                CognitiveServicesAccount createParameters = new CognitiveServicesAccount()
                {
                    Location   = Location,
                    Kind       = Type, // must have value, mandatory parameter
                    Sku        = new Sku(SkuName, null),
                    Tags       = TagsConversionHelper.CreateTagDictionary(Tag),
                    Properties = properties
                };

                if (!string.IsNullOrEmpty(PublicNetworkAccess))
                {
                    createParameters.Properties.PublicNetworkAccess = PublicNetworkAccess;
                }

                if (AssignIdentity.IsPresent)
                {
                    createParameters.Identity = new Identity(IdentityType.SystemAssigned);
                }

                if (CognitiveServicesEncryption.IsPresent)
                {
                    createParameters.Properties.Encryption = new Encryption(null, KeySource.MicrosoftCognitiveServices);
                }

                if (ParameterSetName == KeyVaultEncryptionParameterSet)
                {
                    createParameters.Properties.Encryption = new Encryption(
                        new KeyVaultProperties()
                    {
                        KeyName     = KeyName,
                        KeyVersion  = KeyVersion,
                        KeyVaultUri = KeyVaultUri
                    },
                        KeySource.MicrosoftKeyVault);
                }


                if (StorageAccountId != null && StorageAccountId.Length > 0)
                {
                    createParameters.Properties.UserOwnedStorage = new List <UserOwnedStorage>();
                    foreach (var storageAccountId in StorageAccountId)
                    {
                        createParameters.Properties.UserOwnedStorage.Add(new UserOwnedStorage(storageAccountId));
                    }
                }

                if (ShouldProcess(
                        Name, string.Format(CultureInfo.CurrentCulture, Resources.NewAccount_ProcessMessage, Name, Type, SkuName, Location)))
                {
                    if (Type.StartsWith("Bing.", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (Force.IsPresent)
                        {
                            WriteWarning(Resources.NewAccount_Notice);
                        }
                        else
                        {
                            bool yesToAll = false, noToAll = false;
                            if (!ShouldContinue(Resources.NewAccount_Notice, "Notice", true, ref yesToAll, ref noToAll))
                            {
                                return;
                            }
                        }
                    }

                    if (Type.Equals("Face", StringComparison.InvariantCultureIgnoreCase) || Type.Equals("CognitiveServices", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (Force.IsPresent)
                        {
                            WriteWarning(Resources.NewAccount_LegalTerm_NotPolice);
                        }
                        else
                        {
                            bool yesToAll = false, noToAll = false;
                            if (!ShouldContinue(Resources.NewAccount_LegalTerm_NotPolice, "Notice", true, ref yesToAll, ref noToAll))
                            {
                                return;
                            }
                        }
                    }


                    try
                    {
                        CognitiveServicesAccount createAccountResponse = CognitiveServicesClient.Accounts.Create(
                            ResourceGroupName,
                            Name,
                            createParameters);
                    }
                    catch (ErrorException ex)
                    {
                        // If the Exception is ErrorException, clone the exception with modified message.
                        var newEx      = new ErrorException($"Failed to create Cognitive Services account. {ex.Message}", ex);
                        newEx.Body     = ex.Body;
                        newEx.Request  = ex.Request;
                        newEx.Response = ex.Response;
                        throw newEx;
                    }
                    catch (Exception ex)
                    {
                        // Give users a specific message says `Failed to create Cognitive Services account.`
                        // Details should able be found in the inner exception.
                        throw new Exception("Failed to create Cognitive Services account.", ex);
                    }

                    CognitiveServicesAccount cognitiveServicesAccount = CognitiveServicesClient.Accounts.GetProperties(ResourceGroupName, Name);
                    WriteCognitiveServicesAccount(cognitiveServicesAccount);
                }
            });
        }
예제 #14
0
 /// <summary>
 /// Updates a Cognitive Services account
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group. The name is case insensitive.
 /// </param>
 /// <param name='accountName'>
 /// The name of Cognitive Services account.
 /// </param>
 /// <param name='account'>
 /// The parameters to provide for the created account.
 /// </param>
 public static CognitiveServicesAccount Update(this IAccountsOperations operations, string resourceGroupName, string accountName, CognitiveServicesAccount account)
 {
     return(operations.UpdateAsync(resourceGroupName, accountName, account).GetAwaiter().GetResult());
 }
예제 #15
0
 /// <summary>
 /// Create Cognitive Services Account. Accounts is a resource group wide
 /// resource type. It holds the keys for developer to access intelligent APIs.
 /// It's also the resource type for billing.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group. The name is case insensitive.
 /// </param>
 /// <param name='accountName'>
 /// The name of Cognitive Services account.
 /// </param>
 /// <param name='account'>
 /// The parameters to provide for the created account.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <CognitiveServicesAccount> CreateAsync(this IAccountsOperations operations, string resourceGroupName, string accountName, CognitiveServicesAccount account, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, account, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }