Esempio n. 1
0
        public Subnet CreateNewSubnet(string newSubnetName, string newSubnetAddressPrefix)
        {
            var tokens        = ResourceId.Split('/');
            var newResourceId = ResourceId.Replace($"/{tokens.Last()}", $"/{newSubnetName}");

            return(new Subnet($"{newResourceId}{Delimiter}{Location}{Delimiter}{newSubnetAddressPrefix}{Delimiter}{VNetAddressPrefixes}"));
        }
Esempio n. 2
0
        /// <summary>
        /// Helper method to parse resourceGroupName, serverName, databaseName from resourceId
        /// Ideally this would utilize Microsoft.Azure.Management.Internal.Resources.Utilities.Models.ResourceIdentifier
        /// However, that class is not setup to handle resources that have an ancestry higher than just parent level.
        /// That class could recursively create a parent ResourceIdentifier on a __get__ ParentResource,
        /// rather than just a string, so a consumer could work all the way to the root resource easily.
        /// Leave as a TODO for now, as many other cmdlets consume that class, and I will work on it in separate change.
        /// </summary>
        private void ParseResourceId()
        {
            string[] tokens = ResourceId.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            // "/subscriptions/<subId>/resourceGroups/<resourceGroup>/providers/Microsoft.Sql/servers/<server>/databases/<database>/backupShortTermRetentionPolicies/default"
            if (tokens.Length != BackupShortTermRetentionPolicyResourceIdSegmentsLength)
            {
                throw new ArgumentException("Invalid format of the resource identifier.", "ResourceId");
            }

            // Convert tokens into TYPE:NAME key value pairs, ignoring case
            Dictionary <string, string> segments = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
            int i = 0;

            while (i < tokens.Length)
            {
                string type = tokens[i++];
                string name = tokens[i++];
                segments[type] = name;
            }

            try
            {
                this.ResourceGroupName = segments["resourceGroups"];
                this.ServerName        = segments["servers"];
                this.DatabaseName      = segments["databases"];
            }
            catch (KeyNotFoundException)
            {
                throw new ArgumentException(
                          "Invalid format of the resource identifier. ResourceID should follow format /subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>/providers/Microsoft.Sql/servers/<serverName>/databases/<databaseName>/backupShortTermRetentionPolicies/default");
            }
        }
        public override void Execute()
        {
            base.Execute();

            if (string.IsNullOrEmpty(this.Name))
            {
                if (!string.IsNullOrEmpty(this.ResourceId))
                {
                    string[] SplittedName = ResourceId.Split('/');
                    // Name is in the form resourceName(ResourceGroupName)
                    this.Name = SplittedName[8] + "(" + SplittedName[4] + ")";
                }
                else if (!string.IsNullOrEmpty(this.Address))
                {
                    this.Name = this.Address;
                }
            }

            PSNetworkWatcherConnectionMonitorEndpointObject endpoint = new PSNetworkWatcherConnectionMonitorEndpointObject()
            {
                Name       = this.Name,
                ResourceId = this.ResourceId,
                Address    = this.Address,
            };

            if (this.FilterItem != null)
            {
                endpoint.Filter = new PSNetworkWatcherConnectionMonitorEndpointFilter()
                {
                    Type = FilterType == null ? "Include" : this.FilterType
                };

                foreach (PSNetworkWatcherConnectionMonitorEndpointFilterItem Item in this.FilterItem)
                {
                    if (endpoint.Filter.Items == null)
                    {
                        endpoint.Filter.Items = new List <PSNetworkWatcherConnectionMonitorEndpointFilterItem>();
                    }

                    endpoint.Filter.Items.Add(new PSNetworkWatcherConnectionMonitorEndpointFilterItem()
                    {
                        Type    = string.IsNullOrEmpty(Item.Type) ? "AgentAddress" : Item.Type,
                        Address = Item.Address
                    });
                }
            }

            this.ValidateEndpoint(endpoint);

            WriteObject(endpoint);
        }
        /// <summary>
        /// Helper method to parse resourceGroupName, serverName, databaseName from resourceId
        /// Ideally this would utilize Microsoft.Azure.Management.Internal.Resources.Utilities.Models.ResourceIdentifier
        /// However, that class is not setup to handle resources that have an ancestry higher than just parent level.
        /// That class could recursively create a parent ResourceIdentifier on a __get__ ParentResource,
        /// rather than just a string, so a consumer could work all the way to the root resource easily.
        /// Leave as a TODO for now, as many other cmdlets consume that class, and I will work on it in separate change.
        /// </summary>
        internal void ParseResourceId()
        {
            string[] tokens = ResourceId.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            // "/subscriptions/<subId>/resourceGroups/<resourceGroup>/providers/Microsoft.Sql/managedInstances/<managedInstance>/databases/<database>/backupShortTermRetentionPolicies/default"
            if (tokens.Length != BackupShortTermRetentionPolicyResourceIdSegmentsLength)
            {
                throw new ArgumentException(Resources.InvalidFormatResourceId, "ResourceId");
            }

            // Convert tokens into TYPE:NAME key value pairs, ignoring case
            Dictionary <string, string> segments = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
            int i = 0;

            while (i < tokens.Length)
            {
                string type = tokens[i++];
                string name = tokens[i++];
                segments[type] = name;
            }

            try
            {
                this.ResourceGroupName = segments["resourceGroups"];
                this.InstanceName      = segments["managedInstances"];
                if (segments.ContainsKey("databases"))
                {
                    this.DatabaseName = segments["databases"];
                }
                else
                {
                    int idx = segments["restorableDroppedDatabases"].LastIndexOf(',');

                    if (idx != -1)
                    {
                        this.DatabaseName = segments["restorableDroppedDatabases"].Substring(0, idx);
                        this.DeletionDate = DateTime.FromFileTimeUtc(Convert.ToInt64(segments["restorableDroppedDatabases"].Substring(idx + 1)));
                    }
                    else
                    {
                        throw new ArgumentException(Resources.InvalidFormatResourceId, "ResourceId");
                    }
                }
            }
            catch (KeyNotFoundException)
            {
                throw new ArgumentException(Resources.InvalidFormatResourceId, "ResourceId");
            }
        }
Esempio n. 5
0
        public override void ExecuteCmdlet()
        {
            ExecutionBlock(() =>
            {
                string containerName = Container != null ? Container.Name : ResourceId.Split('/')[8];
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.RegisterContainerWarning, containerName),
                    Resources.RegisterContainerMessage,
                    containerName, () =>
                {
                    base.ExecuteCmdlet();

                    ResourceIdentifier resourceIdentifier = new ResourceIdentifier(VaultId);
                    string vaultName = resourceIdentifier.ResourceName;
                    string vaultResourceGroupName = resourceIdentifier.ResourceGroupName;

                    PsBackupProviderManager providerManager =
                        new PsBackupProviderManager(new Dictionary <Enum, object>()
                    {
                        { VaultParams.VaultName, vaultName },
                        { VaultParams.ResourceGroupName, vaultResourceGroupName },
                        { ContainerParams.Name, containerName },
                        { ContainerParams.ContainerType, ServiceClientHelpers.GetServiceClientWorkloadType(WorkloadType).ToString() },
                        { ContainerParams.BackupManagementType, BackupManagementType.ToString() },
                        { ContainerParams.Container, Container }
                    }, ServiceClientAdapter);

                    IPsBackupProvider psBackupProvider =
                        providerManager.GetProviderInstance(WorkloadType, BackupManagementType);
                    psBackupProvider.RegisterContainer();

                    // List containers
                    string backupManagementType = BackupManagementType.ToString();
                    ODataQuery <BMSContainerQueryObject> queryParams = new ODataQuery <BMSContainerQueryObject>(
                        q => q.FriendlyName == containerName &&
                        q.BackupManagementType == backupManagementType);

                    var listResponse = ServiceClientAdapter.ListContainers(queryParams,
                                                                           vaultName: vaultName, resourceGroupName: vaultResourceGroupName);
                    var containerModels = ConversionHelpers.GetContainerModelList(listResponse);
                    WriteObject(containerModels, enumerateCollection: true);
                });
            }, ShouldProcess(ResourceId, VerbsLifecycle.Register));
        }
Esempio n. 6
0
        public override void ExecuteCmdlet()
        {
            switch (ParameterSetName)
            {
            case ParameterSetNames.SolutionLevelResource:
                break;

            case ParameterSetNames.ResourceId:
                ResourceGroupName = AzureIdUtilities.GetResourceGroup(ResourceId);
                SolutionName      = AzureIdUtilities.GetIotSolutionResourceName(ResourceId);
                var idParts = ResourceId.Split('/');
                if (idParts.Length > 2)
                {
                    Name = $"{idParts[idParts.Length - 2]}/{idParts[idParts.Length - 1]}";
                }
                else
                {
                    throw new ArgumentException("Invalid format of the resource identifier.", "ResourceId");
                }
                break;

            case ParameterSetNames.InputObject:
                ResourceGroupName = AzureIdUtilities.GetResourceGroup(InputObject.Id);
                SolutionName      = AzureIdUtilities.GetIotSolutionResourceName(InputObject.Id);
                Name = AzureIdUtilities.GetResourceName(InputObject.Name);
                break;

            default:
                throw new PSInvalidOperationException();
            }

            if (ShouldProcess(Name, VerbsCommon.Set))
            {
                SecurityCenterClient.IotSecuritySolutionsAnalyticsAggregatedAlert.DismissWithHttpMessagesAsync(ResourceGroupName, SolutionName, Name).GetAwaiter().GetResult();
            }

            if (PassThru.IsPresent)
            {
                WriteObject(true);
            }
        }
Esempio n. 7
0
        public override void ExecuteApiManagementCmdlet()
        {
            string resourceGroupName;
            string serviceName;
            bool   isCert;

            string entityId;

            if (ParameterSetName.Equals(ByInputObjectParameterSet))
            {
                if (InputObjectNamedvalue != null)
                {
                    isCert            = false;
                    entityId          = InputObjectNamedvalue.NamedValueId;
                    resourceGroupName = InputObjectNamedvalue.ResourceGroupName;
                    serviceName       = InputObjectNamedvalue.ServiceName;
                }
                else if (InputObjectCert != null)
                {
                    isCert            = true;
                    entityId          = InputObjectCert.CertificateId;
                    resourceGroupName = InputObjectCert.ResourceGroupName;
                    serviceName       = InputObjectCert.ServiceName;
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Object not exist."));
                }
            }
            else
            {
                var split      = ResourceId.Split('/');
                var entityType = split[split.Length - 2];
                if (string.Equals(entityType, "certificates", StringComparison.OrdinalIgnoreCase))
                {
                    isCert = true;
                    var psBackend = new PsApiManagementCertificate(ResourceId);
                    resourceGroupName = psBackend.ResourceGroupName;
                    serviceName       = psBackend.ServiceName;
                    entityId          = psBackend.CertificateId;
                }
                else if (string.Equals(entityType, "namedvalues", StringComparison.OrdinalIgnoreCase))
                {
                    isCert = false;
                    var psBackend = new PsApiManagementNamedValue(ResourceId);
                    resourceGroupName = psBackend.ResourceGroupName;
                    serviceName       = psBackend.ServiceName;
                    entityId          = psBackend.NamedValueId;
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Object with Id {0} supported for a KeyVault refresh.", ResourceId));
                }
            }

            if (string.IsNullOrEmpty(entityId))
            {
                throw new InvalidOperationException(string.Format("Object with Id {0} supported for a KeyVault refresh.", entityId));
            }

            if (ShouldProcess(entityId, Resources.RefreshKeyVaultBasedObject))
            {
                if (isCert)
                {
                    var entity = Client.CertificateKeyVaultRefresh(resourceGroupName, serviceName, entityId);
                    WriteObject(entity);
                }
                else
                {
                    var entity = Client.NamedValueKeyVaultRefresh(resourceGroupName, serviceName, entityId);
                    WriteObject(entity);
                }
            }
        }