/// <summary>
        /// Filters the subscription's resource groups.
        /// </summary>
        /// <param name="name">The resource group name.</param>
        /// <param name="tag">The resource group tag.</param>
        /// <param name="detailed">Whether the  return is detailed or not.</param>
        /// <param name="location">The resource group location.</param>
        /// <returns>The filtered resource groups</returns>
        public virtual List <PSResourceGroup> FilterResourceGroups(string name, Hashtable tag, bool detailed, string location = null)
        {
            List <PSResourceGroup> result = new List <PSResourceGroup>();

            if (string.IsNullOrEmpty(name))
            {
                var response = ResourceManagementClient.ResourceGroups.List(null);
                List <ResourceGroup> resourceGroups = ResourceManagementClient.ResourceGroups.List(null).ToList();

                while (!string.IsNullOrEmpty(response.NextPageLink))
                {
                    resourceGroups.AddRange(response);
                }

                resourceGroups = !string.IsNullOrEmpty(location)
                    ? resourceGroups.Where(resourceGroup => this.NormalizeLetterOrDigitToUpperInvariant(resourceGroup.Location).Equals(this.NormalizeLetterOrDigitToUpperInvariant(location))).ToList()
                    : resourceGroups;

                // TODO: Replace with server side filtering when available
                if (tag != null && tag.Count >= 1)
                {
                    PSTagValuePair tagValuePair = TagsConversionHelper.Create(tag);
                    if (tagValuePair == null)
                    {
                        throw new ArgumentException(ProjectResources.InvalidTagFormat);
                    }
                    if (string.IsNullOrEmpty(tagValuePair.Value))
                    {
                        resourceGroups =
                            resourceGroups.Where(rg => rg.Tags != null &&
                                                 rg.Tags.Keys.Contains(tagValuePair.Name,
                                                                       StringComparer.OrdinalIgnoreCase))
                            .Select(rg => rg).ToList();
                    }
                    else
                    {
                        resourceGroups =
                            resourceGroups.Where(rg => rg.Tags != null && rg.Tags.Keys.Contains(tagValuePair.Name,
                                                                                                StringComparer.OrdinalIgnoreCase))
                            .Where(rg => rg.Tags.Values.Contains(tagValuePair.Value,
                                                                 StringComparer.OrdinalIgnoreCase))
                            .Select(rg => rg).ToList();
                    }
                }
                result.AddRange(resourceGroups.Select(rg => rg.ToPSResourceGroup()));
            }
            else
            {
                try
                {
                    result.Add(ResourceManagementClient.ResourceGroups.Get(name).ToPSResourceGroup());
                }
                catch (CloudException)
                {
                    throw new ArgumentException(ProjectResources.ResourceGroupDoesntExists);
                }
            }

            return(result);
        }
        /// <summary>
        /// Queries the ARM cache and returns the cached resource groups that match the query specified.
        /// </summary>
        private async Task <ResponseWithContinuation <JObject[]> > GetResourceGroups()
        {
            var resourceGroupsId = string.Format("/subscriptions/{0}/resourceGroups", Uri.EscapeDataString(this.DefaultContext.Subscription.Id.ToString()));

            var apiVersion = await this
                             .DetermineApiVersion(resourceId : resourceGroupsId)
                             .ConfigureAwait(continueOnCapturedContext: false);

            string queryString = null;

            if (this.Tag != null)
            {
                var tagValuePair = TagsConversionHelper.Create(this.Tag);

                if (tagValuePair == null)
                {
                    throw new ArgumentException(ProjectResources.InvalidTagFormat);
                }

                queryString = tagValuePair.Value != null
                    ? string.Format("$filter=tagname eq '{0}' and tagvalue eq '{1}'", tagValuePair.Name, tagValuePair.Value)
                    : string.Format("$filter=tagname eq '{0}'", tagValuePair.Name);
            }

            return(await this
                   .GetResourcesClient()
                   .ListObjectColleciton <JObject>(
                       resourceCollectionId: resourceGroupsId,
                       apiVersion: apiVersion,
                       cancellationToken: this.CancellationToken.Value,
                       odataQuery: queryString)
                   .ConfigureAwait(continueOnCapturedContext: false));
        }
        protected List <T> FilterByTag <T>(List <T> listResult, Hashtable tag) where T : PSKeyVaultIdentityItem
        {
            var tagValuePair = new PSTagValuePair();

            if (tag != null && tag.Count > 0)
            {
                tagValuePair = TagsConversionHelper.Create(tag);
                if (tagValuePair == null)
                {
                    throw new ArgumentException(PSKeyVaultProperties.Resources.InvalidTagFormat);
                }
            }

            if (!string.IsNullOrEmpty(tagValuePair.Name))
            {
                listResult = listResult.Where(r => r.Tags?.Keys != null && r.Tags.ConvertToDictionary().Keys.Any(k => string.Equals(k, tagValuePair.Name, StringComparison.OrdinalIgnoreCase))).ToList();
            }

            if (!string.IsNullOrEmpty(tagValuePair.Value))
            {
                listResult = listResult.Where(r => r.Tags?.Values != null && r.Tags.ConvertToDictionary().Values.Any(v => string.Equals(v, tagValuePair.Value, StringComparison.OrdinalIgnoreCase))).ToList();
            }

            return(listResult);
        }
예제 #4
0
        protected List <PSKeyVaultModels.PSKeyVaultIdentityItem> ListVaults(string resourceGroupName, Hashtable tag)
        {
            IResourceManagementClient armClient = this.ResourceClient;

            PSTagValuePair tagValuePair = new PSTagValuePair();

            if (tag != null && tag.Count > 0)
            {
                tagValuePair = TagsConversionHelper.Create(tag);
                if (tagValuePair == null)
                {
                    throw new ArgumentException(PSKeyVaultProperties.Resources.InvalidTagFormat);
                }
            }
            var listResult   = Enumerable.Empty <PSKeyVaultIdentityItem>();
            var resourceType = KeyVaultManagementClient.VaultsResourceType;

            if (resourceGroupName != null)
            {
                listResult = this.ListByResourceGroup(resourceGroupName,
                                                      new Rest.Azure.OData.ODataQuery <GenericResourceFilter>(
                                                          r => r.ResourceType == resourceType));
            }
            else
            {
                listResult = this.ListResources(
                    new Rest.Azure.OData.ODataQuery <GenericResourceFilter>(
                        r => r.ResourceType == resourceType));
            }

            if (!string.IsNullOrEmpty(tagValuePair.Name))
            {
                listResult = listResult.Where(r => r.Tags != null && r.Tags.Keys != null && r.Tags.ConvertToDictionary().Keys.Where(k => string.Equals(k, tagValuePair.Name, StringComparison.OrdinalIgnoreCase)).Any());
            }

            if (!string.IsNullOrEmpty(tagValuePair.Value))
            {
                listResult = listResult.Where(r => r.Tags != null && r.Tags.Values != null && r.Tags.ConvertToDictionary().Values.Where(v => string.Equals(v, tagValuePair.Value, StringComparison.OrdinalIgnoreCase)).Any());
            }

            List <PSKeyVaultModels.PSKeyVaultIdentityItem> vaults = new List <PSKeyVaultModels.PSKeyVaultIdentityItem>();

            if (listResult != null)
            {
                vaults.AddRange(listResult);
            }

            return(vaults);
        }
예제 #5
0
        public static string ConstructTagsTable(Hashtable[] tags)
        {
            if (tags == null)
            {
                return(null);
            }

            Hashtable emptyHashtable = new Hashtable
            {
                { "Name", string.Empty },
                { "Value", string.Empty }
            };
            StringBuilder resourcesTable = new StringBuilder();

            if (tags.Length > 0)
            {
                int maxNameLength  = Math.Max("Name".Length, tags.Where(ht => ht.ContainsKey("Name")).DefaultIfEmpty(emptyHashtable).Max(ht => ht["Name"].ToString().Length));
                int maxValueLength = Math.Max("Value".Length, tags.Where(ht => ht.ContainsKey("Value")).DefaultIfEmpty(emptyHashtable).Max(ht => ht["Value"].ToString().Length));

                string rowFormat = "{0, -" + maxNameLength + "}  {1, -" + maxValueLength + "}\r\n";
                resourcesTable.AppendLine();
                resourcesTable.AppendFormat(rowFormat, "Name", "Value");
                resourcesTable.AppendFormat(rowFormat,
                                            GeneralUtilities.GenerateSeparator(maxNameLength, "="),
                                            GeneralUtilities.GenerateSeparator(maxValueLength, "="));

                foreach (Hashtable tag in tags)
                {
                    PSTagValuePair tagValuePair = TagsConversionHelper.Create(tag);
                    if (tagValuePair != null)
                    {
                        if (tagValuePair.Name.StartsWith(TagsClient.ExecludedTagPrefix))
                        {
                            continue;
                        }

                        if (tagValuePair.Value == null)
                        {
                            tagValuePair.Value = string.Empty;
                        }
                        resourcesTable.AppendFormat(rowFormat, tagValuePair.Name, tagValuePair.Value);
                    }
                }
            }

            return(resourcesTable.ToString());
        }
예제 #6
0
        /// <summary>
        /// Resolves the tag value given the tagObj and tagValue parameters. If both are specified then tagObj takes precedence.
        /// </summary>
        /// <param name="tagObjParameter">Parameter containing the tag name-value specified as a hashset.</param>
        /// <param name="tagValueParameter">Parameter containing the tag value specified individually.</param>
        /// <returns>The resolved tag value.</returns>
        internal static string GetTagValueFromParameters(Hashtable tagObjParameter, string tagValueParameter)
        {
            PSTagValuePair tagValuePair = null;

            if (tagObjParameter != null)
            {
                tagValuePair = TagsConversionHelper.Create(tagObjParameter);

                if (tagValuePair == null)
                {
                    throw new ArgumentException(ProjectResources.InvalidTagFormat);
                }
            }

            if (tagValuePair != null)
            {
                return(tagValuePair.Value);
            }
            return(tagValueParameter);
        }
        protected List <PSKeyVaultModels.PSVaultIdentityItem> ListVaults(string resourceGroupName, Hashtable tag)
        {
            IResourceManagementClient armClient = this.ResourcesClient.ResourceManagementClient;

            PSTagValuePair tagValuePair = new PSTagValuePair();

            if (tag != null && tag.Count > 0)
            {
                tagValuePair = TagsConversionHelper.Create(tag);
                if (tagValuePair == null)
                {
                    throw new ArgumentException(PSKeyVaultProperties.Resources.InvalidTagFormat);
                }
            }
            ResourceListResult listResult = armClient.Resources.List(new ResourceListParameters
            {
                ResourceGroupName = resourceGroupName,
                ResourceType      = tag == null ? KeyVaultManagementClient.VaultsResourceType : null,
                TagName           = tagValuePair.Name,
                TagValue          = tagValuePair.Value
            });

            List <PSKeyVaultModels.PSVaultIdentityItem> vaults = new List <PSKeyVaultModels.PSVaultIdentityItem>();

            if (listResult.Resources != null)
            {
                vaults.AddRange(listResult.Resources.Where(r => r.Type.Equals(KeyVaultManagementClient.VaultsResourceType, StringComparison.OrdinalIgnoreCase))
                                .Select(r => new PSKeyVaultModels.PSVaultIdentityItem(r)));
            }

            while (!string.IsNullOrEmpty(listResult.NextLink))
            {
                listResult = armClient.Resources.ListNext(listResult.NextLink);
                if (listResult.Resources != null)
                {
                    vaults.AddRange(listResult.Resources.Select(r => new PSKeyVaultModels.PSVaultIdentityItem(r)));
                }
            }

            return(vaults);
        }
예제 #8
0
        /// <summary>
        /// Filters the subscription's account with the given tag.
        /// </summary>
        /// <param name="account">The account to filter on.</param>
        /// <param name="tag">The tag to filter on.</param>
        /// <returns>Whether or not the account's tags match with the given tag</returns>
        public static bool MatchesTag(BatchAccount account, Hashtable tag)
        {
            if (tag != null && tag.Count >= 1)
            {
                PSTagValuePair tagValuePair = TagsConversionHelper.Create(tag);
                if (tagValuePair == null)
                {
                    throw new ArgumentException(Resources.InvalidTagFormat);
                }

                if (string.IsNullOrEmpty(tagValuePair.Value))
                {
                    return(ContainsTagWithName(account.Tags, tagValuePair.Name));
                }
                else
                {
                    return(ContainsTagWithName(account.Tags, tagValuePair.Name) &&
                           account.Tags[tagValuePair.Name] == tagValuePair.Value);
                }
            }

            return(true);
        }
예제 #9
0
        /// <summary>
        /// Filters the subscription's resource groups.
        /// </summary>
        /// <param name="name">The resource group name.</param>
        /// <param name="tag">The resource group tag.</param>
        /// <param name="detailed">Whether the  return is detailed or not.</param>
        /// <param name="location">The resource group location.</param>
        /// <returns>The filtered resource groups</returns>
        public virtual List <PSResourceGroup> FilterResourceGroups(string name, Hashtable tag, bool detailed, string location = null)
        {
            List <PSResourceGroup> result = new List <PSResourceGroup>();

            if (string.IsNullOrEmpty(name) || WildcardPattern.ContainsWildcardCharacters(name))
            {
                List <ResourceGroup> resourceGroups = new List <ResourceGroup>();

                var listResult = ResourceManagementClient.ResourceGroups.List(null);
                resourceGroups.AddRange(listResult);

                while (!string.IsNullOrEmpty(listResult.NextPageLink))
                {
                    listResult = ResourceManagementClient.ResourceGroups.ListNext(listResult.NextPageLink);
                    resourceGroups.AddRange(listResult);
                }

                if (!string.IsNullOrEmpty(name))
                {
                    WildcardPattern pattern = new WildcardPattern(name, WildcardOptions.IgnoreCase);
                    resourceGroups = resourceGroups.Where(t => pattern.IsMatch(t.Name)).ToList();
                }

                resourceGroups = !string.IsNullOrEmpty(location)
                    ? resourceGroups.Where(resourceGroup => resourceGroup.Location.EqualsAsLocation(location)).ToList()
                    : resourceGroups;

                // TODO: Replace with server side filtering when available
                if (tag != null && tag.Count >= 1)
                {
                    PSTagValuePair tagValuePair = TagsConversionHelper.Create(tag);
                    if (tagValuePair == null)
                    {
                        throw new ArgumentException(ProjectResources.InvalidTagFormat);
                    }
                    if (string.IsNullOrEmpty(tagValuePair.Value))
                    {
                        resourceGroups =
                            resourceGroups.Where(rg => rg.Tags != null &&
                                                 rg.Tags.Keys.Contains(tagValuePair.Name,
                                                                       StringComparer.OrdinalIgnoreCase))
                            .Select(rg => rg).ToList();
                    }
                    else
                    {
                        resourceGroups =
                            resourceGroups.Where(rg => rg.Tags != null && rg.Tags.Keys.Contains(tagValuePair.Name,
                                                                                                StringComparer.OrdinalIgnoreCase))
                            .Where(rg => rg.Tags.Values.Contains(tagValuePair.Value,
                                                                 StringComparer.OrdinalIgnoreCase))
                            .Select(rg => rg).ToList();
                    }
                }
                result.AddRange(resourceGroups.Select(rg => rg.ToPSResourceGroup()));
            }
            else
            {
                try
                {
                    result.Add(ResourceManagementClient.ResourceGroups.Get(name).ToPSResourceGroup());
                }
                catch (CloudException)
                {
                    WriteError(ProjectResources.ResourceGroupDoesntExists);
                }
            }

            return(result);
        }
예제 #10
0
        protected List <PSKeyVaultModels.PSVaultIdentityItem> ListVaults(string resourceGroupName, Hashtable tag)
        {
            IResourceManagementClient armClient = this.ResourceClient;

            PSTagValuePair tagValuePair = new PSTagValuePair();

            if (tag != null && tag.Count > 0)
            {
                tagValuePair = TagsConversionHelper.Create(tag);
                if (tagValuePair == null)
                {
                    throw new ArgumentException(PSKeyVaultProperties.Resources.InvalidTagFormat);
                }
            }
            IPage <GenericResource> listResult = null;
            var resourceType = tag == null ? KeyVaultManagementClient.VaultsResourceType : null;

            if (resourceGroupName != null)
            {
                listResult = armClient.ResourceGroups.ListResources(resourceGroupName,
                                                                    new Rest.Azure.OData.ODataQuery <GenericResourceFilter>(
                                                                        r => r.ResourceType == resourceType &&
                                                                        r.Tagname == tagValuePair.Name &&
                                                                        r.Tagvalue == tagValuePair.Value));
            }
            else
            {
                listResult = armClient.Resources.List(
                    new Rest.Azure.OData.ODataQuery <GenericResourceFilter>(
                        r => r.ResourceType == resourceType &&
                        r.Tagname == tagValuePair.Name &&
                        r.Tagvalue == tagValuePair.Value));
            }

            List <PSKeyVaultModels.PSVaultIdentityItem> vaults = new List <PSKeyVaultModels.PSVaultIdentityItem>();

            if (listResult != null)
            {
                vaults.AddRange(listResult.Where(r => r.Type.Equals(KeyVaultManagementClient.VaultsResourceType, StringComparison.OrdinalIgnoreCase))
                                .Select(r => new PSKeyVaultModels.PSVaultIdentityItem(r)));
            }

            while (!string.IsNullOrEmpty(listResult.NextPageLink))
            {
                if (resourceGroupName != null)
                {
                    listResult = armClient.ResourceGroups.ListResourcesNext(listResult.NextPageLink);
                }
                else
                {
                    listResult = armClient.Resources.ListNext(listResult.NextPageLink);
                }

                if (listResult != null)
                {
                    vaults.AddRange(listResult.Select(r => new PSKeyVaultModels.PSVaultIdentityItem(r)));
                }
            }

            return(vaults);
        }