private Tuple<IAccessToken, string> GetToken(IAuthenticationFactory authFactory, AzureContext context)
        {
            if (context.Subscription == null)
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidCurrentSubscription);
            if (context.Account == null)
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidSubscriptionState);
            if (context.Account.Type != AzureAccount.AccountType.User)
                throw new ArgumentException(string.Format(KeyVaultProperties.Resources.UnsupportedAccountType, context.Account.Type));
            var tenant = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                  .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                  .FirstOrDefault();
            if (tenant == null)
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidSubscriptionState);
          
            try
            {
                var accesstoken = authFactory.Authenticate(context.Account, context.Environment, tenant, null, ShowDialog.Auto,
                    ResourceIdEndpoint);

                return Tuple.Create(accesstoken, context.Environment.Endpoints[ResourceIdEndpoint]);
            }
            catch (Exception ex)
            {
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidSubscriptionState, ex);
            }        
        }
        /// <summary>
        /// Determines the API version.
        /// </summary>
        /// <param name="context">The azure profile.</param>
        /// <param name="providerNamespace">The provider namespace.</param>
        /// <param name="resourceType">The resource type.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
        internal static Task<string> DetermineApiVersion(AzureContext context, string providerNamespace, string resourceType, CancellationToken cancellationToken, bool? pre = null, Dictionary<string, string> cmdletHeaderValues = null)
        {
            var cacheKey = ApiVersionCache.GetCacheKey(providerNamespace: providerNamespace, resourceType: resourceType);
            var apiVersions = ApiVersionCache.Instance
                .AddOrGetExisting(cacheKey: cacheKey, getFreshData: () => ApiVersionHelper.GetApiVersionsForResourceType(
                    context,
                    providerNamespace: providerNamespace,
                    resourceType: resourceType,
                    cancellationToken: cancellationToken,
                    cmdletHeaderValues: cmdletHeaderValues));

            apiVersions = apiVersions.CoalesceEnumerable().ToArray();
            var apiVersionsToSelectFrom = apiVersions;
            if (pre == null || pre  == false)
            {
                apiVersionsToSelectFrom = apiVersions
                    .Where(apiVersion => apiVersion.IsDecimal(NumberStyles.AllowDecimalPoint) || apiVersion.IsDateTime("yyyy-mm-dd", DateTimeStyles.None))
                    .ToArray();
            }

            var selectedApiVersion = apiVersionsToSelectFrom.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();
            if (string.IsNullOrWhiteSpace(selectedApiVersion) && apiVersions.Any())
            {
                // fall back on pre-release APIs if they're the only ones available.
                selectedApiVersion = apiVersions.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();
            }

            var result = string.IsNullOrWhiteSpace(selectedApiVersion) 
                ? Constants.DefaultApiVersion
                : selectedApiVersion;

            return Task.FromResult(result);
        }
        private Tuple<IAccessToken, string> GetToken(IAuthenticationFactory authFactory, AzureContext context, AzureEnvironment.Endpoint resourceIdEndpoint)
        {
            if (context.Account == null)
                throw new ArgumentException(KeyVaultProperties.Resources.ArmAccountNotFound);

            if (context.Account.Type != AzureAccount.AccountType.User &&
                context.Account.Type != AzureAccount.AccountType.ServicePrincipal )
                throw new ArgumentException(string.Format(KeyVaultProperties.Resources.UnsupportedAccountType, context.Account.Type));

            if (context.Subscription != null && context.Account != null)
                TenantId = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                       .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                       .FirstOrDefault();

            if (string.IsNullOrWhiteSpace(TenantId) && context.Tenant != null && context.Tenant.Id != Guid.Empty)
                TenantId = context.Tenant.Id.ToString();

            if (string.IsNullOrWhiteSpace(TenantId))
                throw new ArgumentException(KeyVaultProperties.Resources.NoTenantInContext);
          
            try
            {
                var accesstoken = authFactory.Authenticate(context.Account, context.Environment, TenantId, null, ShowDialog.Auto,
                    resourceIdEndpoint);

                return Tuple.Create(accesstoken, context.Environment.Endpoints[resourceIdEndpoint]);
            }
            catch (Exception ex)
            {
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidSubscriptionState, ex);
            }        
        }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseAdapter(AzureContext context)
 {
     Context = context;
     _subscription = context.Subscription;
     Communicator = new AzureSqlDatabaseCommunicator(Context);
     ElasticPoolCommunicator = new AzureSqlElasticPoolCommunicator(Context);
 }
 private static RMProfileClient SetupTestEnvironment(List<string> tenants, params List<string>[] subscriptionLists)
 {
     AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory(DefaultAccount,
         Guid.NewGuid().ToString(), DefaultTenant.ToString());
     var subscriptionList = new Queue<List<string>>(subscriptionLists);
     var clientFactory = new MockSubscriptionClientFactory(tenants, subscriptionList);
     var mock = new MockClientFactory(new List<object>
     {
         clientFactory.GetSubscriptionClient()
     }, true);
     mock.MoqClients = true;
     AzureSession.ClientFactory = mock;
     var context = new AzureContext(new AzureSubscription()
         {
             Account = DefaultAccount,
             Environment = EnvironmentName.AzureCloud,
             Id = DefaultSubscription,
             Name = DefaultSubscriptionName
         },
         new AzureAccount() { Id = DefaultAccount, Type = AzureAccount.AccountType.User },
         AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud],
         new AzureTenant() { Domain = DefaultDomain, Id = DefaultTenant });
     var profile = new AzureRMProfile();
     profile.Context = context;
     return new RMProfileClient(profile);
 }
 public SqlThreatDetectionAdapter(AzureContext context)
 {
     Context = context;
     Subscription = context.Subscription;
     ThreatDetectionCommunicator = new ThreatDetectionEndpointsCommunicator(Context);
     AzureCommunicator = new AzureEndpointsCommunicator(Context);
     AuditingAdapter = new SqlAuditAdapter(context);
 }
 /// <summary>
 /// Creates new ActiveDirectoryClient using WindowsAzureSubscription.
 /// </summary>
 /// <param name="context"></param>
 public ActiveDirectoryClient(AzureContext context)
 {
     AccessTokenCredential creds = (AccessTokenCredential)AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
     GraphClient = AzureSession.ClientFactory.CreateCustomClient<GraphRbacManagementClient>(
         creds.TenantID,
         creds,
         context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.Graph));
 }
 public SqlAuditAdapter(AzureContext context)
 {
     Context = context;
     Subscription = context.Subscription;
     Communicator = new AuditingEndpointsCommunicator(Context);
     AzureCommunicator = new AzureEndpointsCommunicator(Context);
     IgnoreStorage = false;
 }
        /// <summary>
        /// Creates new ResourceManagementClient
        /// </summary>
        /// <param name="context">Profile containing resources to manipulate</param>
        public ResourcesClient(AzureContext context)
            : this(
                AzureSession.ClientFactory.CreateClient<ResourceManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager),
                new GalleryTemplatesClient(context),
                AzureSession.ClientFactory.CreateClient<AuthorizationManagementClient>(context, AzureEnvironment.Endpoint.ResourceManager))
        {

        }
 /// <summary>
 /// Initialize method
 /// </summary>
 public void Initialize(AzureContext defaultContext, string apiVersion)
 {
     if (!this.Initialized)
     {
         this.IntuneClient = IntuneBaseCmdlet.GetIntuneManagementClient(defaultContext, apiVersion);
         this.Initialized = true;
     }
 }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseReplicationAdapter(AzureContext context)
 {
     Context = context;
     _subscription = context.Subscription;
     ReplicationCommunicator = new AzureSqlDatabaseReplicationCommunicator(Context);
     DatabaseCommunicator = new AzureSqlDatabaseCommunicator(Context);
     ServerCommunicator = new AzureSqlServerCommunicator(Context);
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases FirewallRules
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlCapabilitiesCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
        public NotificationHubsManagementClient(AzureContext azureContext)
        {
            if (azureContext == null)
            {
                throw new ArgumentNullException("azureContext");
            }

            _context = azureContext;
        }
 public ThreatDetectionEndpointsCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Recommended Elastic Pool
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlElasticPoolRecommendationCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases TransparentDataEncryption
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlDatabaseTransparentDataEncryptionCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure SQL Server Active Directory administrator
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServerActiveDirectoryAdministratorCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlDatabaseActivationCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Service Tier Advisor
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServiceTierAdvisorCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
        public ApiManagementClient(AzureContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("AzureProfile");
            }

            _context = context;
        }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases ServiceObjective
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServerServiceObjectiveCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 public AuditingEndpointsCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Elastic Pool
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServerCommunicationLinkCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         SqlClient = null;
     }
 }
        public DataServiceCredential(IAuthenticationFactory authFactory, AzureContext context, AzureEnvironment.Endpoint resourceIdEndpoint)
        {
            if (authFactory == null)
                throw new ArgumentNullException("authFactory");
            if (context == null)
                throw new ArgumentNullException("context");

            var bundle = GetToken(authFactory, context, resourceIdEndpoint);
            this.token = bundle.Item1;
        }
        /// <summary>
        /// Determines the API version.
        /// </summary>
        /// <param name="context">The azure profile.</param>
        /// <param name="resourceId">The resource Id.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
        internal static Task<string> DetermineApiVersion(AzureContext context, string resourceId, CancellationToken cancellationToken, bool? pre = null, Dictionary<string, string> cmdletHeaderValues = null)
        {
            var providerNamespace = ResourceIdUtility.GetExtensionProviderNamespace(resourceId)
                ?? ResourceIdUtility.GetProviderNamespace(resourceId);

            var resourceType = ResourceIdUtility.GetExtensionResourceType(resourceId: resourceId, includeProviderNamespace: false)
                ?? ResourceIdUtility.GetResourceType(resourceId: resourceId, includeProviderNamespace: false);

            return ApiVersionHelper.DetermineApiVersion(context: context, providerNamespace: providerNamespace, resourceType: resourceType, cancellationToken: cancellationToken, pre: pre, cmdletHeaderValues: cmdletHeaderValues);
        }
 /// <summary>
 /// Default Constructor.
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureEndpointsCommunicator(AzureContext context)
 {
     Context = context;
     if (context.Subscription != Subscription)
     {
         Subscription = context.Subscription;
         StorageClient = null;
         ResourcesClient = null;
         StorageV2Client = null;
     }
 }
 internal static AzureSubscription ToAzureSubscription(this Subscription other, AzureContext context)
 {
     var subscription = new AzureSubscription();
     subscription.Account = context.Account != null ? context.Account.Id : null;
     subscription.Environment = context.Environment != null ? context.Environment.Name : EnvironmentName.AzureCloud;
     subscription.Id = new Guid(other.SubscriptionId);
     subscription.Name = other.DisplayName;
     subscription.SetProperty(AzureSubscription.Property.Tenants,
         context.Tenant.Id.ToString());
     return subscription;
 }
        public DataLakeStoreClient(AzureContext context)
        {
            if (context == null)
            {
                throw new ApplicationException(Resources.InvalidDefaultSubscription);
            }

            _subscriptionId = context.Subscription.Id;
            _client = AzureSession.ClientFactory.CreateClient<DataLakeStoreManagementClient>(context,
                AzureEnvironment.Endpoint.ResourceManager);
            _client.UserAgentSuffix = " - PowerShell Client";
        }
        public DataLakeStoreFileSystemClient(AzureContext context)
        {
            if (context == null)
            {
                throw new ApplicationException(Resources.InvalidDefaultSubscription);
            }

            var creds = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
            _client = AzureSession.ClientFactory.CreateCustomClient<DataLakeStoreFileSystemManagementClient>(creds,
                context.Environment.GetEndpoint(AzureEnvironment.Endpoint.AzureDataLakeStoreFileSystemEndpointSuffix));
            _client.UserAgentSuffix = " - PowerShell Client";
            uniqueActivityIdGenerator = new Random();
        }
        /// <summary>
        /// Set the context for the current profile, preserving token cache information
        /// </summary>
        /// <param name="profile">The profile to change the context for</param>
        /// <param name="newContext">The new context, with no token cache information.</param>
        public static void SetContextWithCache(this AzureRMProfile profile, AzureContext newContext)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile", Resources.ProfileCannotBeNull);
            }

            if (newContext == null)
            {
                throw new ArgumentNullException("newContext", Resources.ContextCannotBeNull);
            }

            newContext.TokenCache = TokenCache.DefaultShared.Serialize();
            profile.Context = newContext;
        }