Exemplo n.º 1
0
        /**
         * Azure App Service sample for managing web apps.
         *  - app service plan, web app
         *    - Create 2 web apps under the same new app service plan
         *  - domain
         *    - Create a domain
         *  - certificate
         *    - Upload a self-signed wildcard certificate
         *    - update both web apps to use the domain and the created wildcard SSL certificate
         */
        public static void RunSample(IAzure azure)
        {
            string app1Name   = SdkContext.RandomResourceName("webapp1-", 20);
            string app2Name   = SdkContext.RandomResourceName("webapp2-", 20);
            string rgName     = SdkContext.RandomResourceName("rgNEMV_", 24);
            string domainName = SdkContext.RandomResourceName("jsdkdemo-", 20) + ".com";

            try
            {
                //============================================================
                // Create a web app with a new app service plan

                Utilities.Log("Creating web app " + app1Name + "...");

                var app1 = azure.WebApps
                           .Define(app1Name)
                           .WithRegion(Region.USWest)
                           .WithNewResourceGroup(rgName)
                           .WithNewWindowsPlan(PricingTier.StandardS1)
                           .Create();

                Utilities.Log("Created web app " + app1.Name);
                Utilities.Print(app1);

                //============================================================
                // Create a second web app with the same app service plan

                Utilities.Log("Creating another web app " + app2Name + "...");
                var plan = azure.AppServices.AppServicePlans.GetById(app1.AppServicePlanId);
                var app2 = azure.WebApps
                           .Define(app2Name)
                           .WithExistingWindowsPlan(plan)
                           .WithExistingResourceGroup(rgName)
                           .Create();

                Utilities.Log("Created web app " + app2.Name);
                Utilities.Print(app2);

                //============================================================
                // Purchase a domain (will be canceled for a full refund)

                Utilities.Log("Purchasing a domain " + domainName + "...");

                var domain = azure.AppServices.AppServiceDomains.Define(domainName)
                             .WithExistingResourceGroup(rgName)
                             .DefineRegistrantContact()
                             .WithFirstName("Jon")
                             .WithLastName("Doe")
                             .WithEmail("*****@*****.**")
                             .WithAddressLine1("123 4th Ave")
                             .WithCity("Redmond")
                             .WithStateOrProvince("WA")
                             .WithCountry(CountryISOCode.UnitedStates)
                             .WithPostalCode("98052")
                             .WithPhoneCountryCode(CountryPhoneCode.UnitedStates)
                             .WithPhoneNumber("4258828080")
                             .Attach()
                             .WithDomainPrivacyEnabled(true)
                             .WithAutoRenewEnabled(false)
                             .Create();
                Utilities.Log("Purchased domain " + domain.Name);
                Utilities.Print(domain);

                //============================================================
                // Bind domain to web app 1

                Utilities.Log("Binding http://" + app1Name + "." + domainName + " to web app " + app1Name + "...");

                app1 = app1.Update()
                       .DefineHostnameBinding()
                       .WithAzureManagedDomain(domain)
                       .WithSubDomain(app1Name)
                       .WithDnsRecordType(CustomHostNameDnsRecordType.CName)
                       .Attach()
                       .Apply();

                Utilities.Log("Finished binding http://" + app1Name + "." + domainName + " to web app " + app1Name);
                Utilities.Print(app1);

                //============================================================
                // Create a self-singed SSL certificate

                var pfxPath = "webapp_" + nameof(ManageWebAppWithDomainSsl).ToLower() + ".pfx";

                Utilities.Log("Creating a self-signed certificate " + pfxPath + "...");

                Utilities.CreateCertificate(domainName, pfxPath, CertificatePassword);

                Utilities.Log("Created self-signed certificate " + pfxPath);

                //============================================================
                // Bind domain to web app 2 and turn on wild card SSL for both

                Utilities.Log("Binding https://" + app1Name + "." + domainName + " to web app " + app1Name + "...");

                app1 = app1.Update()
                       .WithManagedHostnameBindings(domain, app1Name)
                       .DefineSslBinding()
                       .ForHostname(app1Name + "." + domainName)
                       .WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), CertificatePassword)
                       .WithSniBasedSsl()
                       .Attach()
                       .Apply();

                Utilities.Log("Finished binding https://" + app1Name + "." + domainName + " to web app " + app1Name);
                Utilities.Print(app1);

                Utilities.Log("Binding https://" + app2Name + "." + domainName + " to web app " + app2Name + "...");

                app2 = app2.Update()
                       .WithManagedHostnameBindings(domain, app2Name)
                       .DefineSslBinding()
                       .ForHostname(app2Name + "." + domainName)
                       .WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), CertificatePassword)
                       .WithSniBasedSsl()
                       .Attach()
                       .Apply();

                Utilities.Log("Finished binding https://" + app2Name + "." + domainName + " to web app " + app2Name);
                Utilities.Print(app2);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
Exemplo n.º 2
0
        // This method will be called for each input received from the pipeline to this cmdlet; if no input is received, this method is not called
        protected override void ProcessRecord()
        {
            ProgressRecord progress = new ProgressRecord(1, "SimpleSwarm Setup", "Connecting to Azure...");

            WriteProgress(progress);
            var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));


            var azure = Microsoft.Azure.Management.Fluent.Azure
                        .Configure()
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Resource Group...");
            WriteProgress(progress);
            IResourceGroup resourceGroup = azure.ResourceGroups
                                           .Define(resourceGroupName)
                                           .WithRegion(location)
                                           .Create();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Swarm Manager Identity...");
            WriteProgress(progress);
            IIdentity identityManager = azure.Identities
                                        .Define("AzSwarmManager")
                                        .WithRegion(location)
                                        .WithExistingResourceGroup(resourceGroup)
                                        .Create();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Swarm Worker Identity...");
            WriteProgress(progress);
            IIdentity identityWorker = azure.Identities
                                       .Define("AzSwarmWorker")
                                       .WithRegion(location)
                                       .WithExistingResourceGroup(resourceGroup)
                                       .Create();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Key Vault...");
            WriteProgress(progress);
            IVault keyVault = azure.Vaults
                              .Define(SdkContext.RandomResourceName("azswarmkv-", 20))
                              .WithRegion(location)
                              .WithExistingResourceGroup(resourceGroup)
                              .WithEmptyAccessPolicy().Create();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Updating Key Vault Swarm Manager Access Policy...");
            WriteProgress(progress);
            keyVault.Update()
            .DefineAccessPolicy()
            .ForObjectId(identityManager.PrincipalId)
            .AllowSecretAllPermissions()
            .Attach()
            .Apply();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Updating Key Vault Swarm Worker Access Policy...");
            WriteProgress(progress);
            keyVault.Update()
            .DefineAccessPolicy()
            .ForObjectId(identityWorker.PrincipalId)
            .AllowSecretPermissions(SecretPermissions.Get)
            .AllowSecretPermissions(SecretPermissions.List)
            .Attach()
            .Apply();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Virtual Network...");
            WriteProgress(progress);
            INetwork network = azure.Networks
                               .Define(SdkContext.RandomResourceName("AzSwarmNetwork", 20))
                               .WithRegion(location)
                               .WithExistingResourceGroup(resourceGroup)
                               .WithAddressSpace("10.0.0.0/16")
                               .WithSubnet("AzSwarmSubnet", "10.0.0.0/24")
                               .Create();


            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Storage Account...");
            WriteProgress(progress);
            IStorageAccount storage = azure.StorageAccounts
                                      .Define(SdkContext.RandomResourceName("azswarmst", 20))
                                      .WithRegion(location)
                                      .WithExistingResourceGroup(resourceGroup)
                                      .WithAccessFromAllNetworks()
                                      .WithAccessFromAzureServices()
                                      .WithGeneralPurposeAccountKindV2()
                                      .WithOnlyHttpsTraffic()
                                      .WithSku(StorageAccountSkuType.Standard_LRS)
                                      .Create();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Storage Account Table...");
            WriteProgress(progress);
            var storageAccountAccessKeys = storage.GetKeys();

            string storageConnectionString = "DefaultEndpointsProtocol=https"
                                             + ";AccountName=" + storage.Name
                                             + ";AccountKey=" + storageAccountAccessKeys[0].Value
                                             + ";EndpointSuffix=core.windows.net";

            var cloudStorageAccount      = CloudStorageAccount.Parse(storageConnectionString);
            CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient(new TableClientConfiguration());
            CloudTable       table       = tableClient.GetTableReference("SimpleSwarmSetup");

            table.CreateIfNotExists();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Manager Availability Set...");
            WriteProgress(progress);
            IAvailabilitySet availabilitySetManager = azure.AvailabilitySets.Define("azswarm-manager-avset")
                                                      .WithRegion(location)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithFaultDomainCount(3)
                                                      .WithUpdateDomainCount(5)
                                                      .Create();

            progress = new ProgressRecord(1, "SimpleSwarm Setup", "Creating Manager Availability Set...");
            WriteProgress(progress);
            IAvailabilitySet availabilitySetWorker = azure.AvailabilitySets.Define("azswarm-worker-avset")
                                                     .WithRegion(location)
                                                     .WithExistingResourceGroup(resourceGroup)
                                                     .WithFaultDomainCount(3)
                                                     .WithUpdateDomainCount(5)
                                                     .Create();

            WriteVerbose("SimpleSwarm Setup Completed");
        }
Exemplo n.º 3
0
        public void CanCRUDCassandraTable()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var dbName             = SdkContext.RandomResourceName("cosmosdb", 22);
                var rgName             = SdkContext.RandomResourceName("cosmosdbRg", 22);
                var cassandraName      = SdkContext.RandomResourceName("cassandra", 22);
                var cassandraTableName = SdkContext.RandomResourceName("cassandratable", 22);
                var region             = Region.USWest;

                var azure = TestHelper.CreateRollupClient();

                try
                {
                    azure.ResourceGroups.Define(rgName).WithRegion(region).Create();
                    var databaseAccount = azure.CosmosDBAccounts.Define(dbName)
                                          .WithRegion(region)
                                          .WithExistingResourceGroup(rgName)
                                          .WithDataModelCassandra()
                                          .WithStrongConsistency()
                                          .DefineNewCassandraKeyspace(cassandraName)
                                          .WithThroughput(400)
                                          .DefineNewCassandraTable(cassandraTableName)
                                          .WithThroughput(600)
                                          .WithColumn("id", "int")
                                          .WithColumn("name", "text")
                                          .WithColumn("test", "boolean")
                                          .WithPartitionKey("id")
                                          .Attach()
                                          .Attach()
                                          .Create();

                    var cassandras = databaseAccount.ListCassandraKeyspaces().ToList();
                    Assert.Single(cassandras);

                    var cassandra = cassandras[0];
                    Assert.Equal(cassandraName, cassandra.Name);
                    Assert.Equal(400, cassandra.GetThroughputSettings().Throughput);

                    var tables = cassandra.ListCassandraTables().ToList();
                    Assert.Single(tables);

                    var table = tables[0];
                    Assert.Equal(cassandraTableName, table.Name);
                    Assert.Equal(600, table.GetThroughputSettings().Throughput);
                    Assert.Equal(3, table.Schema.Columns.Count);
                    Assert.Equal(1, table.Schema.PartitionKeys.Count);
                    Assert.Equal("id", table.Schema.PartitionKeys[0].Name);

                    databaseAccount = databaseAccount.Update()
                                      .UpdateCassandraKeyspace(cassandraName)
                                      .UpdateCassandraTable(cassandraTableName)
                                      .WithThroughput(500)
                                      .WithoutColumn("test")
                                      .Parent()
                                      .WithThroughput(800)
                                      .Parent()
                                      .Apply();

                    cassandra = databaseAccount.GetCassandraKeyspace(cassandraName);
                    Assert.Equal(800, cassandra.GetThroughputSettings().Throughput);

                    table = cassandra.GetCassandraTable(cassandraTableName);
                    Assert.Equal(500, table.GetThroughputSettings().Throughput);
                    Assert.Equal(2, table.Schema.Columns.Count);
                    Assert.Null(table.Schema.Columns.SingleOrDefault(element => element.Name == "test"));
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.BeginDeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 4
0
        public void CanCRUDGremlinGraph()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var dbName           = SdkContext.RandomResourceName("cosmosdb", 22);
                var rgName           = SdkContext.RandomResourceName("cosmosdbRg", 22);
                var gremlinName      = SdkContext.RandomResourceName("gremlin", 22);
                var gremlinGraphName = SdkContext.RandomResourceName("gremlingraph", 22);
                var region           = Region.USWest;

                var azure = TestHelper.CreateRollupClient();

                try
                {
                    azure.ResourceGroups.Define(rgName).WithRegion(region).Create();
                    var databaseAccount = azure.CosmosDBAccounts.Define(dbName)
                                          .WithRegion(region)
                                          .WithExistingResourceGroup(rgName)
                                          .WithDataModelGremlin()
                                          .WithStrongConsistency()
                                          .DefineNewGremlinDatabase(gremlinName)
                                          .WithThroughput(1000)
                                          .DefineNewGremlinGraph(gremlinGraphName)
                                          .WithThroughput(400)
                                          .DefineIndexingPolicy()
                                          .WithIndexingMode(IndexingMode.Consistent)
                                          .WithIncludedPath(new IncludedPath(path: "/*"))
                                          .WithExcludedPath(new ExcludedPath(path: "/myPathToNotIndex/*"))
                                          .Attach()
                                          .WithPartitionKey(paths: new List <string>()
                    {
                        "/myPartitionKey"
                    }, kind: PartitionKind.Hash, version: null)
                                          .Attach()
                                          .Attach()
                                          .Create();

                    var gremlins = databaseAccount.ListGremlinDatabases().ToList();
                    Assert.Single(gremlins);

                    var gremlin = gremlins[0];
                    Assert.Equal(gremlinName, gremlin.Name);
                    Assert.Equal(1000, gremlin.GetThroughputSettings().Throughput);

                    var graphs = gremlin.ListGremlinGraphs().ToList();
                    Assert.Single(graphs);

                    var graph = graphs[0];
                    Assert.Equal(gremlinGraphName, graph.Name);
                    Assert.Equal(400, graph.GetThroughputSettings().Throughput);
                    Assert.Equal(IndexingMode.Consistent, graph.IndexingPolicy.IndexingMode);
                    Assert.NotNull(graph.IndexingPolicy.IncludedPaths.Single(element => element.Path == "/*"));
                    Assert.NotNull(graph.IndexingPolicy.ExcludedPaths.Single(element => element.Path == "/myPathToNotIndex/*"));
                    Assert.True(graph.PartitionKey.Paths.Contains("/myPartitionKey"));
                    Assert.Equal(PartitionKind.Hash, graph.PartitionKey.Kind);

                    databaseAccount = databaseAccount.Update()
                                      .UpdateGremlinDatabase(gremlinName)
                                      .WithThroughput(800)
                                      .UpdateGremlinGraph(gremlinGraphName)
                                      .WithThroughput(600)
                                      .Parent()
                                      .Parent()
                                      .Apply();

                    gremlin = databaseAccount.GetGremlinDatabase(gremlinName);
                    Assert.Equal(800, gremlin.GetThroughputSettings().Throughput);

                    graph = gremlin.GetGremlinGraph(gremlinGraphName);
                    Assert.Equal(600, graph.GetThroughputSettings().Throughput);
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.BeginDeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        public void CanCreateImageFromNativeVhd()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var vhdBasedImageName = SdkContext.RandomResourceName("img", 20);
                var resourceManager   = TestHelper.CreateRollupClient();
                var computeManager    = TestHelper.CreateComputeManager();
                var rgName            = TestUtilities.GenerateName("rgfluentchash-");

                try
                {
                    var linuxVM = PrepareGeneralizedVMWith2EmptyDataDisks(rgName,
                                                                          SdkContext.RandomResourceName("muldvm", 15),
                                                                          Location,
                                                                          computeManager);
                    //
                    var creatableDisk = computeManager.VirtualMachineCustomImages.Define(vhdBasedImageName)
                                        .WithRegion(Location)
                                        .WithNewResourceGroup(rgName)
                                        .WithLinuxFromVhd(linuxVM.OSUnmanagedDiskVhdUri, OperatingSystemStateTypes.Generalized)
                                        .WithOSDiskCaching(linuxVM.OSDiskCachingType);
                    foreach (var disk in linuxVM.UnmanagedDataDisks.Values)
                    {
                        creatableDisk.DefineDataDiskImage()
                        .WithLun(disk.Lun)
                        .FromVhd(disk.VhdUri)
                        .WithDiskCaching(disk.CachingType)
                        .WithDiskSizeInGB(disk.Size + 10)         // Resize each data disk image by +10GB
                        .Attach();
                    }
                    var customImage = creatableDisk.Create();
                    Assert.NotNull(customImage.Id);
                    Assert.Equal(customImage.Name, vhdBasedImageName);
                    Assert.False(customImage.IsCreatedFromVirtualMachine);
                    Assert.Null(customImage.SourceVirtualMachineId);
                    Assert.NotNull(customImage.OSDiskImage);
                    Assert.NotNull(customImage.OSDiskImage.BlobUri);
                    Assert.Equal(CachingTypes.ReadWrite, customImage.OSDiskImage.Caching);
                    Assert.Equal(OperatingSystemStateTypes.Generalized, customImage.OSDiskImage.OsState);
                    Assert.Equal(OperatingSystemTypes.Linux, customImage.OSDiskImage.OsType);
                    Assert.NotNull(customImage.DataDiskImages);
                    Assert.Equal(customImage.DataDiskImages.Count, linuxVM.UnmanagedDataDisks.Count);
                    Assert.Equal(customImage.HyperVGeneration, HyperVGenerationTypes.V1);
                    foreach (ImageDataDisk diskImage in customImage.DataDiskImages.Values)
                    {
                        IVirtualMachineUnmanagedDataDisk matchedDisk = null;
                        foreach (var vmDisk in linuxVM.UnmanagedDataDisks.Values)
                        {
                            if (vmDisk.Lun == diskImage.Lun)
                            {
                                matchedDisk = vmDisk;
                                break;
                            }
                        }
                        Assert.NotNull(matchedDisk);
                        Assert.Equal(matchedDisk.CachingType, diskImage.Caching);
                        Assert.Equal(matchedDisk.VhdUri, diskImage.BlobUri);
                        Assert.Equal((long)matchedDisk.Size + 10, (long)diskImage.DiskSizeGB);
                    }
                    var image = computeManager
                                .VirtualMachineCustomImages
                                .GetByResourceGroup(rgName, vhdBasedImageName);
                    Assert.NotNull(image);
                    var images = computeManager
                                 .VirtualMachineCustomImages
                                 .ListByResourceGroup(rgName);
                    Assert.True(images.Count() > 0);

                    // Create virtual machine from custom image
                    //
                    var virtualMachine = computeManager.VirtualMachines
                                         .Define(SdkContext.RandomResourceName("cusvm", 15))
                                         .WithRegion(Location)
                                         .WithNewResourceGroup(rgName)
                                         .WithNewPrimaryNetwork("10.0.0.0/28")
                                         .WithPrimaryPrivateIPAddressDynamic()
                                         .WithoutPrimaryPublicIPAddress()
                                         .WithLinuxCustomImage(image.Id)
                                         .WithRootUsername("javauser")
                                         .WithRootPassword("12NewPA$$w0rd!")
                                         .WithSize(VirtualMachineSizeTypes.StandardD5V2)
                                         .WithOSDiskCaching(CachingTypes.ReadWrite)
                                         .Create();

                    var dataDisks = virtualMachine.DataDisks;
                    Assert.NotNull(dataDisks);
                    Assert.Equal(dataDisks.Count, image.DataDiskImages.Count);

                    //Create a hyperv Gen2 image
                    var creatableDiskGen2 = computeManager
                                            .VirtualMachineCustomImages
                                            .Define(vhdBasedImageName + "Gen2")
                                            .WithRegion(Location)
                                            .WithNewResourceGroup(rgName)
                                            .WithHyperVGeneration(HyperVGenerationTypes.V2)
                                            .WithLinuxFromVhd(linuxVM.OSUnmanagedDiskVhdUri, OperatingSystemStateTypes.Generalized)
                                            .WithOSDiskCaching(linuxVM.OSDiskCachingType);
                    foreach (var disk in linuxVM.UnmanagedDataDisks.Values)
                    {
                        creatableDisk.DefineDataDiskImage()
                        .WithLun(disk.Lun)
                        .FromVhd(disk.VhdUri)
                        .WithDiskCaching(disk.CachingType)
                        .WithDiskSizeInGB(disk.Size + 10)         // Resize each data disk image by +10GB
                        .Attach();
                    }
                    IVirtualMachineCustomImage customImageGen2 = creatableDiskGen2.Create();
                    Assert.NotNull(customImageGen2.Id);
                    Assert.Equal(customImageGen2.Name, vhdBasedImageName + "Gen2");
                    Assert.False(customImageGen2.IsCreatedFromVirtualMachine);
                    Assert.Null(customImageGen2.SourceVirtualMachineId);
                    Assert.NotNull(customImageGen2.OSDiskImage);
                    Assert.NotNull(customImageGen2.OSDiskImage);
                    Assert.Equal(CachingTypes.ReadWrite, customImageGen2.OSDiskImage.Caching);
                    Assert.Equal(OperatingSystemStateTypes.Generalized, customImageGen2.OSDiskImage.OsState);
                    Assert.Equal(OperatingSystemTypes.Linux, customImageGen2.OSDiskImage.OsType);
                    Assert.NotNull(customImageGen2.DataDiskImages);
                    Assert.Equal(0, customImageGen2.DataDiskImages.Count);
                    Assert.Equal(customImageGen2.HyperVGeneration, HyperVGenerationTypes.V2);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 6
0
        public void CanCRUDMongoDBCollection()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var dbName              = SdkContext.RandomResourceName("cosmosdb", 22);
                var rgName              = SdkContext.RandomResourceName("cosmosdbRg", 22);
                var mongoDBName         = SdkContext.RandomResourceName("mongodb", 22);
                var mongoCollectionName = SdkContext.RandomResourceName("mongocollection", 22);
                var region              = Region.USWest;

                var azure = TestHelper.CreateRollupClient();

                try
                {
                    azure.ResourceGroups.Define(rgName).WithRegion(region).Create();
                    var databaseAccount = azure.CosmosDBAccounts.Define(dbName)
                                          .WithRegion(region)
                                          .WithExistingResourceGroup(rgName)
                                          .WithDataModelMongoDB()
                                          .WithStrongConsistency()
                                          .DefineNewMongoDB(mongoDBName)
                                          .WithThroughput(400)
                                          .DefineNewCollection(mongoCollectionName)
                                          .WithThroughput(600)
                                          .WithShardKey("test")
                                          .Attach()
                                          .Attach()
                                          .Create();

                    var mongodbs = databaseAccount.ListMongoDBs().ToList();
                    Assert.Single(mongodbs);

                    var mongodb = mongodbs[0];
                    Assert.Equal(mongoDBName, mongodb.Name);
                    Assert.Equal(400, mongodb.GetThroughputSettings().Throughput);

                    var collections = mongodb.ListCollections().ToList();
                    Assert.Single(collections);

                    var collection = collections[0];
                    Assert.Equal(mongoCollectionName, collection.Name);
                    Assert.Equal(600, collection.GetThroughputSettings().Throughput);
                    Assert.Equal("Hash", collection.ShardKey.GetValueOrDefault("test", "empty"));

                    databaseAccount = databaseAccount.Update()
                                      .UpdateMongoDB(mongoDBName)
                                      .UpdateCollection(mongoCollectionName)
                                      .WithThroughput(500)
                                      .Parent()
                                      .WithThroughput(800)
                                      .Parent()
                                      .Apply();

                    mongodb = databaseAccount.GetMongoDB(mongoDBName);
                    Assert.Equal(800, mongodb.GetThroughputSettings().Throughput);

                    collection = mongodb.GetCollection(mongoCollectionName);
                    Assert.Equal(500, collection.GetThroughputSettings().Throughput);
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.BeginDeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
        /**
         * Azure sample for applying locks to resources
         *
         * Summary ...
         *
         * This sample shows examples of management locks usage on various resources.
         *
         * Details ...
         *
         * 1. Create a number of various resources to apply locks to...
         * 2. Apply various locks to the resources
         * 3. Retrieve and show lock information
         * 4. Remove the locks and clean up
         */

        public static void RunSample(IAzure azure)
        {
            string password    = SdkContext.RandomResourceName("P@s", 14);
            string rgName      = SdkContext.RandomResourceName("rg", 15);
            string vmName      = SdkContext.RandomResourceName("vm", 15);
            string storageName = SdkContext.RandomResourceName("st", 15);
            string diskName    = SdkContext.RandomResourceName("dsk", 15);
            string netName     = SdkContext.RandomResourceName("net", 15);
            Region region      = Region.USEast;

            IResourceGroup  resourceGroup = null;
            IManagementLock lockGroup     = null,
                            lockVM        = null,
                            lockStorage   = null,
                            lockDiskRO    = null,
                            lockDiskDel   = null,
                            lockSubnet    = null;

            try
            {
                //=============================================================
                // Create a shared resource group for all the resources so they can all be deleted together
                //
                resourceGroup = azure.ResourceGroups.Define(rgName)
                                .WithRegion(region)
                                .Create();
                Utilities.Log("Created a new resource group - " + resourceGroup.Id);

                //============================================================
                // Create various resources for demonstrating locks
                //

                // Define a network to apply a lock to
                ICreatable <INetwork> netDefinition = azure.Networks.Define(netName)
                                                      .WithRegion(region)
                                                      .WithExistingResourceGroup(resourceGroup)
                                                      .WithAddressSpace("10.0.0.0/28");

                // Define a managed disk for testing locks on that
                ICreatable <IDisk> diskDefinition = azure.Disks.Define(diskName)
                                                    .WithRegion(region)
                                                    .WithExistingResourceGroup(resourceGroup)
                                                    .WithData()
                                                    .WithSizeInGB(100);

                // Define a VM to apply a lock to
                ICreatable <IVirtualMachine> vmDefinition = azure.VirtualMachines.Define(vmName)
                                                            .WithRegion(region)
                                                            .WithExistingResourceGroup(resourceGroup)
                                                            .WithNewPrimaryNetwork(netDefinition)
                                                            .WithPrimaryPrivateIPAddressDynamic()
                                                            .WithoutPrimaryPublicIPAddress()
                                                            .WithPopularWindowsImage(KnownWindowsVirtualMachineImage.WindowsServer2012Datacenter)
                                                            .WithAdminUsername("tester")
                                                            .WithAdminPassword(password)
                                                            .WithNewDataDisk(diskDefinition, 1, CachingTypes.None)
                                                            .WithSize(VirtualMachineSizeTypes.BasicA1);

                // Define a storage account to apply a lock to
                ICreatable <IStorageAccount> storageDefinition = azure.StorageAccounts.Define(storageName)
                                                                 .WithRegion(region)
                                                                 .WithExistingResourceGroup(resourceGroup);

                // Create resources in parallel to save time
                Utilities.Log("Creating the needed resources...");
                Task.WaitAll(
                    storageDefinition.CreateAsync(),
                    vmDefinition.CreateAsync());
                Utilities.Log("Resources created.");

                IVirtualMachine vm      = (IVirtualMachine)vmDefinition;
                IStorageAccount storage = (IStorageAccount)storageDefinition;
                IDisk           disk    = (IDisk)diskDefinition;
                INetwork        network = vm.GetPrimaryNetworkInterface().PrimaryIPConfiguration.GetNetwork();
                ISubnet         subnet  = network.Subnets.Values.FirstOrDefault();

                //============================================================
                // Create various locks for the created resources
                //

                // Locks can be created serially, and multiple can be applied to the same resource:
                Utilities.Log("Creating locks sequentially...");

                // Apply a ReadOnly lock to the disk
                lockDiskRO = azure.ManagementLocks.Define("diskLockRO")
                             .WithLockedResource(disk)
                             .WithLevel(LockLevel.ReadOnly)
                             .Create();

                // Apply a lock preventing the disk from being deleted
                lockDiskDel = azure.ManagementLocks.Define("diskLockDel")
                              .WithLockedResource(disk)
                              .WithLevel(LockLevel.CanNotDelete)
                              .Create();

                // Locks can also be created in parallel, for better overall performance:
                Utilities.Log("Creating locks in parallel...");

                // Define a subnet lock
                ICreatable <IManagementLock> lockSubnetDef = azure.ManagementLocks.Define("subnetLock")
                                                             .WithLockedResource(subnet.Inner.Id)
                                                             .WithLevel(LockLevel.ReadOnly);

                // Define a VM lock
                ICreatable <IManagementLock> lockVMDef = azure.ManagementLocks.Define("vmlock")
                                                         .WithLockedResource(vm)
                                                         .WithLevel(LockLevel.ReadOnly)
                                                         .WithNotes("vm readonly lock");

                // Define a resource group lock
                ICreatable <IManagementLock> lockGroupDef = azure.ManagementLocks.Define("rglock")
                                                            .WithLockedResource(resourceGroup.Id)
                                                            .WithLevel(LockLevel.CanNotDelete);

                // Define a storage lock
                ICreatable <IManagementLock> lockStorageDef = azure.ManagementLocks.Define("stLock")
                                                              .WithLockedResource(storage)
                                                              .WithLevel(LockLevel.CanNotDelete);

                var created = azure.ManagementLocks.Create(
                    lockVMDef,
                    lockGroupDef,
                    lockStorageDef,
                    lockSubnetDef);

                lockVM      = created.FirstOrDefault(o => o.Key.Equals(lockVMDef.Key, StringComparison.OrdinalIgnoreCase));
                lockStorage = created.FirstOrDefault(o => o.Key.Equals(lockStorageDef.Key, StringComparison.OrdinalIgnoreCase));
                lockGroup   = created.FirstOrDefault(o => o.Key.Equals(lockGroupDef.Key, StringComparison.OrdinalIgnoreCase));
                lockSubnet  = created.FirstOrDefault(o => o.Key.Equals(lockSubnetDef.Key, StringComparison.OrdinalIgnoreCase));

                Utilities.Log("Locks created.");

                //============================================================
                // Retrieve and show lock information
                //

                // Count and show locks (Note: locks returned for a resource include the locks for its resource group and child resources)
                int lockCount = azure.ManagementLocks.ListForResource(vm.Id).Count();
                Utilities.Log("Number of locks applied to the virtual machine: " + lockCount);
                lockCount = azure.ManagementLocks.ListByResourceGroup(resourceGroup.Name).Count();
                Utilities.Log("Number of locks applied to the resource group (includes locks on resources in the group): " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(storage.Id).Count();
                Utilities.Log("Number of locks applied to the storage account: " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(disk.Id).Count();
                Utilities.Log("Number of locks applied to the managed disk: " + lockCount);
                lockCount = azure.ManagementLocks.ListForResource(network.Id).Count();
                Utilities.Log("Number of locks applied to the network (including its subnets): " + lockCount);

                // Locks can be retrieved using their ID
                lockVM      = azure.ManagementLocks.GetById(lockVM.Id);
                lockGroup   = azure.ManagementLocks.GetByResourceGroup(resourceGroup.Name, "rglock");
                lockStorage = azure.ManagementLocks.GetById(lockStorage.Id);
                lockDiskRO  = azure.ManagementLocks.GetById(lockDiskRO.Id);
                lockDiskDel = azure.ManagementLocks.GetById(lockDiskDel.Id);
                lockSubnet  = azure.ManagementLocks.GetById(lockSubnet.Id);

                // Show the locks
                Utilities.Print(lockGroup);
                Utilities.Print(lockVM);
                Utilities.Print(lockDiskDel);
                Utilities.Print(lockDiskRO);
                Utilities.Print(lockStorage);
                Utilities.Print(lockSubnet);

                // List all locks within a subscription
                var locksSubscription = azure.ManagementLocks.List();
                Utilities.Log("Total number of locks within this subscription: " + locksSubscription.Count());
            }
            finally
            {
                try
                {
                    // Clean up (remember to unlock resources before deleting the resource group)
                    azure.ManagementLocks.DeleteByIds(
                        lockGroup.Id,
                        lockVM.Id,
                        lockDiskRO.Id,
                        lockDiskDel.Id,
                        lockStorage.Id,
                        lockSubnet.Id);
                    Utilities.Log("Starting the deletion of the resource group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
        /**
         * This sample shows examples of configuring Metric Alerts for WebApp instance performance monitoring through app service plan.
         *  - Create a App Service plan
         *  - Setup an action group to trigger a notification to the heavy performance alerts
         *  - Create auto-mitigated metric alerts for the App Service plan when
         *    - average CPUPercentage on any of Web App instance (where Instance = *) over the last 5 minutes is above 80%
         */
        public static void RunSample(IAzure azure)
        {
            string storageAccountName = SdkContext.RandomResourceName("saMonitor", 15);
            string rgName             = SdkContext.RandomResourceName("rgMonitor", 15);

            try
            {
                // ============================================================
                // Create an App Service plan
                Utilities.Log("Creating App Service plan");

                var servicePlan = azure.AppServices.AppServicePlans.Define("HighlyAvailableWebApps")
                                  .WithRegion(Region.USEast2)
                                  .WithNewResourceGroup(rgName)
                                  .WithPricingTier(PricingTier.PremiumP1)
                                  .WithOperatingSystem(Microsoft.Azure.Management.AppService.Fluent.OperatingSystem.Windows)
                                  .Create();

                Utilities.Log("App Service plan created:");
                Utilities.Print(servicePlan);

                // ============================================================
                // Create an action group to send notifications in case metric alert condition will be triggered
                var ag = azure.ActionGroups.Define("criticalPerformanceActionGroup")
                         .WithExistingResourceGroup(rgName)
                         .DefineReceiver("tierOne")
                         .WithPushNotification("*****@*****.**")
                         .WithEmail("*****@*****.**")
                         .WithSms("1", "4255655665")
                         .WithVoice("1", "2062066050")
                         .WithWebhook("https://www.weeneedmorepower.performancemonitoring.com")
                         .Attach()
                         .DefineReceiver("tierTwo")
                         .WithEmail("*****@*****.**")
                         .Attach()
                         .Create();
                Utilities.Print(ag);

                // ============================================================
                // Set a trigger to fire each time
                var ma = azure.AlertRules.MetricAlerts.Define("Critical performance alert")
                         .WithExistingResourceGroup(rgName)
                         .WithTargetResource(servicePlan.Id)
                         .WithPeriod(TimeSpan.FromMinutes(5))
                         .WithFrequency(TimeSpan.FromMinutes(1))
                         .WithAlertDetails(3, "This alert rule is for U5 - Single resource-multiple criteria - with dimensions - with star")
                         .WithActionGroups(ag.Id)
                         .DefineAlertCriteria("Metric1")
                         .WithMetricName("CPUPercentage", "Microsoft.Web/serverfarms")
                         .WithCondition(MetricAlertRuleTimeAggregation.Total, MetricAlertRuleCondition.GreaterThan, 80)
                         .WithDimension("Instance", "*")
                         .Attach()
                         .Create();

                Utilities.Print(ma);
            }
            finally
            {
                if (azure.ResourceGroups.GetByName(rgName) != null)
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                else
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }
 ///GENMHASH:233A62609A15DC3B8EB48DD8DB699DDC:5F2825180653A2E415C39BF41FD682D6
 internal NicIPConfigurationImpl WithNewPublicIPAddress(string leafDnsLabel)
 {
     return(WithNewPublicIPAddress(
                PrepareCreatablePublicIP(SdkContext.RandomResourceName("pip", 15), leafDnsLabel)));
 }
Exemplo n.º 10
0
        /**
         * Azure Network sample for managing network security groups -
         *  - Create a network security group for the front end of a subnet
         *  - Create a network security group for the back end of a subnet
         *  - Create Linux virtual machines for the front end and back end
         *  -- Apply network security groups
         *  - List network security groups
         *  - Update a network security group.
         */
        public static void RunSample(IAzure azure)
        {
            string frontEndNSGName         = SdkContext.RandomResourceName("fensg", 24);
            string backEndNSGName          = SdkContext.RandomResourceName("bensg", 24);
            string rgName                  = SdkContext.RandomResourceName("rgNEMS", 24);
            string vnetName                = SdkContext.RandomResourceName("vnet", 24);
            string networkInterfaceName1   = SdkContext.RandomResourceName("nic1", 24);
            string networkInterfaceName2   = SdkContext.RandomResourceName("nic2", 24);
            string publicIPAddressLeafDNS1 = SdkContext.RandomResourceName("pip1", 24);
            string frontEndVMName          = SdkContext.RandomResourceName("fevm", 24);
            string backEndVMName           = SdkContext.RandomResourceName("bevm", 24);

            try
            {
                // Define a virtual network for VMs in this availability set

                Utilities.Log("Creating a virtual network ...");

                var network = azure.Networks.Define(vnetName)
                              .WithRegion(Region.USEast)
                              .WithNewResourceGroup(rgName)
                              .WithAddressSpace("172.16.0.0/16")
                              .DefineSubnet("Front-end")
                              .WithAddressPrefix("172.16.1.0/24")
                              .Attach()
                              .DefineSubnet("Back-end")
                              .WithAddressPrefix("172.16.2.0/24")
                              .Attach()
                              .Create();

                Utilities.Log("Created a virtual network: " + network.Id);
                Utilities.PrintVirtualNetwork(network);

                //============================================================
                // Create a network security group for the front end of a subnet
                // front end subnet contains two rules
                // - ALLOW-SSH - allows SSH traffic into the front end subnet
                // - ALLOW-WEB- allows HTTP traffic into the front end subnet

                Utilities.Log("Creating a security group for the front end - allows SSH and HTTP");
                var frontEndNSG = azure.NetworkSecurityGroups.Define(frontEndNSGName)
                                  .WithRegion(Region.USEast)
                                  .WithNewResourceGroup(rgName)
                                  .DefineRule("ALLOW-SSH")
                                  .AllowInbound()
                                  .FromAnyAddress()
                                  .FromAnyPort()
                                  .ToAnyAddress()
                                  .ToPort(22)
                                  .WithProtocol(SecurityRuleProtocol.Tcp)
                                  .WithPriority(100)
                                  .WithDescription("Allow SSH")
                                  .Attach()
                                  .DefineRule("ALLOW-HTTP")
                                  .AllowInbound()
                                  .FromAnyAddress()
                                  .FromAnyPort()
                                  .ToAnyAddress()
                                  .ToPort(80)
                                  .WithProtocol(SecurityRuleProtocol.Tcp)
                                  .WithPriority(101)
                                  .WithDescription("Allow HTTP")
                                  .Attach()
                                  .Create();

                Utilities.Log("Created a security group for the front end: " + frontEndNSG.Id);
                Utilities.PrintNetworkSecurityGroup(frontEndNSG);

                //============================================================
                // Create a network security group for the back end of a subnet
                // back end subnet contains two rules
                // - ALLOW-SQL - allows SQL traffic only from the front end subnet
                // - DENY-WEB - denies all outbound internet traffic from the back end subnet

                Utilities.Log("Creating a security group for the front end - allows SSH and "
                              + "denies all outbound internet traffic  ");

                var backEndNSG = azure.NetworkSecurityGroups.Define(backEndNSGName)
                                 .WithRegion(Region.USEast)
                                 .WithExistingResourceGroup(rgName)
                                 .DefineRule("ALLOW-SQL")
                                 .AllowInbound()
                                 .FromAddress("172.16.1.0/24")
                                 .FromAnyPort()
                                 .ToAnyAddress()
                                 .ToPort(1433)
                                 .WithProtocol(SecurityRuleProtocol.Tcp)
                                 .WithPriority(100)
                                 .WithDescription("Allow SQL")
                                 .Attach()
                                 .DefineRule("DENY-WEB")
                                 .DenyOutbound()
                                 .FromAnyAddress()
                                 .FromAnyPort()
                                 .ToAnyAddress()
                                 .ToAnyPort()
                                 .WithAnyProtocol()
                                 .WithDescription("Deny Web")
                                 .WithPriority(200)
                                 .Attach()
                                 .Create();

                Utilities.Log("Created a security group for the back end: " + backEndNSG.Id);
                Utilities.PrintNetworkSecurityGroup(backEndNSG);

                Utilities.Log("Creating multiple network interfaces");
                Utilities.Log("Creating network interface 1");

                //========================================================
                // Create a network interface and apply the
                // front end network security group

                Utilities.Log("Creating a network interface for the front end");

                var networkInterface1 = azure.NetworkInterfaces.Define(networkInterfaceName1)
                                        .WithRegion(Region.USEast)
                                        .WithExistingResourceGroup(rgName)
                                        .WithExistingPrimaryNetwork(network)
                                        .WithSubnet("Front-end")
                                        .WithPrimaryPrivateIPAddressDynamic()
                                        .WithNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1)
                                        .WithIPForwarding()
                                        .WithExistingNetworkSecurityGroup(frontEndNSG)
                                        .Create();

                Utilities.Log("Created network interface for the front end");

                Utilities.PrintNetworkInterface(networkInterface1);

                //========================================================
                // Create a network interface and apply the
                // back end network security group

                Utilities.Log("Creating a network interface for the back end");

                var networkInterface2 = azure.NetworkInterfaces.Define(networkInterfaceName2)
                                        .WithRegion(Region.USEast)
                                        .WithExistingResourceGroup(rgName)
                                        .WithExistingPrimaryNetwork(network)
                                        .WithSubnet("Back-end")
                                        .WithPrimaryPrivateIPAddressDynamic()
                                        .WithExistingNetworkSecurityGroup(backEndNSG)
                                        .Create();

                Utilities.PrintNetworkInterface(networkInterface2);

                //=============================================================
                // Create a virtual machine (for the front end)
                // with the network interface that has the network security group for the front end

                Utilities.Log("Creating a Linux virtual machine (for the front end) - "
                              + "with the network interface that has the network security group for the front end");

                var t1 = DateTime.UtcNow;

                var frontEndVM = azure.VirtualMachines.Define(frontEndVMName)
                                 .WithRegion(Region.USEast)
                                 .WithExistingResourceGroup(rgName)
                                 .WithExistingPrimaryNetworkInterface(networkInterface1)
                                 .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                 .WithRootUsername(UserName)
                                 .WithSsh(SshKey)
                                 .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                 .Create();

                var t2 = DateTime.UtcNow;
                Utilities.Log("Created Linux VM: (took "
                              + (t2 - t1).TotalSeconds + " seconds) " + frontEndVM.Id);
                // Print virtual machine details
                Utilities.PrintVirtualMachine(frontEndVM);

                //=============================================================
                // Create a virtual machine (for the back end)
                // with the network interface that has the network security group for the back end

                Utilities.Log("Creating a Linux virtual machine (for the back end) - "
                              + "with the network interface that has the network security group for the back end");

                t1 = DateTime.UtcNow;

                var backEndVM = azure.VirtualMachines.Define(backEndVMName)
                                .WithRegion(Region.USEast)
                                .WithExistingResourceGroup(rgName)
                                .WithExistingPrimaryNetworkInterface(networkInterface2)
                                .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                .WithRootUsername(UserName)
                                .WithSsh(SshKey)
                                .WithSize(VirtualMachineSizeTypes.Parse("Standard_D2a_v4"))
                                .Create();

                t2 = DateTime.UtcNow;
                Utilities.Log("Created a Linux VM: (took "
                              + (t2 - t1).TotalSeconds + " seconds) " + backEndVM.Id);
                Utilities.PrintVirtualMachine(backEndVM);

                //========================================================
                // List network security groups

                Utilities.Log("Walking through network security groups");
                var networkSecurityGroups = azure.NetworkSecurityGroups.ListByResourceGroup(rgName);

                foreach (var networkSecurityGroup in networkSecurityGroups)
                {
                    Utilities.PrintNetworkSecurityGroup(networkSecurityGroup);
                }

                //========================================================
                // Update a network security group

                Utilities.Log("Updating the front end network security group to allow FTP");

                frontEndNSG.Update()
                .DefineRule("ALLOW-FTP")
                .AllowInbound()
                .FromAnyAddress()
                .FromAnyPort()
                .ToAnyAddress()
                .ToPortRange(20, 21)
                .WithProtocol(SecurityRuleProtocol.Tcp)
                .WithDescription("Allow FTP")
                .WithPriority(200)
                .Attach()
                .Apply();

                Utilities.Log("Updated the front end network security group");
                Utilities.PrintNetworkSecurityGroup(frontEndNSG);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception ex)
                {
                    Utilities.Log(ex);
                }
            }
        }
        ///GENMHASH:1C505DCDEFCB5F029B7A60E2375286BF:3FA7D2EF04027DEAAE836DB63A20039B
        internal NicIPConfigurationImpl WithNewPublicIPAddress()
        {
            string name = SdkContext.RandomResourceName("pip", 15);

            return(WithNewPublicIPAddress(PrepareCreatablePublicIP(name, name)));
        }
 ///GENMHASH:73C84BBD3D307731A80C2DAF5F9B5EB0:591AFF02B37C91A947B66FA2CFEFFB51
 internal NicIPConfigurationImpl WithNewNetwork(string addressSpaceCidr)
 {
     return(WithNewNetwork(SdkContext.RandomResourceName("vnet", 20), addressSpaceCidr));
 }
        public void CanCreateImageFromManagedDisk()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var vmName          = SdkContext.RandomResourceName("vm7-", 20);
                var uname           = "juser";
                var password        = "******";
                var resourceManager = TestHelper.CreateRollupClient();
                var computeManager  = TestHelper.CreateComputeManager();
                var rgName          = TestUtilities.GenerateName("rgfluentchash-");
                try
                {
                    var nativeVM = computeManager.VirtualMachines
                                   .Define(vmName)
                                   .WithRegion(Location)
                                   .WithNewResourceGroup(rgName)
                                   .WithNewPrimaryNetwork("10.0.0.0/28")
                                   .WithPrimaryPrivateIPAddressDynamic()
                                   .WithoutPrimaryPublicIPAddress()
                                   .WithLatestLinuxImage("Canonical", "UbuntuServer", "14.04.2-LTS")
                                   .WithRootUsername(uname)
                                   .WithRootPassword(password)
                                   .WithUnmanagedDisks()           /* UN-MANAGED OS and DATA DISKS */
                                   .DefineUnmanagedDataDisk("disk1")
                                   .WithNewVhd(100)
                                   .WithCaching(CachingTypes.ReadWrite)
                                   .Attach()
                                   .WithNewUnmanagedDataDisk(100)
                                   .WithSize(VirtualMachineSizeTypes.StandardDS5V2)
                                   .WithNewStorageAccount(SdkContext.RandomResourceName("stg", 17))
                                   .WithOSDiskCaching(CachingTypes.ReadWrite)
                                   .Create();

                    Assert.False(nativeVM.IsManagedDiskEnabled);
                    var osVhdUri = nativeVM.OSUnmanagedDiskVhdUri;
                    Assert.NotNull(osVhdUri);
                    var dataDisks = nativeVM.UnmanagedDataDisks;
                    Assert.Equal(2, dataDisks.Count);

                    computeManager.VirtualMachines.DeleteById(nativeVM.Id);

                    var osDiskName = SdkContext.RandomResourceName("dsk", 15);
                    // Create managed disk with Os from vm's Os disk
                    //
                    var managedOsDisk = computeManager.Disks.Define(osDiskName)
                                        .WithRegion(Location)
                                        .WithNewResourceGroup(rgName)
                                        .WithLinuxFromVhd(osVhdUri)
                                        .Create();

                    // Create managed disk with Data from vm's lun0 data disk
                    //
                    var dataDiskName1     = SdkContext.RandomResourceName("dsk", 15);
                    var vmNativeDataDisk1 = dataDisks[0];
                    var managedDataDisk1  = computeManager.Disks.Define(dataDiskName1)
                                            .WithRegion(Location)
                                            .WithNewResourceGroup(rgName)
                                            .WithData()
                                            .FromVhd(vmNativeDataDisk1.VhdUri)
                                            .Create();

                    // Create managed disk with Data from vm's lun1 data disk
                    //
                    var dataDiskName2     = SdkContext.RandomResourceName("dsk", 15);
                    var vmNativeDataDisk2 = dataDisks[1];
                    var managedDataDisk2  = computeManager.Disks.Define(dataDiskName2)
                                            .WithRegion(Location)
                                            .WithNewResourceGroup(rgName)
                                            .WithData()
                                            .FromVhd(vmNativeDataDisk2.VhdUri)
                                            .Create();

                    // Create an image from the above managed disks
                    // Note that this is not a direct user scenario, but including this as per CRP team request
                    //
                    var imageName   = SdkContext.RandomResourceName("img", 15);
                    var customImage = computeManager.VirtualMachineCustomImages.Define(imageName)
                                      .WithRegion(Location)
                                      .WithNewResourceGroup(rgName)
                                      .WithLinuxFromDisk(managedOsDisk, OperatingSystemStateTypes.Generalized)
                                      .DefineDataDiskImage()
                                      .WithLun(vmNativeDataDisk1.Lun)
                                      .FromManagedDisk(managedDataDisk1)
                                      .WithDiskCaching(vmNativeDataDisk1.CachingType)
                                      .WithDiskSizeInGB(vmNativeDataDisk1.Size + 10)
                                      .Attach()
                                      .DefineDataDiskImage()
                                      .WithLun(vmNativeDataDisk2.Lun)
                                      .FromManagedDisk(managedDataDisk2)
                                      .WithDiskSizeInGB(vmNativeDataDisk2.Size + 10)
                                      .Attach()
                                      .Create();

                    Assert.NotNull(customImage);
                    Assert.Equal(customImage.Name, imageName, ignoreCase: true);
                    Assert.NotNull(customImage.OSDiskImage);
                    Assert.Equal(OperatingSystemStateTypes.Generalized, customImage.OSDiskImage.OsState);
                    Assert.Equal(OperatingSystemTypes.Linux, customImage.OSDiskImage.OsType);
                    Assert.NotNull(customImage.DataDiskImages);
                    Assert.Equal(2, customImage.DataDiskImages.Count);
                    Assert.Equal(customImage.HyperVGeneration, HyperVGenerationTypes.V1);
                    Assert.Null(customImage.SourceVirtualMachineId);

                    Assert.True(customImage.DataDiskImages.ContainsKey(vmNativeDataDisk1.Lun));
                    Assert.Equal(customImage.DataDiskImages[vmNativeDataDisk1.Lun].Caching, vmNativeDataDisk1.CachingType);
                    Assert.True(customImage.DataDiskImages.ContainsKey(vmNativeDataDisk2.Lun));
                    Assert.Equal(CachingTypes.None, customImage.DataDiskImages[vmNativeDataDisk2.Lun].Caching);

                    foreach (var vmDisk in dataDisks.Values)
                    {
                        Assert.True(customImage.DataDiskImages.ContainsKey(vmDisk.Lun));
                        var diskImage = customImage.DataDiskImages[vmDisk.Lun];
                        Assert.Equal((long)diskImage.DiskSizeGB, vmDisk.Size + 10);
                        Assert.Null(diskImage.BlobUri);
                        Assert.NotNull(diskImage.ManagedDisk);
                        Assert.True(diskImage.ManagedDisk.Id.Equals(managedDataDisk1.Id, StringComparison.OrdinalIgnoreCase) ||
                                    diskImage.ManagedDisk.Id.Equals(managedDataDisk2.Id, StringComparison.OrdinalIgnoreCase));
                    }
                    computeManager.Disks.DeleteById(managedOsDisk.Id);
                    computeManager.Disks.DeleteById(managedDataDisk1.Id);
                    computeManager.Disks.DeleteById(managedDataDisk2.Id);
                    computeManager.VirtualMachineCustomImages.DeleteById(customImage.Id);
                }
                finally
                {
                    try
                    {
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 14
0
        internal async Task <bool> AddAsync(InstanceName instance, string location, string requiredVersion, string sourceUrl, CancellationToken cancellationToken)
        {
            string rgName = instance.ResourceGroupName;

            logger.WriteVerbose($"Checking if Resource Group {rgName} already exists");
            if (!await azure.ResourceGroups.ContainAsync(rgName, cancellationToken))
            {
                if (instance.IsCustom)
                {
                    logger.WriteError($"Resource group {rgName} is custom and cannot be created.");
                    return(false);
                }

                logger.WriteVerbose($"Creating resource group {rgName}");
                await azure.ResourceGroups
                .Define(rgName)
                .WithRegion(location)
                .CreateAsync();

                logger.WriteInfo($"Resource group {rgName} created.");
            }

            // IDEA the template should create a Storage account and/or a Key Vault for Rules' use
            // TODO https://github.com/gjlumsden/AzureFunctionsSlots suggest that slots must be created in template
            var    resourceName = "aggregator.cli.Instances.instance-template.json";
            string armTemplateString;
            var    assembly = Assembly.GetExecutingAssembly();

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    armTemplateString = await reader.ReadToEndAsync();
                }

            var parsedTemplate = JObject.Parse(armTemplateString);

            // sanity checks
            if (parsedTemplate.SelectToken("parameters.appName") == null)
            {
                // not good, blah
                logger.WriteWarning($"Something is wrong with the ARM template");
            }

            string appName        = instance.FunctionAppName;
            var    infoVersion    = GetCustomAttribute <AssemblyInformationalVersionAttribute>();
            var    templateParams = new Dictionary <string, Dictionary <string, object> > {
                { "appName", new Dictionary <string, object> {
                      { "value", appName }
                  } },
                { "aggregatorVersion", new Dictionary <string, object> {
                      { "value", infoVersion.InformationalVersion }
                  } },
                { "hostingPlanSkuName", new Dictionary <string, object> {
                      { "value", "Y1" }
                  } },
                { "hostingPlanSkuTier", new Dictionary <string, object> {
                      { "value", "Dynamic" }
                  } },
            };

            string deploymentName = SdkContext.RandomResourceName("aggregator", 24);

            logger.WriteInfo($"Started deployment (id: {deploymentName})");
            var deployment = await azure.Deployments.Define(deploymentName)
                             .WithExistingResourceGroup(rgName)
                             .WithTemplate(armTemplateString)
                             .WithParameters(templateParams)
                             .WithMode(DeploymentMode.Incremental)
                             .CreateAsync(cancellationToken);

            // poll
            const int pollIntervalInSeconds = 3;
            int       totalDelay            = 0;

            while (!(StringComparer.OrdinalIgnoreCase.Equals(deployment.ProvisioningState, "Succeeded") ||
                     StringComparer.OrdinalIgnoreCase.Equals(deployment.ProvisioningState, "Failed") ||
                     StringComparer.OrdinalIgnoreCase.Equals(deployment.ProvisioningState, "Cancelled")))
            {
                SdkContext.DelayProvider.Delay(pollIntervalInSeconds * 1000);
                totalDelay += pollIntervalInSeconds;
                logger.WriteVerbose($"Deployment running ({totalDelay}s)");
                await deployment.RefreshAsync(cancellationToken);
            }
            logger.WriteInfo($"Deployment {deployment.ProvisioningState}");

            // check runtime package
            var  package = new FunctionRuntimePackage(logger);
            bool ok      = await package.UpdateVersionAsync(requiredVersion, sourceUrl, instance, azure, cancellationToken);

            if (ok)
            {
                var devopsLogonData = DevOpsLogon.Load().connection;
                if (devopsLogonData.Mode == DevOpsTokenType.PAT)
                {
                    logger.WriteVerbose($"Saving Azure DevOps token");
                    ok = await ChangeAppSettingsAsync(instance, devopsLogonData, SaveMode.Default, cancellationToken);

                    if (ok)
                    {
                        logger.WriteInfo($"Azure DevOps token saved");
                    }
                    else
                    {
                        logger.WriteError($"Failed to save Azure DevOps token");
                    }
                }
                else
                {
                    logger.WriteWarning($"Azure DevOps token type {devopsLogonData.Mode} is unsupported");
                    ok = false;
                }
            }
            return(ok);
        }
Exemplo n.º 15
0
        public void CanCreateSqlPrivateEndpoint()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var dbName            = SdkContext.RandomResourceName("cosmosdb", 22);
                var rgName            = SdkContext.RandomResourceName("cosmosdbRg", 22);
                var networkName       = SdkContext.RandomResourceName("network", 22);
                var subnetName        = SdkContext.RandomResourceName("subnet", 22);
                var plsConnectionName = SdkContext.RandomResourceName("plsconnect", 22);
                var pedName           = SdkContext.RandomResourceName("ped", 22);
                var region            = Region.USWest;

                var azure = TestHelper.CreateRollupClient();

                try
                {
                    azure.ResourceGroups.Define(rgName)
                    .WithRegion(region)
                    .Create();

                    var network = azure.Networks.Define(networkName)
                                  .WithRegion(region)
                                  .WithExistingResourceGroup(rgName)
                                  .WithAddressSpace("10.0.0.0/16")
                                  .DefineSubnet(subnetName)
                                  .WithAddressPrefix("10.0.0.0/24")
                                  .WithAccessFromService(ServiceEndpointType.MicrosoftAzureCosmosDB)
                                  .Attach()
                                  .Create();

                    network.Subnets[subnetName].Inner.PrivateEndpointNetworkPolicies    = "Disabled";
                    network.Subnets[subnetName].Inner.PrivateLinkServiceNetworkPolicies = "Disabled";

                    network.Update()
                    .UpdateSubnet(subnetName)
                    .Parent()
                    .Apply();

                    var databaseAccount = azure.CosmosDBAccounts.Define(dbName)
                                          .WithRegion(region)
                                          .WithExistingResourceGroup(rgName)
                                          .WithDataModelSql()
                                          .WithStrongConsistency()
                                          .WithDisableKeyBaseMetadataWriteAccess(true)
                                          .Create();

                    Assert.True(databaseAccount.KeyBasedMetadataWriteAccessDisabled);

                    var privateLinkServiceConnection = new PrivateLinkServiceConnectionInner(name: plsConnectionName)
                    {
                        PrivateLinkServiceId = databaseAccount.Id,
                        GroupIds             = new List <string> {
                            "Sql"
                        },
                        PrivateLinkServiceConnectionState = new PrivateLinkServiceConnectionState("Approved"),
                    };

                    var privateEndpoint = new PrivateEndpointInner(name: pedName)
                    {
                        Location = region.ToString(),
                        Subnet   = network.Subnets[subnetName].Inner,
                        PrivateLinkServiceConnections = new List <PrivateLinkServiceConnectionInner> {
                            privateLinkServiceConnection
                        },
                    };

                    azure.Networks.Manager.Inner.PrivateEndpoints
                    .CreateOrUpdateWithHttpMessagesAsync(rgName, pedName, privateEndpoint).Wait();

                    Assert.Equal("Approved", databaseAccount.GetPrivateEndpointConnection(pedName).PrivateLinkServiceConnectionState.Status);

                    databaseAccount.Update()
                    .UpdatePrivateEndpointConnection(pedName)
                    .WithStatus("Rejected")
                    .WithDescription("Rej")
                    .Parent()
                    .Apply();

                    var connections = databaseAccount.ListPrivateEndpointConnection();
                    Assert.True(connections.ContainsKey(pedName));
                    Assert.Equal("Rejected", connections[pedName].PrivateLinkServiceConnectionState.Status);

                    Assert.Equal(1, databaseAccount.ListPrivateLinkResources().Count);
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.BeginDeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 16
0
        public void UnfinishedTest()
        {
            string vnetName1 = SdkContext.RandomResourceName("vnet1", 20);
            string vnetName2 = SdkContext.RandomResourceName("vnet2", 20);
            string vnet1FrontEndSubnetName    = "frontend";
            string vnet1BackEndSubnetName     = "backend";
            string vnet1FrontEndSubnetNsgName = "frontendnsg";
            string vnet1BackEndSubnetNsgName  = "backendnsg";
            string frontEndVMName             = SdkContext.RandomResourceName("fevm", 24);
            string backEndVMName = SdkContext.RandomResourceName("bevm", 24);
            string publicIPAddressLeafDNSForFrontEndVM = SdkContext.RandomResourceName("pip1", 24);

            INetworkManager manager = TestHelper.CreateNetworkManager();

            string rgName = SdkContext.RandomResourceName("rgNEMV", 24);

            try
            {
                INetworkSecurityGroup backEndSubnetNsg = manager.NetworkSecurityGroups
                                                         .Define(vnet1BackEndSubnetNsgName)
                                                         .WithRegion(Region.USEast)
                                                         .WithExistingResourceGroup(rgName)
                                                         .DefineRule("DenyInternetInComing")
                                                         .DenyInbound()
                                                         .FromAddress("INTERNET")
                                                         .FromAnyPort()
                                                         .ToAnyAddress()
                                                         .ToAnyPort()
                                                         .WithAnyProtocol()
                                                         .Attach()
                                                         .DefineRule("DenyInternetOutGoing")
                                                         .DenyOutbound()
                                                         .FromAnyAddress()
                                                         .FromAnyPort()
                                                         .ToAddress("INTERNET")
                                                         .ToAnyPort()
                                                         .WithAnyProtocol()
                                                         .Attach()
                                                         .Create();

                INetwork virtualNetwork1 = manager.Networks
                                           .Define(vnetName1)
                                           .WithRegion(Region.USEast)
                                           .WithExistingResourceGroup(rgName)
                                           .WithAddressSpace("192.168.0.0/16")
                                           .WithSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24")
                                           .DefineSubnet(vnet1BackEndSubnetName)
                                           .WithAddressPrefix("192.168.2.0/24")
                                           .WithExistingNetworkSecurityGroup(backEndSubnetNsg)
                                           .Attach()
                                           .Create();

                INetworkSecurityGroup frontEndSubnetNsg = manager.NetworkSecurityGroups
                                                          .Define(vnet1FrontEndSubnetNsgName)
                                                          .WithRegion(Region.USEast)
                                                          .WithExistingResourceGroup(rgName)
                                                          .DefineRule("AllowHttpInComing")
                                                          .AllowInbound()
                                                          .FromAddress("INTERNET")
                                                          .FromAnyPort()
                                                          .ToAnyAddress()
                                                          .ToPort(80)
                                                          .WithProtocol(SecurityRuleProtocol.Tcp)
                                                          .Attach()
                                                          .DefineRule("DenyInternetOutGoing")
                                                          .DenyOutbound()
                                                          .FromAnyAddress()
                                                          .FromAnyPort()
                                                          .ToAddress("INTERNET")
                                                          .ToAnyPort()
                                                          .WithAnyProtocol()
                                                          .Attach()
                                                          .Create();

                virtualNetwork1.Update()
                .UpdateSubnet(vnet1FrontEndSubnetName)
                .WithExistingNetworkSecurityGroup(frontEndSubnetNsg)
                .Parent()
                .Apply();

                INetwork virtualNetwork2 = manager.Networks
                                           .Define(vnetName2)
                                           .WithRegion(Region.USEast)
                                           .WithNewResourceGroup(rgName)
                                           .Create();


                foreach (INetwork virtualNetwork in manager.Networks.ListByResourceGroup(rgName))
                {
                }


                manager.Networks.DeleteById(virtualNetwork2.Id);
            }
            finally
            {
                try
                {
                    TestHelper.CreateResourceManager().ResourceGroups.DeleteByName(rgName);
                }
                catch { }
            }
        }
Exemplo n.º 17
0
        public void CanCRUDSqlContainer()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                var dbName           = SdkContext.RandomResourceName("cosmosdb", 22);
                var rgName           = SdkContext.RandomResourceName("cosmosdbRg", 22);
                var sqlDbName        = SdkContext.RandomResourceName("sqldb", 22);
                var sqlContainerName = SdkContext.RandomResourceName("sqlcontainer", 22);
                var region           = Region.USWest;

                var azure = TestHelper.CreateRollupClient();

                try
                {
                    azure.ResourceGroups.Define(rgName).WithRegion(region).Create();

                    var databaseAccount = azure.CosmosDBAccounts.Define(dbName)
                                          .WithRegion(region)
                                          .WithExistingResourceGroup(rgName)
                                          .WithDataModelSql()
                                          .WithStrongConsistency()
                                          .WithAutomaticFailoverEnabled(true)
                                          .DefineNewSqlDatabase(sqlDbName)
                                          .WithThroughput(1000)
                                          .DefineNewSqlContainer(sqlContainerName)
                                          .WithThroughput(400)
                                          .DefineIndexingPolicy()
                                          .WithIndexingMode(IndexingMode.Consistent)
                                          .WithIncludedPath("/*")
                                          .WithExcludedPath("/myPathToNotIndex/*")
                                          .WithNewCompositeIndexList()
                                          .WithCompositePath("/myOrderByPath1", CompositePathSortOrder.Ascending)
                                          .WithCompositePath("/myOrderByPath2", CompositePathSortOrder.Descending)
                                          .Attach()
                                          .Attach()
                                          .WithPartitionKey(PartitionKind.Hash, null)
                                          .WithPartitionKeyPath("/myPartitionKey")
                                          .WithStoredProcedure("test", "function test(){}")
                                          .WithUserDefinedFunction("test", "function test(){}")
                                          .WithTrigger("test", "function test(){}", TriggerType.Pre, TriggerOperation.All)
                                          .Attach()
                                          .Attach()
                                          .Create();

                    Assert.True(databaseAccount.AutomaticFailoverEnabled);

                    var sqldbs = databaseAccount.ListSqlDatabases().ToList();
                    Assert.Single(sqldbs);

                    var sqldb = sqldbs[0];
                    Assert.Equal(sqlDbName, sqldb.Name);
                    Assert.Equal(1000, sqldb.GetThroughputSettings().Throughput);

                    var containers = sqldb.ListSqlContainers().ToList();
                    Assert.Single(containers);

                    var container = containers[0];
                    Assert.Equal(sqlContainerName, container.Name);
                    Assert.Equal(400, container.GetThroughputSettings().Throughput);
                    Assert.Equal(IndexingMode.Consistent, container.IndexingPolicy.IndexingMode);
                    Assert.NotNull(container.IndexingPolicy.IncludedPaths.Single(element => element.Path == "/*"));
                    Assert.NotNull(container.IndexingPolicy.ExcludedPaths.Single(element => element.Path == "/myPathToNotIndex/*"));
                    Assert.Equal(1, container.IndexingPolicy.CompositeIndexes.Count);
                    Assert.Equal(2, container.IndexingPolicy.CompositeIndexes[0].Count);
                    Assert.True(container.PartitionKey.Paths.Contains("/myPartitionKey"));
                    Assert.Equal(PartitionKind.Hash, container.PartitionKey.Kind);
                    Assert.NotNull(container.GetStoredProcedure("test"));
                    Assert.NotNull(container.GetUserDefinedFunction("test"));
                    Assert.NotNull(container.GetTrigger("test"));

                    databaseAccount = databaseAccount.Update()
                                      .WithAutomaticFailoverEnabled(false)
                                      .UpdateSqlDatabase(sqlDbName)
                                      .WithThroughput(800)
                                      .UpdateSqlContainer(sqlContainerName)
                                      .WithThroughput(600)
                                      .UpdateIndexingPolicy()
                                      .WithoutExcludedPath("/myPathToNotIndex/*")
                                      .Parent()
                                      .Parent()
                                      .Parent()
                                      .Apply();
                    Assert.False(databaseAccount.AutomaticFailoverEnabled);

                    sqldb = databaseAccount.GetSqlDatabase(sqlDbName);
                    Assert.Equal(800, sqldb.GetThroughputSettings().Throughput);

                    container = sqldb.GetSqlContainer(sqlContainerName);
                    Assert.Equal(600, container.GetThroughputSettings().Throughput);
                    Assert.Null(container.IndexingPolicy.ExcludedPaths.SingleOrDefault(element => element.Path == "/myPathToNotIndex/*"));
                }
                finally
                {
                    try
                    {
                        azure.ResourceGroups.BeginDeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
Exemplo n.º 18
0
        /**
         * Azure Service Bus basic scenario sample.
         * - Create namespace.
         * - Create a service bus subscription in the topic with session and dead-letter enabled.
         * - Create another subscription in the topic with auto deletion of idle entities.
         * - Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription.
         * - Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule.
         * - Get the keys from default authorization rule to connect to topic.
         * - Send a "Hello" message to topic using Data plan sdk for Service Bus.
         * - Delete a topic
         * - Delete namespace
         */
        public static void RunSample(IAzure azure)
        {
            var rgName            = SdkContext.RandomResourceName("rgSB04_", 24);
            var namespaceName     = SdkContext.RandomResourceName("namespace", 20);
            var topic1Name        = SdkContext.RandomResourceName("topic1_", 24);
            var topic2Name        = SdkContext.RandomResourceName("topic2_", 24);
            var subscription1Name = SdkContext.RandomResourceName("subs_", 24);
            var subscription2Name = SdkContext.RandomResourceName("subs_", 24);
            var subscription3Name = SdkContext.RandomResourceName("subs_", 24);
            var sendRuleName      = "SendRule";
            var manageRuleName    = "ManageRule";

            try
            {
                //============================================================
                // Create a namespace.

                Utilities.Log("Creating name space " + namespaceName + " in resource group " + rgName + "...");

                var serviceBusNamespace = azure.ServiceBusNamespaces
                                          .Define(namespaceName)
                                          .WithRegion(Region.USWest)
                                          .WithNewResourceGroup(rgName)
                                          .WithSku(NamespaceSku.PremiumCapacity1)
                                          .WithNewTopic(topic1Name, 1024)
                                          .Create();

                Utilities.Log("Created service bus " + serviceBusNamespace.Name);
                Utilities.Print(serviceBusNamespace);

                Utilities.Log("Created topic following topic along with namespace " + namespaceName);

                var firstTopic = serviceBusNamespace.Topics.GetByName(topic1Name);
                Utilities.Print(firstTopic);

                //============================================================
                // Create a service bus subscription in the topic with session and dead-letter enabled.

                Utilities.Log("Creating subscription " + subscription1Name + " in topic " + topic1Name + "...");
                var firstSubscription = firstTopic.Subscriptions.Define(subscription1Name)
                                        .WithSession()
                                        .WithDefaultMessageTTL(TimeSpan.FromMinutes(20))
                                        .WithMessageMovedToDeadLetterSubscriptionOnMaxDeliveryCount(20)
                                        .WithExpiredMessageMovedToDeadLetterSubscription()
                                        .WithMessageMovedToDeadLetterSubscriptionOnFilterEvaluationException()
                                        .Create();
                Utilities.Log("Created subscription " + subscription1Name + " in topic " + topic1Name + "...");

                Utilities.Print(firstSubscription);

                //============================================================
                // Create another subscription in the topic with auto deletion of idle entities.
                Utilities.Log("Creating another subscription " + subscription2Name + " in topic " + topic1Name + "...");

                var secondSubscription = firstTopic.Subscriptions.Define(subscription2Name)
                                         .WithSession()
                                         .WithDeleteOnIdleDurationInMinutes(20)
                                         .Create();
                Utilities.Log("Created subscription " + subscription2Name + " in topic " + topic1Name + "...");

                Utilities.Print(secondSubscription);

                //============================================================
                // Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription.

                Utilities.Log("Creating second topic " + topic2Name + ", with De-duplication and AutoDeleteOnIdle features...");

                var secondTopic = serviceBusNamespace.Topics.Define(topic2Name)
                                  .WithNewSendRule(sendRuleName)
                                  .WithPartitioning()
                                  .WithNewSubscription(subscription3Name)
                                  .Create();

                Utilities.Log("Created second topic in namespace");

                Utilities.Print(secondTopic);

                Utilities.Log("Creating following authorization rules in second topic ");

                var authorizationRules = secondTopic.AuthorizationRules.List();
                foreach (var authorizationRule in authorizationRules)
                {
                    Utilities.Print(authorizationRule);
                }

                //============================================================
                // Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule.
                Utilities.Log("Updating second topic " + topic2Name + "...");

                secondTopic = secondTopic.Update()
                              .WithDeleteOnIdleDurationInMinutes(5)
                              .WithoutAuthorizationRule(sendRuleName)
                              .WithNewManageRule(manageRuleName)
                              .Apply();

                Utilities.Log("Updated second topic to change its auto deletion time");

                Utilities.Print(secondTopic);
                Utilities.Log("Updated  following authorization rules in second topic, new list of authorization rules are ");

                authorizationRules = secondTopic.AuthorizationRules.List();
                foreach (var authorizationRule in  authorizationRules)
                {
                    Utilities.Print(authorizationRule);
                }

                //=============================================================
                // Get connection string for default authorization rule of namespace

                var namespaceAuthorizationRules = serviceBusNamespace.AuthorizationRules.List();
                Utilities.Log("Number of authorization rule for namespace :" + namespaceAuthorizationRules.Count());


                foreach (var namespaceAuthorizationRule in  namespaceAuthorizationRules)
                {
                    Utilities.Print(namespaceAuthorizationRule);
                }

                Utilities.Log("Getting keys for authorization rule ...");

                var keys = namespaceAuthorizationRules.FirstOrDefault().GetKeys();
                Utilities.Print(keys);

                //=============================================================
                // Send a message to topic.
                Utilities.SendMessageToTopic(keys.PrimaryConnectionString, topic1Name, "Hello");
                //=============================================================
                // Delete a topic and namespace
                Utilities.Log("Deleting topic " + topic1Name + "in namespace " + namespaceName + "...");
                serviceBusNamespace.Topics.DeleteByName(topic1Name);
                Utilities.Log("Deleted topic " + topic1Name + "...");

                Utilities.Log("Deleting namespace " + namespaceName + "...");
                // This will delete the namespace and topic within it.
                try
                {
                    azure.ServiceBusNamespaces.DeleteById(serviceBusNamespace.Id);
                }
                catch (Exception)
                {
                }
                Utilities.Log("Deleted namespace " + namespaceName + "...");
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (NullReferenceException)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
                catch (Exception g)
                {
                    Utilities.Log(g);
                }
            }
        }
        /**
         * This sample shows examples of retrieving metrics and activity logs for Storage Account.
         *  - List all metric definitions available for a storage account
         *  - Retrieve and show metrics for the past 7 days for Transactions where
         *    - Api name was 'PutBlob' and
         *    - response type was 'Success' and
         *    - Geo type was 'Primary'
         *  -  Retrieve and show all activity logs for the past 7 days for the same Storage account.
         */

        public static void RunSample(IAzure azure)
        {
            string storageAccountName = SdkContext.RandomResourceName("saMonitor", 15);
            string rgName             = SdkContext.RandomResourceName("rgMonitor", 15);

            try
            {
                // ============================================================
                // Create a storage account

                Utilities.Log("Creating a Storage Account");

                var storageAccount = azure.StorageAccounts.Define(storageAccountName)
                                     .WithRegion(Region.USEast)
                                     .WithNewResourceGroup(rgName)
                                     .WithBlobStorageAccountKind()
                                     .WithAccessTier(AccessTier.Cool)
                                     .Create();

                Utilities.Log("Created a Storage Account:");
                Utilities.PrintStorageAccount(storageAccount);

                var storageAccountKeys      = storageAccount.GetKeys();
                var storageConnectionString = $"DefaultEndpointsProtocol=http;AccountName={storageAccount.Name};AccountKey={storageAccountKeys.First().Value}";

                // Add some blob transaction events
                AddBlobTransactions(storageConnectionString);

                DateTime recordDateTime = DateTime.Now;
                // get metric definitions for storage account.
                foreach (var metricDefinition in azure.MetricDefinitions.ListByResource(storageAccount.Id))
                {
                    // find metric definition for Transactions
                    if (metricDefinition.Name.LocalizedValue.Equals("transactions", StringComparison.OrdinalIgnoreCase))
                    {
                        // get metric records
                        var metricCollection = metricDefinition.DefineQuery()
                                               .StartingFrom(recordDateTime.AddDays(-7))
                                               .EndsBefore(recordDateTime)
                                               .WithAggregation("Average")
                                               .WithInterval(TimeSpan.FromMinutes(5))
                                               .WithOdataFilter("apiName eq 'PutBlob' and responseType eq 'Success' and geoType eq 'Primary'")
                                               .Execute();

                        Utilities.Log("Metrics for '" + storageAccount.Id + "':");
                        Utilities.Log("Query time: " + metricCollection.Timespan);
                        Utilities.Log("Time Grain: " + metricCollection.Interval);
                        Utilities.Log("Cost: " + metricCollection.Cost);

                        foreach (var metric in metricCollection.Metrics)
                        {
                            Utilities.Log("\tMetric: " + metric.Name.LocalizedValue);
                            Utilities.Log("\tType: " + metric.Type);
                            Utilities.Log("\tUnit: " + metric.Unit);
                            Utilities.Log("\tTime Series: ");
                            foreach (var timeElement in metric.Timeseries)
                            {
                                Utilities.Log("\t\tMetadata: ");
                                foreach (var metadata in timeElement.Metadatavalues)
                                {
                                    Utilities.Log("\t\t\t" + metadata.Name.LocalizedValue + ": " + metadata.Value);
                                }
                                Utilities.Log("\t\tData: ");
                                foreach (var data in timeElement.Data)
                                {
                                    Utilities.Log("\t\t\t" + data.TimeStamp
                                                  + " : (Min) " + data.Minimum
                                                  + " : (Max) " + data.Maximum
                                                  + " : (Avg) " + data.Average
                                                  + " : (Total) " + data.Total
                                                  + " : (Count) " + data.Count);
                                }
                            }
                        }
                        break;
                    }
                }

                // get activity logs for the same period.
                var logs = azure.ActivityLogs.DefineQuery()
                           .StartingFrom(recordDateTime.AddDays(-7))
                           .EndsBefore(recordDateTime)
                           .WithAllPropertiesInResponse()
                           .FilterByResource(storageAccount.Id)
                           .Execute();

                Utilities.Log("Activity logs for the Storage Account:");

                foreach (var eventData in logs)
                {
                    Utilities.Log("\tEvent: " + eventData.EventName?.LocalizedValue);
                    Utilities.Log("\tOperation: " + eventData.OperationName?.LocalizedValue);
                    Utilities.Log("\tCaller: " + eventData.Caller);
                    Utilities.Log("\tCorrelationId: " + eventData.CorrelationId);
                    Utilities.Log("\tSubscriptionId: " + eventData.SubscriptionId);
                }
            }
            finally
            {
                if (azure.ResourceGroups.GetByName(rgName) != null)
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                else
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }