Skip to content

HPF PR: dev <- Azure:dev #547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 4, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

/// <summary>
/// String extension methods
Expand Down Expand Up @@ -94,5 +95,24 @@ public static bool IsDateTime(this string source, string format, DateTimeStyles
DateTime parsedDateTime;
return DateTime.TryParseExact(s: source, format: format, provider: null, style: styles, result: out parsedDateTime);
}

/// <summary>
/// Normalize a location string.
/// </summary>
/// <param name="location">The location string.</param>
public static string ToNormalizedLocation(this string location)
{
return location == null ? null : new string(location.Where(c => char.IsLetterOrDigit(c)).ToArray());
}

/// <summary>
/// Compare two location strings.
/// </summary>
/// <param name="location1">The first location string.</param>
/// <param name="location2">The second location string.</param>
public static bool EqualsAsLocation(this string location1, string location2)
{
return location1.ToNormalizedLocation().EqualsInsensitively(location2.ToNormalizedLocation());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@

namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation
{
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkExtensions;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;

/// <summary>
/// Get an existing resource.
Expand Down Expand Up @@ -59,7 +61,7 @@ public class GetAzureProviderCmdlet : ResourceManagerCmdletBase
/// </summary>
public override void ExecuteCmdlet()
{
var providers = this.ResourceManagerSdkClient.ListPSResourceProviders(providerName: this.ProviderNamespace, listAvailable: this.ListAvailable, location: this.Location);
var providers = this.ListPSResourceProviders();

if (!string.IsNullOrEmpty(this.ProviderNamespace))
{
Expand Down Expand Up @@ -89,5 +91,38 @@ public override void ExecuteCmdlet()
this.WriteObject(providers, enumerateCollection: true);
}
}

private PSResourceProvider[] ListPSResourceProviders()
{
var providers = this.ResourceManagerSdkClient.ListResourceProviders(
providerName: this.ProviderNamespace,
listAvailable: this.ListAvailable);

if (string.IsNullOrEmpty(this.Location))
{
return providers
.Select(provider => provider.ToPSResourceProvider())
.ToArray();
}

var validLocations = this.SubscriptionSdkClient.ListLocations(DefaultContext.Subscription.Id.ToString());

if (!validLocations.Any(loc => loc.Name.EqualsAsLocation(this.Location)))
{
return new PSResourceProvider[] { };
}

foreach (var provider in providers)
{
provider.ResourceTypes = provider.ResourceTypes
.Where(type => !type.Locations.Any() || type.Locations.Any(loc => loc.EqualsAsLocation(this.Location)))
.ToList();
}

return providers
.Where(provider => provider.ResourceTypes.Any())
.Select(provider => provider.ToPSResourceProvider())
.ToArray();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,6 @@ public class MoveAzureResourceCommand : ResourceManagerCmdletBase
[Alias("Id", "SubscriptionId")]
public Guid? DestinationSubscriptionId { get; set; }

/// <summary>
/// Gets or sets a value that indicates if the user should be prompted for confirmation.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
public SwitchParameter Force { get; set; }

/// <summary>
/// Gets or sets the ids of the resources to move.
/// </summary>
Expand All @@ -66,6 +60,12 @@ public class MoveAzureResourceCommand : ResourceManagerCmdletBase
[ValidateNotNullOrEmpty]
public string[] ResourceId { get; set; }

/// <summary>
/// Gets or sets a value that indicates if the user should be prompted for confirmation.
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Do not ask for confirmation.")]
public SwitchParameter Force { get; set; }

/// <summary>
/// Collects subscription ids from the pipeline.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,34 +282,34 @@
</ListControl>
</View>
<View>
<Name>Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceProviderType</Name>
<Name>Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceProvider</Name>
<ViewSelectedBy>
<TypeName>Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceProviderType</TypeName>
<TypeName>Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceProvider</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Name</Label>
<Width>50</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Locations</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<Wrap/>
<TableColumnItems>
<TableColumnItem>
<ScriptBlock>$_.Name</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>$_.LocationsString</ScriptBlock>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<Label>ProviderNamespace</Label>
<PropertyName>ProviderNamespace</PropertyName>
</ListItem>
<ListItem>
<Label>RegistrationState</Label>
<PropertyName>RegistrationState</PropertyName>
</ListItem>
<ListItem>
<Label>ResourceTypes</Label>
<PropertyName>ResourceTypes</PropertyName>
</ListItem>
<ListItem>
<Label>Locations</Label>
<PropertyName>Locations</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
</ViewDefinitions>
</Configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkExtensions;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Utilities;
Expand Down Expand Up @@ -430,30 +431,6 @@ private TemplateValidationInfo CheckBasicDeploymentErrors(string resourceGroup,
return new TemplateValidationInfo(validationResult);
}

public virtual PSResourceProvider[] ListPSResourceProviders(string providerName = null, bool listAvailable = false, string location = null)
{
var providers = this.ListResourceProviders(providerName: providerName, listAvailable: listAvailable);

if (string.IsNullOrEmpty(location))
{
return providers
.Select(provider => provider.ToPSResourceProvider())
.ToArray();
}

foreach (var provider in providers)
{
provider.ResourceTypes = provider.ResourceTypes
.Where(type => !type.Locations.Any() || this.ContainsNormalizedLocation(type.Locations.ToArray(), location))
.ToList();
}

return providers
.Where(provider => provider.ResourceTypes.Any())
.Select(provider => provider.ToPSResourceProvider())
.ToArray();
}

public virtual List<Provider> ListResourceProviders(string providerName = null, bool listAvailable = true)
{
if (!string.IsNullOrEmpty(providerName))
Expand Down Expand Up @@ -485,16 +462,6 @@ public virtual List<Provider> ListResourceProviders(string providerName = null,
}
}

private bool ContainsNormalizedLocation(string[] locations, string location)
{
return locations.Any(existingLocation => this.NormalizeLetterOrDigitToUpperInvariant(existingLocation).Equals(this.NormalizeLetterOrDigitToUpperInvariant(location)));
}

private string NormalizeLetterOrDigitToUpperInvariant(string value)
{
return value != null ? new string(value.Where(c => char.IsLetterOrDigit(c)).ToArray()).ToUpperInvariant() : null;
}

private bool IsProviderRegistered(Provider provider)
{
return string.Equals(
Expand Down Expand Up @@ -540,64 +507,6 @@ public ResourceIdentifier[] ParseResourceIds(string[] resourceIds)
.ToArray();
}

/// <summary>
/// Get a mapping of Resource providers that support the operations API (/operations) to the operations api-version supported for that RP
/// (Current logic is to prefer the latest "non-test' api-version. If there are no such version, choose the latest one)
/// </summary>
public Dictionary<string, string> GetResourceProvidersWithOperationsSupport()
{
PSResourceProvider[] allProviders = this.ListPSResourceProviders(listAvailable: true);

Dictionary<string, string> providersSupportingOperations = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
PSResourceProviderResourceType[] providerResourceTypes = null;

foreach (PSResourceProvider provider in allProviders)
{
providerResourceTypes = provider.ResourceTypes;
if (providerResourceTypes != null && providerResourceTypes.Any())
{
PSResourceProviderResourceType operationsResourceType = providerResourceTypes.Where(r => r != null && r.ResourceTypeName == ResourceManagerSdkClient.Operations).FirstOrDefault();
if (operationsResourceType != null &&
operationsResourceType.ApiVersions != null &&
operationsResourceType.ApiVersions.Any())
{
string[] allowedTestPrefixes = new[] { "-preview", "-alpha", "-beta", "-rc", "-privatepreview" };
List<string> nonTestApiVersions = new List<string>();

foreach (string apiVersion in operationsResourceType.ApiVersions)
{
bool isTestApiVersion = false;
foreach (string testPrefix in allowedTestPrefixes)
{
if (apiVersion.EndsWith(testPrefix, StringComparison.InvariantCultureIgnoreCase))
{
isTestApiVersion = true;
break;
}
}

if (isTestApiVersion == false && !nonTestApiVersions.Contains(apiVersion))
{
nonTestApiVersions.Add(apiVersion);
}
}

if (nonTestApiVersions.Any())
{
string latestNonTestApiVersion = nonTestApiVersions.OrderBy(o => o).Last();
providersSupportingOperations.Add(provider.ProviderNamespace, latestNonTestApiVersion);
}
else
{
providersSupportingOperations.Add(provider.ProviderNamespace, operationsResourceType.ApiVersions.OrderBy(o => o).Last());
}
}
}
}

return providersSupportingOperations;
}

/// <summary>
/// Creates a new resource group
/// </summary>
Expand Down Expand Up @@ -667,7 +576,7 @@ public virtual List<PSResourceGroup> FilterResourceGroups(string name, Hashtable
}

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

// TODO: Replace with server side filtering when available
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,31 +49,40 @@ public class GetAzureProviderCmdletTests : RMTestBase
private MockCommandRuntime mockRuntime;

/// <summary>
/// A mock of the client
/// A mock of the IProvidersOperations
/// </summary>
private readonly Mock<IProvidersOperations> providerOperationsMock;

/// <summary>
/// A mock of the ISubscriptionsOperations
/// </summary>
private readonly Mock<ISubscriptionsOperations> subscriptionsOperationsMock;

/// <summary>
/// Initializes a new instance of the <see cref="GetAzureProviderCmdletTests"/> class.
/// </summary>
public GetAzureProviderCmdletTests(ITestOutputHelper output)
{
this.providerOperationsMock = new Mock<IProvidersOperations>();
this.subscriptionsOperationsMock = new Mock<ISubscriptionsOperations>();
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
var resourceManagementClient = new Mock<Microsoft.Azure.Management.ResourceManager.IResourceManagementClient>();
var subscriptionClient = new Mock<Microsoft.Azure.Management.ResourceManager.ISubscriptionClient>();

resourceManagementClient
.SetupGet(client => client.Providers)
.Returns(() => this.providerOperationsMock.Object);

subscriptionClient
.SetupGet(client => client.Subscriptions)
.Returns(() => this.subscriptionsOperationsMock.Object);

this.commandRuntimeMock = new Mock<ICommandRuntime>();
this.cmdlet = new GetAzureProviderCmdletTest
{
//CommandRuntime = commandRuntimeMock.Object,
ResourceManagerSdkClient = new ResourceManagerSdkClient
{
ResourceManagementClient = resourceManagementClient.Object,
}
ResourceManagerSdkClient = new ResourceManagerSdkClient(resourceManagementClient.Object),
SubscriptionSdkClient = new SubscriptionSdkClient(subscriptionClient.Object)
};
PSCmdletExtensions.SetCommandRuntimeMock(cmdlet, commandRuntimeMock.Object);
mockRuntime = new MockCommandRuntime();
Expand Down Expand Up @@ -134,6 +143,25 @@ public void GetsResourceProviderTests()
.Setup(f => f.ListWithHttpMessagesAsync(null, null, It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(result));

var locationList = new List<Location>
{
new Location
{
Name = "southus",
DisplayName = "South US",
}
};
var pagableLocations = new Page<Location>();
pagableLocations.SetItemValue<Location>(locationList);
var locationsResult = new AzureOperationResponse<IPage<Location>>()
{
Body = pagableLocations
};
this.subscriptionsOperationsMock
.Setup(f => f.ListLocationsWithHttpMessagesAsync(It.IsAny<string>(), null, It.IsAny<CancellationToken>()))
.Returns(() => Task.FromResult(locationsResult));


// 1. List only registered providers
this.commandRuntimeMock
.Setup(m => m.WriteObject(It.IsAny<object>()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ function Test-AzureProvider

Assert-True { $allProviders.Length -gt $defaultProviders.Length }

$nonProviders = Get-AzureRmResourceProvider -Location "abc"

Assert-True { $nonProviders.Length -eq 0 }

Register-AzureRmResourceProvider -ProviderName "Microsoft.ApiManagement" -Force

$endTime = [DateTime]::UtcNow.AddMinutes(5)
Expand Down
Loading