Example #1
0
        public void DefaultExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            if (this.VM.DiagnosticsProfile == null)
            {
                var storageUri = GetOrCreateStorageAccountForBootDiagnostics();

                if (storageUri != null)
                {
                    this.VM.DiagnosticsProfile = new DiagnosticsProfile
                    {
                        BootDiagnostics = new BootDiagnostics
                        {
                            Enabled    = true,
                            StorageUri = storageUri.ToString(),
                        }
                    };
                }
            }

            CM.ExtendedLocation ExtendedLocation = null;
            if (this.EdgeZone != null)
            {
                ExtendedLocation = new CM.ExtendedLocation {
                    Name = this.EdgeZone, Type = CM.ExtendedLocationTypes.EdgeZone
                };
            }

            if (ShouldProcess(this.VM.Name, VerbsCommon.New))
            {
                ExecuteClientAction(() =>
                {
                    var parameters = new VirtualMachine
                    {
                        DiagnosticsProfile = this.VM.DiagnosticsProfile,
                        HardwareProfile    = this.VM.HardwareProfile,
                        StorageProfile     = this.VM.StorageProfile,
                        NetworkProfile     = this.VM.NetworkProfile,
                        OsProfile          = this.VM.OSProfile,
                        Plan                    = this.VM.Plan,
                        LicenseType             = this.LicenseType ?? this.VM.LicenseType,
                        AvailabilitySet         = this.VM.AvailabilitySetReference,
                        Location                = this.Location ?? this.VM.Location,
                        ExtendedLocation        = ExtendedLocation,
                        Tags                    = this.Tag != null ? this.Tag.ToDictionary() : this.VM.Tags,
                        Identity                = ComputeAutoMapperProfile.Mapper.Map <VirtualMachineIdentity>(this.VM.Identity),
                        Zones                   = this.Zone ?? this.VM.Zones,
                        ProximityPlacementGroup = this.VM.ProximityPlacementGroup,
                        Host                    = this.VM.Host,
                        VirtualMachineScaleSet  = this.VM.VirtualMachineScaleSet,
                        AdditionalCapabilities  = this.VM.AdditionalCapabilities,
                        Priority                = this.VM.Priority,
                        EvictionPolicy          = this.VM.EvictionPolicy,
                        BillingProfile          = this.VM.BillingProfile,
                        SecurityProfile         = this.VM.SecurityProfile
                    };

                    Dictionary <string, List <string> > auxAuthHeader = null;
                    if (!string.IsNullOrEmpty(parameters.StorageProfile?.ImageReference?.Id))
                    {
                        var resourceId = ResourceId.TryParse(parameters.StorageProfile.ImageReference.Id);

                        if (string.Equals(ComputeStrategy.Namespace, resourceId?.ResourceType?.Namespace, StringComparison.OrdinalIgnoreCase) &&
                            string.Equals("galleries", resourceId?.ResourceType?.Provider, StringComparison.OrdinalIgnoreCase) &&
                            !string.Equals(this.ComputeClient?.ComputeManagementClient?.SubscriptionId, resourceId?.SubscriptionId, StringComparison.OrdinalIgnoreCase))
                        {
                            List <string> resourceIds = new List <string>();
                            resourceIds.Add(parameters.StorageProfile.ImageReference.Id);
                            var auxHeaderDictionary = GetAuxilaryAuthHeaderFromResourceIds(resourceIds);
                            if (auxHeaderDictionary != null && auxHeaderDictionary.Count > 0)
                            {
                                auxAuthHeader = new Dictionary <string, List <string> >(auxHeaderDictionary);
                            }
                        }
                    }

                    var result = this.VirtualMachineClient.CreateOrUpdateWithHttpMessagesAsync(
                        this.ResourceGroupName,
                        this.VM.Name,
                        parameters,
                        auxAuthHeader).GetAwaiter().GetResult();
                    var psResult = ComputeAutoMapperProfile.Mapper.Map <PSAzureOperationResponse>(result);

                    if (!(this.DisableBginfoExtension.IsPresent || IsLinuxOs()))
                    {
                        var currentBginfoVersion = GetBginfoExtension();

                        if (!string.IsNullOrEmpty(currentBginfoVersion))
                        {
                            var extensionParameters = new VirtualMachineExtension
                            {
                                Location  = this.Location,
                                Publisher = VirtualMachineBGInfoExtensionContext.ExtensionDefaultPublisher,
                                VirtualMachineExtensionType = VirtualMachineBGInfoExtensionContext.ExtensionDefaultName,
                                TypeHandlerVersion          = currentBginfoVersion,
                                AutoUpgradeMinorVersion     = true,
                            };

                            typeof(CM.Resource).GetRuntimeProperty("Name")
                            .SetValue(extensionParameters, VirtualMachineBGInfoExtensionContext.ExtensionDefaultName);
                            typeof(CM.Resource).GetRuntimeProperty("Type")
                            .SetValue(extensionParameters, VirtualMachineExtensionType);

                            var op2 = ComputeClient.ComputeManagementClient.VirtualMachineExtensions.CreateOrUpdateWithHttpMessagesAsync(
                                this.ResourceGroupName,
                                this.VM.Name,
                                VirtualMachineBGInfoExtensionContext.ExtensionDefaultName,
                                extensionParameters).GetAwaiter().GetResult();
                            psResult = ComputeAutoMapperProfile.Mapper.Map <PSAzureOperationResponse>(op2);
                        }
                    }
                    WriteObject(psResult);
                });
            }
        }
Example #2
0
        public static async Task <ImageAndOsType> UpdateImageAndOsTypeAsync(
            this IClient client,
            ImageAndOsType imageAndOsType,
            string resourceGroupName,
            string imageName,
            string location)
        {
            if (imageAndOsType != null)
            {
                return(imageAndOsType);
            }

            var compute = client.GetClient <ComputeManagementClient>();

            if (imageName.Contains(':'))
            {
                if (location == null)
                {
                    return(null);
                }

                var imageArray = imageName.Split(':');
                if (imageArray.Length != 4)
                {
                    throw new InvalidOperationException(
                              string.Format(Resources.InvalidImageName, imageName));
                }
                var image = new ImageReference
                {
                    Publisher = imageArray[0],
                    Offer     = imageArray[1],
                    Sku       = imageArray[2],
                    Version   = imageArray[3],
                };

                if (image.Version.ToLower() == "latest")
                {
                    var images = await compute.VirtualMachineImages.ListAsync(
                        location, image.Publisher, image.Offer, image.Sku);

                    // According to Compute API:
                    // "The allowed formats are Major.Minor.Build or 'latest'.
                    //  Major, Minor, and Build are decimal numbers."
                    image.Version = images
                                    .Select(i => ImageVersion.Parse(i.Name))
                                    .Aggregate((a, b) => a.CompareTo(b) < 0 ? b : a)
                                    .ToString();
                }
                var imageModel = await compute.VirtualMachineImages.GetAsync(
                    location, image.Publisher, image.Offer, image.Sku, image.Version);

                return(new ImageAndOsType(
                           imageModel.OsDiskImage.OperatingSystem,
                           image,
                           imageModel.DataDiskImages.GetLuns()));
            }
            else if (imageName.Contains("/"))
            {
                var resourceId = ResourceId.TryParse(imageName);
                if (resourceId == null ||
                    resourceId.ResourceType.Namespace != ComputeStrategy.Namespace ||
                    (resourceId.ResourceType.Provider != "images") &&
                    resourceId.ResourceType.Provider != "galleries")
                {
                    throw new ArgumentException(string.Format(Resources.ComputeInvalidImageName, imageName));
                }

                if (resourceId.ResourceType.Provider == "galleries")
                {
                    var compute2 = client.GetClient <ComputeManagementClient>();
                    compute2.SubscriptionId = resourceId.SubscriptionId;
                    return(await compute2.GetGalleryImageAndOsTypeAsync(resourceId.ResourceGroupName, imageName));
                }
                else
                {
                    return(await compute.GetImageAndOsTypeAsync(resourceId.ResourceGroupName, resourceId.Name));
                }
            }
            else
            {
                try
                {
                    return(await compute.GetImageAndOsTypeAsync(resourceGroupName, imageName));
                }
                catch
                {
                }

                // get generic image
                var result = Images
                             .Instance
                             .SelectMany(osAndMap => osAndMap
                                         .Value
                                         .Where(nameAndImage => nameAndImage.Key.ToLower() == imageName.ToLower())
                                         .Select(nameAndImage => new ImageAndOsType(
                                                     osAndMap.Key == "Windows"
                                ? OperatingSystemTypes.Windows
                                : OperatingSystemTypes.Linux,
                                                     nameAndImage.Value,
                                                     null)))
                             .FirstOrDefault();

                if (result == null)
                {
                    throw new ArgumentException(string.Format(Resources.ComputeNoImageFound, imageName));
                }

                return(result);
            }
        }
Example #3
0
        /// <summary>
        /// When resuming an order by query we need to filter the document producers.
        /// </summary>
        /// <param name="producer">The producer to filter down.</param>
        /// <param name="sortOrders">The sort orders.</param>
        /// <param name="continuationToken">The continuation token.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task to await on.</returns>
        private async Task FilterAsync(
            DocumentProducerTree producer,
            SortOrder[] sortOrders,
            OrderByContinuationToken continuationToken,
            CancellationToken cancellationToken)
        {
            // When we resume a query on a partition there is a possibility that we only read a partial page from the backend
            // meaning that will we repeat some documents if we didn't do anything about it.
            // The solution is to filter all the documents that come before in the sort order, since we have already emitted them to the client.
            // The key is to seek until we get an order by value that matches the order by value we left off on.
            // Once we do that we need to seek to the correct _rid within the term,
            // since there might be many documents with the same order by value we left off on.

            foreach (DocumentProducerTree tree in producer)
            {
                if (!ResourceId.TryParse(continuationToken.Rid, out ResourceId continuationRid))
                {
                    this.TraceWarning(string.Format(
                                          CultureInfo.InvariantCulture,
                                          "Invalid Rid in the continuation token {0} for OrderBy~Context.",
                                          continuationToken.CompositeContinuationToken.Token));
                    throw new BadRequestException(RMResources.InvalidContinuationToken);
                }

                Dictionary <string, ResourceId> resourceIds = new Dictionary <string, ResourceId>();
                int  itemToSkip = continuationToken.SkipCount;
                bool continuationRidVerified = false;

                while (true)
                {
                    OrderByQueryResult orderByResult = new OrderByQueryResult(tree.Current);
                    // Throw away documents until it matches the item from the continuation token.
                    int cmp = 0;
                    for (int i = 0; i < sortOrders.Length; ++i)
                    {
                        cmp = ItemComparer.Instance.Compare(
                            continuationToken.OrderByItems[i].Item,
                            orderByResult.OrderByItems[i].Item);

                        if (cmp != 0)
                        {
                            cmp = sortOrders[i] != SortOrder.Descending ? cmp : -cmp;
                            break;
                        }
                    }

                    if (cmp < 0)
                    {
                        // We might have passed the item due to deletions and filters.
                        break;
                    }

                    if (cmp == 0)
                    {
                        ResourceId rid;
                        if (!resourceIds.TryGetValue(orderByResult.Rid, out rid))
                        {
                            if (!ResourceId.TryParse(orderByResult.Rid, out rid))
                            {
                                this.TraceWarning(string.Format(
                                                      CultureInfo.InvariantCulture,
                                                      "Invalid Rid in the continuation token {0} for OrderBy~Context.",
                                                      continuationToken.CompositeContinuationToken.Token));
                                throw new BadRequestException(RMResources.InvalidContinuationToken);
                            }

                            resourceIds.Add(orderByResult.Rid, rid);
                        }

                        if (!continuationRidVerified)
                        {
                            if (continuationRid.Database != rid.Database || continuationRid.DocumentCollection != rid.DocumentCollection)
                            {
                                this.TraceWarning(string.Format(
                                                      CultureInfo.InvariantCulture,
                                                      "Invalid Rid in the continuation token {0} for OrderBy~Context.",
                                                      continuationToken.CompositeContinuationToken.Token));
                                throw new BadRequestException(RMResources.InvalidContinuationToken);
                            }

                            continuationRidVerified = true;
                        }

                        // Once the item matches the order by items from the continuation tokens
                        // We still need to remove all the documents that have a lower rid in the rid sort order.
                        // If there is a tie in the sort order the documents should be in _rid order in the same direction as the first order by field.
                        // So if it's ORDER BY c.age ASC, c.name DESC the _rids are ASC
                        // If ti's ORDER BY c.age DESC, c.name DESC the _rids are DESC
                        cmp = continuationRid.Document.CompareTo(rid.Document);
                        if (sortOrders[0] == SortOrder.Descending)
                        {
                            cmp = -cmp;
                        }

                        // We might have passed the item due to deletions and filters.
                        // We also have a skip count for JOINs
                        if (cmp < 0 || (cmp == 0 && itemToSkip-- <= 0))
                        {
                            break;
                        }
                    }

                    if (!await tree.MoveNextAsync(cancellationToken))
                    {
                        break;
                    }
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            ExecuteClientAction(() =>
            {
                if (ShouldProcess(this.Name, VerbsCommon.New))
                {
                    string resourceGroupName                = this.ResourceGroupName;
                    string galleryName                      = this.GalleryName;
                    string galleryImageName                 = this.GalleryImageDefinitionName;
                    string galleryImageVersionName          = this.Name;
                    GalleryImageVersion galleryImageVersion = new GalleryImageVersion();

                    galleryImageVersion.Location = this.Location;

                    if (this.IsParameterBound(c => c.Tag))
                    {
                        galleryImageVersion.Tags = this.Tag.Cast <DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value);
                    }

                    if (this.IsParameterBound(c => c.DataDiskImage))
                    {
                        if (galleryImageVersion.StorageProfile == null)
                        {
                            galleryImageVersion.StorageProfile = new GalleryImageVersionStorageProfile();
                        }
                        galleryImageVersion.StorageProfile.DataDiskImages = this.DataDiskImage;
                    }

                    if (this.IsParameterBound(c => c.OSDiskImage))
                    {
                        if (galleryImageVersion.StorageProfile == null)
                        {
                            galleryImageVersion.StorageProfile = new GalleryImageVersionStorageProfile();
                        }
                        galleryImageVersion.StorageProfile.OsDiskImage = this.OSDiskImage;
                    }

                    if (this.IsParameterBound(c => c.ReplicaCount))
                    {
                        if (galleryImageVersion.PublishingProfile == null)
                        {
                            galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile();
                        }
                        galleryImageVersion.PublishingProfile.ReplicaCount = this.ReplicaCount;
                    }

                    if (this.IsParameterBound(c => c.PublishingProfileExcludeFromLatest))
                    {
                        if (galleryImageVersion.PublishingProfile == null)
                        {
                            galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile();
                        }
                        galleryImageVersion.PublishingProfile.ExcludeFromLatest = this.PublishingProfileExcludeFromLatest.IsPresent;
                    }

                    if (this.IsParameterBound(c => c.PublishingProfileEndOfLifeDate))
                    {
                        if (galleryImageVersion.PublishingProfile == null)
                        {
                            galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile();
                        }
                        galleryImageVersion.PublishingProfile.EndOfLifeDate = this.PublishingProfileEndOfLifeDate;
                    }

                    if (this.IsParameterBound(c => c.StorageAccountType))
                    {
                        if (galleryImageVersion.PublishingProfile == null)
                        {
                            galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile();
                        }
                        galleryImageVersion.PublishingProfile.StorageAccountType = this.StorageAccountType;
                    }

                    if (this.IsParameterBound(c => c.TargetRegion))
                    {
                        if (galleryImageVersion.PublishingProfile == null)
                        {
                            galleryImageVersion.PublishingProfile = new GalleryImageVersionPublishingProfile();
                        }
                        galleryImageVersion.PublishingProfile.TargetRegions = new List <TargetRegion>();
                        foreach (var t in this.TargetRegion)
                        {
                            var target = new TargetRegion()
                            {
                                Name = (string)t["Name"],
                                RegionalReplicaCount = (int?)t["ReplicaCount"],
                                StorageAccountType   = (string)t["StorageAccountType"],
                            };
                            if (t["Encryption"] != null)
                            {
                                var osDiskEncryptionSetId = (string)((Hashtable)((Hashtable)t["Encryption"])["osDiskImage"])["DiskEncryptionSetId"];
                                var osDiskImageEncryption = new OSDiskImageEncryption(osDiskEncryptionSetId);

                                List <DataDiskImageEncryption> dataDiskImageEncryption = null;
                                var dataDiskImage = (object[])((Hashtable)t["Encryption"])["dataDiskImages"];

                                if (dataDiskImage != null)
                                {
                                    dataDiskImageEncryption = new List <DataDiskImageEncryption>();
                                    foreach (Hashtable dataDiskEncryptionSetId in dataDiskImage)
                                    {
                                        DataDiskImageEncryption d = new DataDiskImageEncryption((int)dataDiskEncryptionSetId["Lun"], (string)dataDiskEncryptionSetId["DiskEncryptionSetId"]);
                                        dataDiskImageEncryption.Add(d);
                                    }
                                }

                                target.Encryption = new EncryptionImages(osDiskImageEncryption, dataDiskImageEncryption);
                            }

                            galleryImageVersion.PublishingProfile.TargetRegions.Add(target);
                        }
                    }

                    Dictionary <string, List <string> > auxAuthHeader = null;
                    if (this.IsParameterBound(c => c.SourceImageId))
                    {
                        if (galleryImageVersion.StorageProfile == null)
                        {
                            galleryImageVersion.StorageProfile = new GalleryImageVersionStorageProfile();
                        }
                        if (galleryImageVersion.StorageProfile.Source == null)
                        {
                            galleryImageVersion.StorageProfile.Source = new GalleryArtifactVersionSource();
                        }
                        galleryImageVersion.StorageProfile.Source.Id = this.SourceImageId;

                        var resourceId = ResourceId.TryParse(this.SourceImageId);

                        if (string.Equals("galleries", resourceId?.ResourceType?.Provider, StringComparison.OrdinalIgnoreCase) &&
                            !string.Equals(this.ComputeClient?.ComputeManagementClient?.SubscriptionId, resourceId?.SubscriptionId, StringComparison.OrdinalIgnoreCase))
                        {
                            List <string> resourceIds = new List <string>();
                            resourceIds.Add(this.SourceImageId);
                            var auxHeaderDictionary = GetAuxilaryAuthHeaderFromResourceIds(resourceIds);
                            if (auxHeaderDictionary != null && auxHeaderDictionary.Count > 0)
                            {
                                auxAuthHeader = new Dictionary <string, List <string> >(auxHeaderDictionary);
                            }
                        }
                    }

                    GalleryImageVersion result;
                    if (auxAuthHeader != null)
                    {
                        var res = GalleryImageVersionsClient.CreateOrUpdateWithHttpMessagesAsync(
                            this.ResourceGroupName,
                            galleryName,
                            galleryImageName,
                            galleryImageVersionName, galleryImageVersion,
                            auxAuthHeader).GetAwaiter().GetResult();

                        result = res.Body;
                    }
                    else
                    {
                        result = GalleryImageVersionsClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImageVersionName, galleryImageVersion);
                    }

                    var psObject = new PSGalleryImageVersion();
                    ComputeAutomationAutoMapperProfile.Mapper.Map <GalleryImageVersion, PSGalleryImageVersion>(result, psObject);
                    WriteObject(psObject);
                }
            });
        }
Example #5
0
        private async Task FilterAsync(
            DocumentProducer <OrderByQueryResult> producer,
            SortOrder[] sortOrders,
            OrderByContinuationToken continuationToken,
            CancellationToken cancellationToken)
        {
            ResourceId continuationRid;

            if (!ResourceId.TryParse(continuationToken.Rid, out continuationRid))
            {
                DefaultTrace.TraceWarning(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{0}, CorrelatedActivityId: {1}, ActivityId: {2} | Invalid Rid in the continuation token {3} for OrderBy~Context.",
                        DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
                        this.CorrelatedActivityId,
                        this.ActivityId,
                        continuationToken.CompositeToken.Token));
                throw new BadRequestException(RMResources.InvalidContinuationToken);
            }

            Dictionary <string, ResourceId> resourceIds = new Dictionary <string, ResourceId>();
            int  itemToSkip = continuationToken.SkipCount;
            bool continuationRidVerified = false;

            while (true)
            {
                OrderByQueryResult orderByResult = (OrderByQueryResult)producer.Current;

                int cmp = 0;
                for (int i = 0; i < sortOrders.Length; ++i)
                {
                    cmp = ItemComparer.Instance.Compare(
                        continuationToken.OrderByItems[i].GetItem(),
                        orderByResult.OrderByItems[i].GetItem());

                    if (cmp != 0)
                    {
                        cmp = sortOrders[i] != SortOrder.Descending ? cmp : -cmp;
                        break;
                    }
                }

                if (cmp < 0)
                {
                    break;
                }

                if (cmp == 0)
                {
                    ResourceId rid;
                    if (!resourceIds.TryGetValue(orderByResult.Rid, out rid))
                    {
                        if (!ResourceId.TryParse(orderByResult.Rid, out rid))
                        {
                            DefaultTrace.TraceWarning(
                                string.Format(
                                    CultureInfo.InvariantCulture,
                                    "{0}, CorrelatedActivityId: {1}, ActivityId: {2} | Invalid Rid in the continuation token {3} for OrderBy~Context.",
                                    DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
                                    this.CorrelatedActivityId,
                                    this.ActivityId,
                                    continuationToken.CompositeToken.Token));
                            throw new BadRequestException(RMResources.InvalidContinuationToken);
                        }

                        resourceIds.Add(orderByResult.Rid, rid);
                    }

                    if (!continuationRidVerified)
                    {
                        if (continuationRid.Database != rid.Database || continuationRid.DocumentCollection != rid.DocumentCollection)
                        {
                            DefaultTrace.TraceWarning(
                                string.Format(
                                    CultureInfo.InvariantCulture,
                                    "{0}, CorrelatedActivityId: {1}, ActivityId: {2} | Invalid Rid in the continuation token {3} for OrderBy~Context.",
                                    DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
                                    this.CorrelatedActivityId,
                                    this.ActivityId,
                                    continuationToken.CompositeToken.Token));
                            throw new BadRequestException(RMResources.InvalidContinuationToken);
                        }

                        continuationRidVerified = true;
                    }

                    cmp = continuationRid.Document.CompareTo(rid.Document);
                    if (sortOrders[sortOrders.Length - 1] == SortOrder.Descending)
                    {
                        cmp = -cmp;
                    }

                    if (cmp < 0 || (cmp == 0 && itemToSkip-- <= 0))
                    {
                        break;
                    }
                }


                if (!await producer.MoveNextAsync(cancellationToken))
                {
                    break;
                }
            }
        }
Example #6
0
        public override void ExecuteCmdlet()
        {
            if (this.IsParameterBound(c => c.UserData))
            {
                if (!ValidateBase64EncodedString.ValidateStringIsBase64Encoded(this.UserData))
                {
                    this.UserData = ValidateBase64EncodedString.EncodeStringToBase64(this.UserData);
                    this.WriteInformation(ValidateBase64EncodedString.UserDataEncodeNotification, new string[] { "PSHOST" });
                }
            }

            base.ExecuteCmdlet();
            switch (ParameterSetName)
            {
            case SimpleParameterSet:
                this.StartAndWait(SimpleParameterSetExecuteCmdlet);
                break;

            default:
                ExecuteClientAction(() =>
                {
                    if (ShouldProcess(this.VMScaleSetName, VerbsCommon.New))
                    {
                        string resourceGroupName          = this.ResourceGroupName;
                        string vmScaleSetName             = this.VMScaleSetName;
                        VirtualMachineScaleSet parameters = new VirtualMachineScaleSet();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <PSVirtualMachineScaleSet, VirtualMachineScaleSet>(this.VirtualMachineScaleSet, parameters);
                        if (parameters?.VirtualMachineProfile?.StorageProfile?.ImageReference?.Version?.ToLower() != "latest")
                        {
                            WriteWarning("You are deploying VMSS pinned to a specific image version from Azure Marketplace. \n" +
                                         "Consider using \"latest\" as the image version. This allows VMSS to auto upgrade when a newer version is available.");
                        }

                        if (parameters?.OrchestrationMode == "Flexible")
                        {
                            if (parameters?.VirtualMachineProfile?.NetworkProfile?.NetworkInterfaceConfigurations != null)
                            {
                                foreach (var nicConfig in parameters.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations)
                                {
                                    if (nicConfig.IpConfigurations != null)
                                    {
                                        foreach (var ipConfig in nicConfig.IpConfigurations)
                                        {
                                            ipConfig.LoadBalancerInboundNatPools = null;
                                        }
                                    }
                                }
                            }

                            parameters.UpgradePolicy = null;

                            flexibleOrchestrationModeDefaultParameters(parameters);
                            checkFlexibleOrchestrationModeParamsDefaultParamSet(parameters);
                        }

                        // For Cross-tenant RBAC sharing
                        Dictionary <string, List <string> > auxAuthHeader = null;
                        if (!string.IsNullOrEmpty(parameters.VirtualMachineProfile?.StorageProfile?.ImageReference?.Id))
                        {
                            var resourceId = ResourceId.TryParse(parameters.VirtualMachineProfile?.StorageProfile.ImageReference.Id);

                            if (string.Equals(ComputeStrategy.Namespace, resourceId?.ResourceType?.Namespace, StringComparison.OrdinalIgnoreCase) &&
                                string.Equals("galleries", resourceId?.ResourceType?.Provider, StringComparison.OrdinalIgnoreCase) &&
                                !string.Equals(this.ComputeClient?.ComputeManagementClient?.SubscriptionId, resourceId?.SubscriptionId, StringComparison.OrdinalIgnoreCase))
                            {
                                List <string> resourceIds = new List <string>();
                                resourceIds.Add(parameters.VirtualMachineProfile?.StorageProfile.ImageReference.Id);
                                var auxHeaderDictionary = GetAuxilaryAuthHeaderFromResourceIds(resourceIds);
                                if (auxHeaderDictionary != null && auxHeaderDictionary.Count > 0)
                                {
                                    auxAuthHeader = new Dictionary <string, List <string> >(auxHeaderDictionary);
                                }
                            }
                        }
                        // END: For Cross-tenant RBAC sharing

                        VirtualMachineScaleSet result;
                        if (auxAuthHeader != null)
                        {
                            var res = VirtualMachineScaleSetsClient.CreateOrUpdateWithHttpMessagesAsync(
                                resourceGroupName,
                                vmScaleSetName,
                                parameters,
                                auxAuthHeader).GetAwaiter().GetResult();

                            result = res.Body;
                        }
                        else
                        {
                            result = VirtualMachineScaleSetsClient.CreateOrUpdate(resourceGroupName, vmScaleSetName, parameters);
                        }
                        var psObject = new PSVirtualMachineScaleSet();
                        ComputeAutomationAutoMapperProfile.Mapper.Map <VirtualMachineScaleSet, PSVirtualMachineScaleSet>(result, psObject);
                        WriteObject(psObject);
                    }
                });
                break;
            }
        }
            private async Task <ResourceConfig <VirtualMachineScaleSet> > SimpleParameterSetNormalMode()
            {
                ImageAndOsType = await _client.UpdateImageAndOsTypeAsync(
                    ImageAndOsType, _cmdlet.ResourceGroupName, _cmdlet.ImageName, Location);


                // generate a domain name label if it's not specified.
                _cmdlet.DomainNameLabel = await PublicIPAddressStrategy.UpdateDomainNameLabelAsync(
                    domainNameLabel : _cmdlet.DomainNameLabel,
                    name : _cmdlet.VMScaleSetName,
                    location : Location,
                    client : _client);

                var resourceGroup = ResourceGroupStrategy.CreateResourceGroupConfig(_cmdlet.ResourceGroupName);

                var noZones = _cmdlet.Zone == null || _cmdlet.Zone.Count == 0;

                var publicIpAddress = resourceGroup.CreatePublicIPAddressConfig(
                    name: _cmdlet.PublicIpAddressName,
                    edgeZone: _cmdlet.EdgeZone,
                    domainNameLabel: _cmdlet.DomainNameLabel,
                    allocationMethod: _cmdlet.AllocationMethod,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? PublicIPAddressStrategy.Sku.Basic
                        : PublicIPAddressStrategy.Sku.Standard,
                    zones: null);

                var virtualNetwork = resourceGroup.CreateVirtualNetworkConfig(
                    name: _cmdlet.VirtualNetworkName,
                    edgeZone: _cmdlet.EdgeZone,
                    addressPrefix: _cmdlet.VnetAddressPrefix);

                var subnet = virtualNetwork.CreateSubnet(
                    _cmdlet.SubnetName, _cmdlet.SubnetAddressPrefix);

                var loadBalancer = resourceGroup.CreateLoadBalancerConfig(
                    name: _cmdlet.LoadBalancerName,
                    //sku.Basic is not compatible with multiple placement groups
                    sku: (noZones && _cmdlet.SinglePlacementGroup.IsPresent)
                        ? LoadBalancerStrategy.Sku.Basic
                        : LoadBalancerStrategy.Sku.Standard);

                var frontendIpConfiguration = loadBalancer.CreateFrontendIPConfiguration(
                    name: _cmdlet.FrontendPoolName,
                    publicIpAddress: publicIpAddress);

                var backendAddressPool = loadBalancer.CreateBackendAddressPool(
                    name: _cmdlet.BackendPoolName);

                if (_cmdlet.BackendPort != null)
                {
                    var loadBalancingRuleName = _cmdlet.LoadBalancerName;
                    foreach (var backendPort in _cmdlet.BackendPort)
                    {
                        loadBalancer.CreateLoadBalancingRule(
                            name: loadBalancingRuleName + backendPort.ToString(),
                            fronendIpConfiguration: frontendIpConfiguration,
                            backendAddressPool: backendAddressPool,
                            frontendPort: backendPort,
                            backendPort: backendPort);
                    }
                }

                _cmdlet.NatBackendPort = ImageAndOsType.UpdatePorts(_cmdlet.NatBackendPort);

                var inboundNatPoolName = _cmdlet.VMScaleSetName;
                var PortRangeSize      = _cmdlet.InstanceCount * 2;

                var ports = _cmdlet
                            .NatBackendPort
                            ?.Select((port, i) => Tuple.Create(
                                         port,
                                         FirstPortRangeStart + i * 2000))
                            .ToList();

                var inboundNatPools = ports
                                      ?.Select(p => loadBalancer.CreateInboundNatPool(
                                                   name: inboundNatPoolName + p.Item1.ToString(),
                                                   frontendIpConfiguration: frontendIpConfiguration,
                                                   frontendPortRangeStart: p.Item2,
                                                   frontendPortRangeEnd: p.Item2 + PortRangeSize,
                                                   backendPort: p.Item1))
                                      .ToList();

                var networkSecurityGroup = noZones
                    ? null
                    : resourceGroup.CreateNetworkSecurityGroupConfig(
                    _cmdlet.VMScaleSetName,
                    _cmdlet.NatBackendPort.Concat(_cmdlet.BackendPort).ToList());

                var proximityPlacementGroup = resourceGroup.CreateProximityPlacementGroupSubResourceFunc(_cmdlet.ProximityPlacementGroupId);

                var hostGroup = resourceGroup.CreateDedicatedHostGroupSubResourceFunc(_cmdlet.HostGroupId);

                if (_cmdlet.IsParameterBound(c => c.UserData))
                {
                    if (!ValidateBase64EncodedString.ValidateStringIsBase64Encoded(_cmdlet.UserData))
                    {
                        _cmdlet.UserData = ValidateBase64EncodedString.EncodeStringToBase64(_cmdlet.UserData);
                        _cmdlet.WriteInformation(ValidateBase64EncodedString.UserDataEncodeNotification, new string[] { "PSHOST" });
                    }
                }

                Dictionary <string, List <string> > auxAuthHeader = null;

                if (!string.IsNullOrEmpty(_cmdlet.ImageReferenceId))
                {
                    var resourceId = ResourceId.TryParse(_cmdlet.ImageReferenceId);

                    if (string.Equals(ComputeStrategy.Namespace, resourceId?.ResourceType?.Namespace, StringComparison.OrdinalIgnoreCase) &&
                        string.Equals("galleries", resourceId?.ResourceType?.Provider, StringComparison.OrdinalIgnoreCase) &&
                        !string.Equals(_cmdlet.ComputeClient?.ComputeManagementClient?.SubscriptionId, resourceId?.SubscriptionId, StringComparison.OrdinalIgnoreCase))
                    {
                        List <string> resourceIds = new List <string>();
                        resourceIds.Add(_cmdlet.ImageReferenceId);
                        var auxHeaderDictionary = _cmdlet.GetAuxilaryAuthHeaderFromResourceIds(resourceIds);
                        if (auxHeaderDictionary != null && auxHeaderDictionary.Count > 0)
                        {
                            auxAuthHeader = new Dictionary <string, List <string> >(auxHeaderDictionary);
                        }
                    }
                }

                return(resourceGroup.CreateVirtualMachineScaleSetConfig(
                           name: _cmdlet.VMScaleSetName,
                           subnet: subnet,
                           backendAdressPool: backendAddressPool,
                           inboundNatPools: inboundNatPools,
                           networkSecurityGroup: networkSecurityGroup,
                           imageAndOsType: ImageAndOsType,
                           adminUsername: _cmdlet.Credential.UserName,
                           adminPassword: new NetworkCredential(string.Empty, _cmdlet.Credential.Password).Password,
                           vmSize: _cmdlet.VmSize,
                           instanceCount: _cmdlet.InstanceCount,
                           upgradeMode: _cmdlet.MyInvocation.BoundParameters.ContainsKey(nameof(UpgradePolicyMode))
                        ? _cmdlet.UpgradePolicyMode
                        : (UpgradeMode?)null,
                           dataDisks: _cmdlet.DataDiskSizeInGb,
                           zones: _cmdlet.Zone,
                           ultraSSDEnabled: _cmdlet.EnableUltraSSD.IsPresent,
                           identity: _cmdlet.GetVmssIdentityFromArgs(),
                           singlePlacementGroup: _cmdlet.SinglePlacementGroup.IsPresent,
                           proximityPlacementGroup: proximityPlacementGroup,
                           hostGroup: hostGroup,
                           priority: _cmdlet.Priority,
                           evictionPolicy: _cmdlet.EvictionPolicy,
                           maxPrice: _cmdlet.IsParameterBound(c => c.MaxPrice) ? _cmdlet.MaxPrice : (double?)null,
                           scaleInPolicy: _cmdlet.ScaleInPolicy,
                           doNotRunExtensionsOnOverprovisionedVMs: _cmdlet.SkipExtensionsOnOverprovisionedVMs.IsPresent,
                           encryptionAtHost: _cmdlet.EncryptionAtHost.IsPresent,
                           platformFaultDomainCount: _cmdlet.IsParameterBound(c => c.PlatformFaultDomainCount) ? _cmdlet.PlatformFaultDomainCount : (int?)null,
                           edgeZone: _cmdlet.EdgeZone,
                           orchestrationMode: _cmdlet.IsParameterBound(c => c.OrchestrationMode) ? _cmdlet.OrchestrationMode : null,
                           capacityReservationId: _cmdlet.IsParameterBound(c => c.CapacityReservationGroupId) ? _cmdlet.CapacityReservationGroupId : null,
                           userData: _cmdlet.IsParameterBound(c => c.UserData) ? _cmdlet.UserData : null,
                           imageReferenceId: _cmdlet.IsParameterBound(c => c.ImageReferenceId) ? _cmdlet.ImageReferenceId : null,
                           auxAuthHeader: auxAuthHeader
                           ));
            }