示例#1
0
        /// <summary>
        /// Creates a new resource group and deployment using the passed template file option which
        /// can be user customized or from gallery templates.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created resource group</returns>
        public virtual PSResourceGroup CreatePSResourceGroup(CreatePSResourceGroupParameters parameters)
        {
            bool createDeployment = !string.IsNullOrEmpty(parameters.GalleryTemplateIdentity) || !string.IsNullOrEmpty(parameters.TemplateFile);
            bool resourceExists   = ResourceManagementClient.ResourceGroups.CheckExistence(parameters.ResourceGroupName).Exists;

            ResourceGroup resourceGroup = null;
            Action        createOrUpdateResourceGroup = () =>
            {
                resourceGroup = CreateOrUpdateResourceGroup(parameters.ResourceGroupName, parameters.Location, parameters.Tag);
                WriteVerbose(string.Format("Created resource group '{0}' in location '{1}'", resourceGroup.Name, resourceGroup.Location));

                if (createDeployment)
                {
                    ExecuteDeployment(parameters);
                }
            };

            if (resourceExists && !parameters.Force)
            {
                parameters.ConfirmAction(parameters.Force,
                                         ProjectResources.ResourceGroupAlreadyExists,
                                         ProjectResources.NewResourceGroupMessage,
                                         parameters.DeploymentName,
                                         createOrUpdateResourceGroup);
                resourceGroup = ResourceManagementClient.ResourceGroups.Get(parameters.ResourceGroupName).ResourceGroup;
            }
            else
            {
                createOrUpdateResourceGroup();
            }

            return(resourceGroup.ToPSResourceGroup(this, true));
        }
        /// <summary>
        /// Creates a new resource group and deployment using the passed template file option which
        /// can be user customized or from gallery templates.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created resource group</returns>
        public virtual PSResourceGroup CreatePSResourceGroup(CreatePSResourceGroupParameters parameters)
        {
            bool resourceExists = ResourceManagementClient.ResourceGroups.CheckExistence(parameters.ResourceGroupName).Exists;

            ResourceGroupExtended resourceGroup = null;
            Action createOrUpdateResourceGroup = () =>
            {
                resourceGroup = CreateOrUpdateResourceGroup(parameters.ResourceGroupName, parameters.Location, parameters.Tag);
                WriteVerbose(string.Format("Created resource group '{0}' in location '{1}'", resourceGroup.Name, resourceGroup.Location));
            };

            if (resourceExists && !parameters.Force)
            {
                parameters.ConfirmAction(parameters.Force,
                    ProjectResources.ResourceGroupAlreadyExists,
                    ProjectResources.NewResourceGroupMessage,
                    parameters.DeploymentName,
                    createOrUpdateResourceGroup);
                resourceGroup = ResourceManagementClient.ResourceGroups.Get(parameters.ResourceGroupName).ResourceGroup;
            }
            else
            {
                createOrUpdateResourceGroup();
            }

            return resourceGroup.ToPSResourceGroup(this, true);
        }
        public void CreatesNewPSResourceGroup()
        {
            CreatePSResourceGroupParameters expectedParameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                TemplateFile = templateFile,
                DeploymentName = deploymentName,
                Tag = tags
            };
            CreatePSResourceGroupParameters actualParameters = new CreatePSResourceGroupParameters();
            PSResourceGroup expected = new PSResourceGroup()
            {
                Location = expectedParameters.Location,
                ResourceGroupName = expectedParameters.ResourceGroupName,
                Resources = new List<PSResource>() { new PSResource() { Name = "resource1" } },
                Tags = expectedParameters.Tag
            };
            resourcesClientMock.Setup(f => f.CreatePSResourceGroup(It.IsAny<CreatePSResourceGroupParameters>()))
                .Returns(expected)
                .Callback((CreatePSResourceGroupParameters p) => { actualParameters = p; });

            cmdlet.Name = expectedParameters.ResourceGroupName;
            cmdlet.Location = expectedParameters.Location;
            cmdlet.Tag = expectedParameters.Tag;

            cmdlet.ExecuteCmdlet();

            Assert.Equal(expectedParameters.ResourceGroupName, actualParameters.ResourceGroupName);
            Assert.Equal(expectedParameters.Location, actualParameters.Location);
            Assert.Equal(expectedParameters.Tag, actualParameters.Tag);

            commandRuntimeMock.Verify(f => f.WriteObject(expected), Times.Once());
        }
        protected override void ProcessRecord()
        {
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters
            {
                ResourceGroupName = Name,
                Location = Location,
                Force = Force.IsPresent,
                Tag = Tag,
                ConfirmAction = ConfirmAction
            };

            WriteObject(ResourcesClient.CreatePSResourceGroup(parameters));
        }
        public override void ExecuteCmdlet()
        {
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters
            {
                ResourceGroupName = Name,
                Location = Location,
                Force = Force.IsPresent,
                Tag = Tag,
                ConfirmAction = ConfirmAction
            };

            WriteObject(ResourcesClient.CreatePSResourceGroup(parameters));
        }
        protected override void ProcessRecord()
        {
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters
            {
                ResourceGroupName = Name,
                Location = Location,
                Force = Force.IsPresent,
                Tag = Tag,
                ConfirmAction = ConfirmAction
            };

            WriteWarning("The output object of this cmdlet will be modified in a future release.");
            WriteObject(ResourcesClient.CreatePSResourceGroup(parameters));
        }
        public override void ExecuteCmdlet()
        {
            WriteWarning("The output object type of this cmdlet will be modified in a future release.");
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters
            {
                ResourceGroupName = Name,
                Location = Location,
                Force = Force.IsPresent,
                Tag = Tag,
                ConfirmAction = ConfirmAction
            };

            WriteObject(ResourcesClient.CreatePSResourceGroup(parameters));
        }
        public override void ExecuteCmdlet()
        {
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = Name,
                Location = Location,
                DeploymentName = DeploymentName,
                GalleryTemplateIdentity = GalleryTemplateIdentity,
                TemplateFile = TemplateUri ?? this.TryResolvePath(TemplateFile),
                TemplateParameterObject = GetTemplateParameterObject(TemplateParameterObject),
                TemplateVersion = TemplateVersion,
                StorageAccountName = StorageAccountName,
                Force = Force.IsPresent,
                ConfirmAction = ConfirmAction
            };

            WriteObject(ResourcesClient.CreatePSResourceGroup(parameters));
        }
        public void CreatesNewPSResourceGroupWithUserTemplate()
        {
            CreatePSResourceGroupParameters expectedParameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                TemplateFile = templateFile,
                DeploymentName = deploymentName,
                StorageAccountName = storageAccountName,
                TemplateVersion = "1.0"
            };
            CreatePSResourceGroupParameters actualParameters = new CreatePSResourceGroupParameters();
            PSResourceGroup expected = new PSResourceGroup()
            {
                Location = expectedParameters.Location,
                ResourceGroupName = expectedParameters.ResourceGroupName,
                Resources = new List<PSResource>() { new PSResource() { Name = "resource1" } }
            };
            resourcesClientMock.Setup(f => f.CreatePSResourceGroup(It.IsAny<CreatePSResourceGroupParameters>()))
                .Returns(expected)
                .Callback((CreatePSResourceGroupParameters p) => { actualParameters = p; });

            cmdlet.Name = expectedParameters.ResourceGroupName;
            cmdlet.Location = expectedParameters.Location;
            cmdlet.TemplateFile = expectedParameters.TemplateFile;
            cmdlet.DeploymentName = expectedParameters.DeploymentName;
            cmdlet.TemplateVersion = expectedParameters.TemplateVersion;

            cmdlet.ExecuteCmdlet();

            Assert.Equal(expectedParameters.ResourceGroupName, actualParameters.ResourceGroupName);
            Assert.Equal(expectedParameters.Location, actualParameters.Location);
            Assert.Equal(expectedParameters.DeploymentName, actualParameters.DeploymentName);
            Assert.Equal(expectedParameters.GalleryTemplateIdentity, actualParameters.GalleryTemplateIdentity);
            Assert.Equal(expectedParameters.TemplateFile, actualParameters.TemplateFile);
            Assert.NotNull(actualParameters.TemplateParameterObject);
            Assert.Equal(expectedParameters.TemplateVersion, actualParameters.TemplateVersion);
            Assert.Equal(null, actualParameters.StorageAccountName);

            commandRuntimeMock.Verify(f => f.WriteObject(expected), Times.Once());
        }
 public override void ExecuteCmdlet()
 {
     CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters
     {
         ResourceGroupName = Name,
         Location = Location,
         DeploymentName = DeploymentName,
         GalleryTemplateIdentity = GalleryTemplateIdentity,
         TemplateFile = TemplateUri ?? this.TryResolvePath(TemplateFile),
         TemplateParameterObject = GetTemplateParameterObject(TemplateParameterObject),
         TemplateVersion = TemplateVersion,
         StorageAccountName = StorageAccountName,
         Force = Force.IsPresent,
         Tag = Tag,
         ConfirmAction = ConfirmAction
     };
     if(!string.IsNullOrEmpty(DeploymentName) || !string.IsNullOrEmpty(GalleryTemplateIdentity) || !string.IsNullOrEmpty(TemplateFile)
         || !string.IsNullOrEmpty(TemplateVersion) || TemplateParameterObject != null || !string.IsNullOrEmpty(StorageAccountName))
     {
         WriteWarning("The deployment parameters in New-AzureResourceGroup cmdlet is being deprecated and will be removed in a future release. Please use New-AzureResourceGroupDeployment to submit deployments.");
     }
     WriteWarning("The output object of this cmdlet will be modified in a future release.");
     WriteObject(ResourcesClient.CreatePSResourceGroup(parameters));
 }
        public void NewResourceGroupWithDeploymentSucceeds()
        {
            Uri templateUri = new Uri("http://templateuri.microsoft.com");
            Deployment deploymentFromGet = new Deployment();
            Deployment deploymentFromValidate = new Deployment();
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                DeploymentName = deploymentName,
                TemplateFile = templateFile,
                StorageAccountName = storageAccountName,
                ConfirmAction = ConfirmAction
            };
            resourceGroupMock.Setup(f => f.CheckExistenceAsync(parameters.ResourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupExistsResult
                {
                    Exists = false
                }));

            resourceGroupMock.Setup(f => f.CreateOrUpdateAsync(
                parameters.ResourceGroupName,
                It.IsAny<ResourceGroup>(),
                new CancellationToken()))
                    .Returns(Task.Factory.StartNew(() => new ResourceGroupCreateOrUpdateResult
                    {
                        ResourceGroup = new ResourceGroupExtended() { Name = parameters.ResourceGroupName, Location = parameters.Location }
                    }));
            resourceGroupMock.Setup(f => f.GetAsync(resourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupGetResult
                {
                    ResourceGroup = new ResourceGroupExtended() { Location = resourceGroupLocation }
                }));
            deploymentsMock.Setup(f => f.CreateOrUpdateAsync(resourceGroupName, deploymentName, It.IsAny<Deployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsCreateResult
                {
                    RequestId = requestId
                }))
                .Callback((string name, string dName, Deployment bDeploy, CancellationToken token) => { deploymentFromGet = bDeploy; });
            deploymentsMock.Setup(f => f.GetAsync(resourceGroupName, deploymentName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                    {
                        Deployment = new DeploymentExtended()
                            {
                                Name = deploymentName,
                                Properties = new DeploymentPropertiesExtended()
                                {
                                    Mode = DeploymentMode.Incremental,
                                    CorrelationId = "123",
                                    ProvisioningState = ProvisioningState.Succeeded
                                },
                            }
                    }
                ));

            deploymentsMock.Setup(f => f.ValidateAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<Deployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentValidateResponse
                {
                    IsValid = true,
                    Error = new ResourceManagementErrorWithDetails()
                }))
                .Callback((string rg, string dn, Deployment d, CancellationToken c) => { deploymentFromValidate = d; });
            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<GenericResourceExtended>() { new GenericResourceExtended() { Name = "website" } });
            deploymentOperationsMock.Setup(f => f.ListAsync(resourceGroupName, deploymentName, null, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        new DeploymentOperation()
                        {
                            OperationId = Guid.NewGuid().ToString(),
                            Properties = new DeploymentOperationProperties()
                            {
                                ProvisioningState = ProvisioningState.Succeeded,
                                TargetResource = new TargetResource()
                                {
                                    ResourceType = "Microsoft.Website",
                                    ResourceName = resourceName
                                }
                            }
                        }
                    }
                }));

            PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);
            deploymentsMock.Verify((f => f.CreateOrUpdateAsync(resourceGroupName, deploymentName, deploymentFromGet, new CancellationToken())), Times.Once());
            Assert.Equal(parameters.ResourceGroupName, result.ResourceGroupName);
            Assert.Equal(parameters.Location, result.Location);
            Assert.Equal(1, result.Resources.Count);

            Assert.Equal(DeploymentMode.Incremental, deploymentFromGet.Properties.Mode);
            Assert.NotNull(deploymentFromGet.Properties.Template);

            progressLoggerMock.Verify(
                f => f(string.Format("Resource {0} '{1}' provisioning status is {2}",
                        "Microsoft.Website",
                        resourceName,
                        ProvisioningState.Succeeded.ToLower())),
                Times.Once());
        }
        public void NewResourceGroupFailsWithInvalidDeployment()
        {
            Uri templateUri = new Uri("http://templateuri.microsoft.com");
            BasicDeployment deploymentFromGet = new BasicDeployment();
            BasicDeployment deploymentFromValidate = new BasicDeployment();
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                DeploymentName = deploymentName,
                TemplateFile = templateFile,
                StorageAccountName = storageAccountName,
                ConfirmAction = ConfirmAction
            };
            resourceGroupMock.Setup(f => f.CheckExistenceAsync(parameters.ResourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupExistsResult
                {
                    Exists = false
                }));

            resourceGroupMock.Setup(f => f.CreateOrUpdateAsync(
                parameters.ResourceGroupName,
                It.IsAny<BasicResourceGroup>(),
                new CancellationToken()))
                    .Returns(Task.Factory.StartNew(() => new ResourceGroupCreateOrUpdateResult
                    {
                        ResourceGroup = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
                    }));
            resourceGroupMock.Setup(f => f.GetAsync(resourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupGetResult
                {
                    ResourceGroup = new ResourceGroup() { Location = resourceGroupLocation }
                }));
            deploymentsMock.Setup(f => f.CreateOrUpdateAsync(resourceGroupName, deploymentName, It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsCreateResult
                {
                    RequestId = requestId
                }))
                .Callback((string name, string dName, BasicDeployment bDeploy, CancellationToken token) => { deploymentFromGet = bDeploy; });
            deploymentsMock.Setup(f => f.GetAsync(resourceGroupName, deploymentName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = new Deployment
                        {
                            Name = deploymentName,
                            Properties = new DeploymentProperties()
                            {
                                Mode = DeploymentMode.Incremental,
                                ProvisioningState = ProvisioningState.Succeeded
                            },
                        }
                }));
            deploymentsMock.Setup(f => f.ValidateAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentValidateResponse
                {
                    Error = new ResourceManagementErrorWithDetails()
                        {
                            Code = "404",
                            Message = "Awesome error message",
                            Target = "Bad deployment"
                        }
                }))
                .Callback((string rg, string dn, BasicDeployment d, CancellationToken c) => { deploymentFromValidate = d; });
            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<Resource>() { new Resource() { Name = "website" } });
            deploymentOperationsMock.Setup(f => f.ListAsync(resourceGroupName, deploymentName, null, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        new DeploymentOperation()
                        {
                            OperationId = Guid.NewGuid().ToString(),
                            Properties = new DeploymentOperationProperties()
                            {
                                ProvisioningState = ProvisioningState.Succeeded,
                                TargetResource = new TargetResource()
                                {
                                    ResourceName = resourceName,
                                    ResourceType = "Microsoft.Website"
                                }
                            }
                        }
                    }
                }));

            Assert.Throws<ArgumentException>(() => resourcesClient.CreatePSResourceGroup(parameters));
        }
        public void NewResourceGroupWithoutDeploymentSucceeds()
        {
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                ConfirmAction = ConfirmAction
            };
            resourceGroupMock.Setup(f => f.CheckExistenceAsync(parameters.ResourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupExistsResult
                {
                    Exists = false
                }));

            resourceGroupMock.Setup(f => f.CreateOrUpdateAsync(
                parameters.ResourceGroupName,
                It.IsAny<BasicResourceGroup>(),
                new CancellationToken()))
                    .Returns(Task.Factory.StartNew(() => new ResourceGroupCreateOrUpdateResult
                    {
                        ResourceGroup = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
                    }));
            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<Resource>());

            PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);

            Assert.Equal(parameters.ResourceGroupName, result.ResourceGroupName);
            Assert.Equal(parameters.Location, result.Location);
            Assert.Empty(result.Resources);
        }
        public void NewResourceGroupWithGalleryTemplateAndWithoutStorageAccountNameSucceeds()
        {
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                ConfirmAction = ConfirmAction,
                GalleryTemplateIdentity = "templateFile"
            };
            galleryTemplatesClientMock.Setup(f => f.GetGalleryTemplateFile("templateFile")).Returns("http://microsoft.com");
            resourceGroupMock.Setup(f => f.CheckExistenceAsync(parameters.ResourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupExistsResult
                {
                    Exists = false
                }));

            resourceGroupMock.Setup(f => f.CreateOrUpdateAsync(
                parameters.ResourceGroupName,
                It.IsAny<BasicResourceGroup>(),
                new CancellationToken()))
                    .Returns(Task.Factory.StartNew(() => new ResourceGroupCreateOrUpdateResult
                    {
                        ResourceGroup = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
                    }));
            resourceGroupMock.Setup(f => f.GetAsync(resourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupGetResult
                {
                    ResourceGroup = new ResourceGroup()
                    {
                        Name = resourceGroupName,
                        Location = resourceGroupLocation
                    }
                }));
            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<Resource>());
            deploymentsMock.Setup(f => f.ValidateAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentValidateResponse
                {
                    IsValid = true
                }));
            deploymentsMock.Setup(f => f.GetAsync(resourceGroupName, It.IsAny<string>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = new Deployment()
                    {
                        Properties = new DeploymentProperties()
                        {
                            ProvisioningState = ProvisioningState.Succeeded
                        }
                    }
                }));
            deploymentOperationsMock.Setup(f => f.ListAsync(resourceGroupName, It.IsAny<string>(), null, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                }));

            PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);

            Assert.Equal(parameters.ResourceGroupName, result.ResourceGroupName);
            Assert.Equal(parameters.Location, result.Location);
            Assert.Empty(result.Resources);
        }
        public void NewResourceGroupChecksForPermissionForExistingResource()
        {
            RejectActionCounter = 0;
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters() { ResourceGroupName = resourceGroupName, ConfirmAction = RejectAction };
            resourceGroupMock.Setup(f => f.CheckExistenceAsync(parameters.ResourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupExistsResult
                {
                    Exists = true
                }));

            resourceGroupMock.Setup(f => f.GetAsync(
                parameters.ResourceGroupName,
                new CancellationToken()))
                    .Returns(Task.Factory.StartNew(() => new ResourceGroupGetResult
                    {
                        ResourceGroup = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
                    }));

            resourceOperationsMock.Setup(f => f.ListAsync(It.IsAny<ResourceListParameters>(), It.IsAny<CancellationToken>()))
                .Returns(() => Task.Factory.StartNew(() => new ResourceListResult
                {
                    StatusCode = HttpStatusCode.OK,
                    Resources = new List<Resource>(new[]
                        {
                            new Resource
                            {
                                Name = "foo",
                                Properties = null,
                                ProvisioningState = ProvisioningState.Running,
                                Location = "West US"
                            },
                            new Resource
                            {
                                Name = "bar",
                                Properties = null,
                                ProvisioningState = ProvisioningState.Running,
                                Location = "West US"
                            }
                        })

                }));

            resourcesClient.CreatePSResourceGroup(parameters);
            Assert.Equal(1, RejectActionCounter);
        }
        public void ExtractsErrorMessageFromFailedDeploymentOperation()
        {
            Uri templateUri = new Uri("http://templateuri.microsoft.com");
            BasicDeployment deploymentFromGet = new BasicDeployment();
            BasicDeployment deploymentFromValidate = new BasicDeployment();
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                DeploymentName = deploymentName,
                TemplateFile = templateFile,
                StorageAccountName = storageAccountName,
                ConfirmAction = ConfirmAction
            };
            resourceGroupMock.Setup(f => f.CheckExistenceAsync(parameters.ResourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupExistsResult
                {
                    Exists = false
                }));

            resourceGroupMock.Setup(f => f.CreateOrUpdateAsync(
                parameters.ResourceGroupName,
                It.IsAny<BasicResourceGroup>(),
                new CancellationToken()))
                    .Returns(Task.Factory.StartNew(() => new ResourceGroupCreateOrUpdateResult
                    {
                        ResourceGroup = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
                    }));
            resourceGroupMock.Setup(f => f.GetAsync(resourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupGetResult
                {
                    ResourceGroup = new ResourceGroup() { Location = resourceGroupLocation }
                }));
            deploymentsMock.Setup(f => f.CreateOrUpdateAsync(resourceGroupName, deploymentName, It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsCreateResult
                {
                    RequestId = requestId
                }))
                .Callback((string name, string dName, BasicDeployment bDeploy, CancellationToken token) => { deploymentFromGet = bDeploy; });
            deploymentsMock.Setup(f => f.GetAsync(resourceGroupName, deploymentName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = new Deployment
                    {
                        Name = deploymentName,
                        Properties = new DeploymentProperties()
                        {
                            Mode = DeploymentMode.Incremental,
                            ProvisioningState = ProvisioningState.Succeeded
                        }
                    }
                }));
            deploymentsMock.Setup(f => f.ValidateAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentValidateResponse
                {
                    IsValid = true,
                    Error = new ResourceManagementErrorWithDetails()
                }))
                .Callback((string rg, string dn, BasicDeployment d, CancellationToken c) => { deploymentFromValidate = d; });
            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<Resource>() { new Resource() { Name = "website" } });
            deploymentOperationsMock.Setup(f => f.ListAsync(resourceGroupName, deploymentName, null, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        new DeploymentOperation()
                        {
                            OperationId = Guid.NewGuid().ToString(),
                            Properties = new DeploymentOperationProperties()
                            {
                                ProvisioningState = ProvisioningState.Failed,
                                StatusMessage = JsonConvert.SerializeObject(new ResourceManagementError()
                                {
                                    Message = "A really bad error occured"
                                }),
                                TargetResource = new TargetResource()
                                {
                                    ResourceType = "Microsoft.Website",
                                    ResourceName = resourceName
                                }
                            }
                        }
                    }
                }));

            PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);

            deploymentsMock.Verify((f => f.CreateOrUpdateAsync(resourceGroupName, deploymentName, deploymentFromGet, new CancellationToken())), Times.Once());
            Assert.Equal(parameters.ResourceGroupName, result.ResourceGroupName);
            Assert.Equal(parameters.Location, result.Location);
            Assert.Equal(1, result.Resources.Count);

            Assert.Equal(DeploymentMode.Incremental, deploymentFromGet.Mode);
            Assert.NotNull(deploymentFromGet.Template);

            Assert.Equal(DeploymentMode.Incremental, deploymentFromValidate.Mode);
            Assert.NotNull(deploymentFromValidate.Template);

            errorLoggerMock.Verify(
                f => f(string.Format("Resource {0} '{1}' failed with message '{2}'",
                        "Microsoft.Website",
                        resourceName,
                        "A really bad error occured")),
                Times.Once());
        }
        public void CreatesResourceGroupWithDeploymentFromTemplateParameterObject()
        {
            Uri templateUri = new Uri("http://templateuri.microsoft.com");
            BasicDeployment deploymentFromGet = new BasicDeployment();
            BasicDeployment deploymentFromValidate = new BasicDeployment();
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                DeploymentName = deploymentName,
                TemplateFile = templateFile,
                TemplateParameterObject = new Hashtable()
                {
                    { "string", "myvalue" },
                    { "securestring", "myvalue" },
                    { "int", 12 },
                    { "bool", true },
                },
                StorageAccountName = storageAccountName,
                ConfirmAction = ConfirmAction
            };
            resourceGroupMock.Setup(f => f.CheckExistenceAsync(parameters.ResourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupExistsResult
                {
                    Exists = false
                }));

            resourceGroupMock.Setup(f => f.CreateOrUpdateAsync(
                parameters.ResourceGroupName,
                It.IsAny<BasicResourceGroup>(),
                new CancellationToken()))
                    .Returns(Task.Factory.StartNew(() => new ResourceGroupCreateOrUpdateResult
                    {
                        ResourceGroup = new ResourceGroup() { Name = parameters.ResourceGroupName, Location = parameters.Location }
                    }));
            resourceGroupMock.Setup(f => f.GetAsync(resourceGroupName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new ResourceGroupGetResult
                {
                    ResourceGroup = new ResourceGroup() { Location = resourceGroupLocation }
                }));
            deploymentsMock.Setup(f => f.CreateOrUpdateAsync(resourceGroupName, deploymentName, It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsCreateResult
                {
                    RequestId = requestId
                }))
                .Callback((string name, string dName, BasicDeployment bDeploy, CancellationToken token) => { deploymentFromGet = bDeploy; });
            deploymentsMock.Setup(f => f.GetAsync(resourceGroupName, deploymentName, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = new Deployment
                        {
                            Name = deploymentName,
                            Properties = new DeploymentProperties()
                            {
                                Mode = DeploymentMode.Incremental,
                                ProvisioningState = ProvisioningState.Succeeded
                            },
                        }
                }));
            deploymentsMock.Setup(f => f.ValidateAsync(resourceGroupName, It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentValidateResponse
                {
                    IsValid = true,
                    Error = new ResourceManagementErrorWithDetails()
                }))
                .Callback((string rg, string dn, BasicDeployment d, CancellationToken c) => { deploymentFromValidate = d; });
            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<Resource>() { new Resource() { Name = "website" } });
            deploymentOperationsMock.Setup(f => f.ListAsync(resourceGroupName, deploymentName, null, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        new DeploymentOperation()
                        {
                            OperationId = Guid.NewGuid().ToString(),
                            Properties = new DeploymentOperationProperties()
                            {
                                ProvisioningState = ProvisioningState.Succeeded,
                                TargetResource = new TargetResource()
                                {
                                    ResourceType = "Microsoft.Website",
                                    ResourceName = resourceName
                                }
                            }
                        }
                    }
                }));

            PSResourceGroup result = resourcesClient.CreatePSResourceGroup(parameters);

            deploymentsMock.Verify((f => f.CreateOrUpdateAsync(resourceGroupName, deploymentName, deploymentFromGet, new CancellationToken())), Times.Once());
            Assert.Equal(parameters.ResourceGroupName, result.ResourceGroupName);
            Assert.Equal(parameters.Location, result.Location);
            Assert.Equal(1, result.Resources.Count);

            Assert.Equal(DeploymentMode.Incremental, deploymentFromGet.Mode);
            Assert.NotNull(deploymentFromGet.Template);
            // Skip: Test produces different outputs since hashtable order is not guaranteed.
            //EqualsIgnoreWhitespace(File.ReadAllText(templateParameterFile), deploymentFromGet.Parameters);

            Assert.Equal(DeploymentMode.Incremental, deploymentFromValidate.Mode);
            Assert.NotNull(deploymentFromValidate.Template);
            // Skip: Test produces different outputs since hashtable order is not guaranteed.
            //EqualsIgnoreWhitespace(File.ReadAllText(templateParameterFile), deploymentFromValidate.Parameters);

            progressLoggerMock.Verify(
                f => f(string.Format("Resource {0} '{1}' provisioning status is {2}",
                        "Microsoft.Website",
                        resourceName,
                        ProvisioningState.Succeeded.ToLower())),
                Times.Once());
        }
        public void NewResourceGroupUsesDeploymentNameForDeploymentName()
        {
            string deploymentName = "abc123";
            BasicDeployment deploymentFromGet = new BasicDeployment();
            BasicDeployment deploymentFromValidate = new BasicDeployment();
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                DeploymentName = deploymentName,
                GalleryTemplateIdentity = "abc",
                StorageAccountName = storageAccountName,
                ConfirmAction = ConfirmAction
            };

            galleryTemplatesClientMock.Setup(g => g.GetGalleryTemplateFile(It.IsAny<string>())).Returns("http://path/file.html");

            deploymentsMock.Setup(f => f.ValidateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentValidateResponse
                {
                    IsValid = true,
                    Error = new ResourceManagementErrorWithDetails()
                }))
                .Callback((string rg, string dn, BasicDeployment d, CancellationToken c) => { deploymentFromValidate = d; });

            deploymentsMock.Setup(f => f.CreateOrUpdateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsCreateResult
                {
                    RequestId = requestId
                }))
                .Callback((string name, string dName, BasicDeployment bDeploy, CancellationToken token) => { deploymentFromGet = bDeploy; deploymentName = dName; });

            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<Resource>() { new Resource() { Name = "website" } });

            var operationId = Guid.NewGuid().ToString();
            var operationQueue = new Queue<DeploymentOperation>();
            operationQueue.Enqueue(
                new DeploymentOperation()
                {
                    OperationId = operationId,
                    Properties = new DeploymentOperationProperties()
                    {
                        ProvisioningState = ProvisioningState.Accepted,
                        TargetResource = new TargetResource()
                        {
                            ResourceType = "Microsoft.Website",
                            ResourceName = resourceName
                        }
                    }
                }
            );
            operationQueue.Enqueue(
                new DeploymentOperation()
                {
                    OperationId = operationId,
                    Properties = new DeploymentOperationProperties()
                    {
                        ProvisioningState = ProvisioningState.Running,
                        TargetResource = new TargetResource()
                        {
                            ResourceType = "Microsoft.Website",
                            ResourceName = resourceName
                        }
                    }
                }
            );
            operationQueue.Enqueue(
                new DeploymentOperation()
                {
                    OperationId = operationId,
                    Properties = new DeploymentOperationProperties()
                    {
                        ProvisioningState = ProvisioningState.Succeeded,
                        TargetResource = new TargetResource()
                        {
                            ResourceType = "Microsoft.Website",
                            ResourceName = resourceName
                        }
                    }
                }
            );
            deploymentOperationsMock.SetupSequence(f => f.ListAsync(It.IsAny<string>(), It.IsAny<string>(), null, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        operationQueue.Dequeue()
                    }
                }))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        operationQueue.Dequeue()
                    }
                }))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        operationQueue.Dequeue()
                    }
                }));

            var deploymentQueue = new Queue<Deployment>();
            deploymentQueue.Enqueue(new Deployment
            {
                Name = deploymentName,
                Properties = new DeploymentProperties()
                {
                    Mode = DeploymentMode.Incremental,
                    CorrelationId = "123",
                    ProvisioningState = ProvisioningState.Accepted
                }
            });
            deploymentQueue.Enqueue(new Deployment
            {
                Name = deploymentName,
                Properties = new DeploymentProperties()
                {
                    Mode = DeploymentMode.Incremental,
                    CorrelationId = "123",
                    ProvisioningState = ProvisioningState.Running
                }
            });
            deploymentQueue.Enqueue(new Deployment
            {
                Name = deploymentName,
                Properties = new DeploymentProperties()
                {
                    Mode = DeploymentMode.Incremental,
                    CorrelationId = "123",
                    ProvisioningState = ProvisioningState.Succeeded
                }
            });
            deploymentsMock.SetupSequence(f => f.GetAsync(It.IsAny<string>(), It.IsAny<string>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = deploymentQueue.Dequeue()
                }))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = deploymentQueue.Dequeue()
                }))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = deploymentQueue.Dequeue()
                }));

            PSResourceGroupDeployment result = resourcesClient.ExecuteDeployment(parameters);
            Assert.Equal(deploymentName, deploymentName);
            Assert.Equal(ProvisioningState.Succeeded, result.ProvisioningState);
            progressLoggerMock.Verify(
                f => f(string.Format("Resource {0} '{1}' provisioning status is {2}", "Microsoft.Website", resourceName, ProvisioningState.Accepted.ToLower())),
                Times.Once());
            progressLoggerMock.Verify(
                f => f(string.Format("Resource {0} '{1}' provisioning status is {2}", "Microsoft.Website", resourceName, ProvisioningState.Running.ToLower())),
                Times.Once());
            progressLoggerMock.Verify(
                f => f(string.Format("Resource {0} '{1}' provisioning status is {2}", "Microsoft.Website", resourceName, ProvisioningState.Succeeded.ToLower())),
                Times.Once());
        }
        public void NewResourceGroupUsesTemplateNameForDeploymentName(string templatePath, string expectedName)
        {
            BasicDeployment deploymentFromGet = new BasicDeployment();
            BasicDeployment deploymentFromValidate = new BasicDeployment();
            CreatePSResourceGroupParameters parameters = new CreatePSResourceGroupParameters()
            {
                ResourceGroupName = resourceGroupName,
                Location = resourceGroupLocation,
                DeploymentName = null,
                TemplateFile = templatePath,
                StorageAccountName = storageAccountName,
                ConfirmAction = ConfirmAction
            };
            galleryTemplatesClientMock.Setup(g => g.GetGalleryTemplateFile(It.IsAny<string>())).Returns("http://path/file.html");
            deploymentsMock.Setup(f => f.ValidateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentValidateResponse
                {
                    IsValid = true,
                    Error = new ResourceManagementErrorWithDetails()
                }))
                .Callback((string rg, string dn, BasicDeployment d, CancellationToken c) => { deploymentFromValidate = d; });
            deploymentsMock.Setup(f => f.CreateOrUpdateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<BasicDeployment>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsCreateResult
                {
                    RequestId = requestId
                }))
                .Callback((string name, string dName, BasicDeployment bDeploy, CancellationToken token) => { deploymentFromGet = bDeploy; deploymentName= dName; });
            SetupListForResourceGroupAsync(parameters.ResourceGroupName, new List<Resource>() { new Resource() { Name = "website" } });
            deploymentOperationsMock.Setup(f => f.ListAsync(It.IsAny<string>(), It.IsAny<string>(), null, new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentOperationsListResult
                {
                    Operations = new List<DeploymentOperation>()
                    {
                        new DeploymentOperation()
                        {
                            OperationId = Guid.NewGuid().ToString(),
                            Properties = new DeploymentOperationProperties()
                            {
                                ProvisioningState = ProvisioningState.Succeeded,
                                TargetResource = new TargetResource()
                                {
                                    ResourceType = "Microsoft.Website",
                                    ResourceName = resourceName
                                }
                            }
                        }
                    }
                }));
            deploymentsMock.Setup(f => f.GetAsync(It.IsAny<string>(), It.IsAny<string>(), new CancellationToken()))
                .Returns(Task.Factory.StartNew(() => new DeploymentGetResult
                {
                    Deployment = new Deployment
                    {
                        Name = deploymentName,
                        Properties = new DeploymentProperties()
                        {
                            Mode = DeploymentMode.Incremental,
                            CorrelationId = "123",
                            ProvisioningState = ProvisioningState.Succeeded
                        },
                    }
                }));

            resourcesClient.ExecuteDeployment(parameters);
            if (expectedName == "GUID")
            {
                Guid.Parse(deploymentName);
            }
            else
            {
                Assert.Equal(expectedName, deploymentName);
            }
        }
        /// <summary>
        /// Creates a new resource group and deployment using the passed template file option which
        /// can be user customized or from gallery tenplates.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created resource group</returns>
        public virtual PSResourceGroup CreatePSResourceGroup(CreatePSResourceGroupParameters parameters)
        {
            bool createDeployment = !string.IsNullOrEmpty(parameters.GalleryTemplateIdentity) || !string.IsNullOrEmpty(parameters.TemplateFile);
            bool resourceExists = ResourceManagementClient.ResourceGroups.CheckExistence(parameters.ResourceGroupName).Exists;

            ResourceGroup resourceGroup = null;
            Action createOrUpdateResourceGroup = () =>
            {
                resourceGroup = CreateOrUpdateResourceGroup(parameters.ResourceGroupName, parameters.Location, parameters.Tag);
                WriteVerbose(string.Format("Created resource group '{0}' in location '{1}'", resourceGroup.Name, resourceGroup.Location));

                if (createDeployment)
                {
                    ExecuteDeployment(parameters);
                }
            };

            if (resourceExists && !parameters.Force)
            {
                parameters.ConfirmAction(parameters.Force,
                    ProjectResources.ResourceGroupAlreadyExists,
                    ProjectResources.NewResourceGroupMessage,
                    parameters.DeploymentName,
                    createOrUpdateResourceGroup);
                resourceGroup = ResourceManagementClient.ResourceGroups.Get(parameters.ResourceGroupName).ResourceGroup;
            }
            else
            {
                createOrUpdateResourceGroup();
            }

            return resourceGroup.ToPSResourceGroup(this);
        }