/// <summary>
        /// Creates the client.
        /// </summary>
        /// <typeparam name="TClient">The type of the client.</typeparam>
        /// <param name="profile">The profile.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="endpoint">The endpoint.</param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException"></exception>
        /// <exception cref="System.ArgumentException">
        /// accountName
        /// or
        /// environment
        /// </exception>
        public virtual TClient CreateClient <TClient>(IAzureContextContainer profile, IAzureSubscription subscription, string endpoint) where TClient : ServiceClient <TClient>
        {
            if (subscription == null)
            {
                throw new ApplicationException(Resources.InvalidDefaultSubscription);
            }

            var account = profile.Accounts.FirstOrDefault((a) => string.Equals(a.Id, (subscription.GetAccount()), StringComparison.OrdinalIgnoreCase));

            if (null == account)
            {
                throw new ArgumentException(string.Format("Account with name '{0}' does not exist.", subscription.GetAccount()), "accountName");
            }

            var environment = profile.Environments.FirstOrDefault((e) => string.Equals(e.Name, subscription.GetEnvironment(), StringComparison.OrdinalIgnoreCase));

            if (null == environment)
            {
                throw new ArgumentException(string.Format(Resources.EnvironmentNotFound, subscription.GetEnvironment()));
            }

            AzureContext context = new AzureContext(subscription, account, environment);

            var client = CreateClient <TClient>(context, endpoint);

            foreach (IClientAction action in GetActions())
            {
                action.Apply <TClient>(client, profile, endpoint);
            }

            return(client);
        }
        public TClient CreateClient <TClient>(IAzureContextContainer profile, IAzureSubscription subscription, string endpoint) where TClient : ServiceClient <TClient>
        {
#if !NETSTANDARD
            if (subscription == null)
            {
                throw new ArgumentException(Microsoft.Azure.Commands.ResourceManager.Common.Properties.Resources.InvalidDefaultSubscription);
            }

            if (profile == null)
            {
                profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            }

            SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription.Id.ToString(), "fake_token");
            if (HttpMockServer.GetCurrentMode() != HttpRecorderMode.Playback)
            {
                ProfileClient profileClient = new ProfileClient(profile as AzureSMProfile);
                AzureContext  context       = new AzureContext(
                    subscription,
                    profileClient.GetAccount(subscription.GetAccount()),
                    profileClient.GetEnvironmentOrDefault(subscription.GetEnvironment())
                    );

                creds = AzureSession.Instance.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
            }

            Uri endpointUri = profile.Environments.FirstOrDefault((e) => e.Name.Equals(subscription.GetEnvironment(), StringComparison.OrdinalIgnoreCase)).GetEndpointAsUri(endpoint);
            return(CreateCustomClient <TClient>(creds, endpointUri));
#else
            throw new NotSupportedException("AzureSMProfile is not supported in Azure PS on .Net Core.");
#endif
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="PSAsrFabricDiscoveryClient" /> class.
        /// </summary>
        /// <param name="azureProfile">Azure context.</param>
        public PSAsrFabricDiscoveryClient(IAzureContextContainer azureProfile)
        {
            AzureContext = (AzureContext)azureProfile.DefaultContext;
            if (endPointUri == null)
            {
                endPointUri =
                    azureProfile.DefaultContext.Environment.GetEndpointAsUri(
                        AzureEnvironment.Endpoint.ResourceManager);
            }

            this.DeserializationSettings = new JsonSerializerSettings
            {
                DateFormatHandling    = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling  = DateTimeZoneHandling.Utc,
                NullValueHandling     = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                ContractResolver      = new ReadOnlyJsonContractResolver(),
                Converters            = new List <JsonConverter>
                {
                    new Iso8601TimeSpanConverter(),
                    new PolymorphicDeserializeJsonConverter <VMwareRunAsAccount>("type"),
                    new PolymorphicDeserializeJsonConverter <VMwareMachine>("type")
                }
            };
        }
 public static void SetTokenCache(this IAzureContextContainer container, IAzureTokenCache cache)
 {
     if (container != null && container.DefaultContext != null)
     {
         container.DefaultContext.TokenCache = cache;
     }
 }
        /// <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 IAzureContextContainer profile, IAzureContext newContext, string name = null)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile", Resources.ProfileCannotBeNull);
            }

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

            if (newContext.TokenCache != null && newContext.TokenCache.CacheData != null && newContext.TokenCache.CacheData.Length > 0)
            {
                AzureSession.Instance.TokenCache.CacheData = newContext.TokenCache.CacheData;
            }

            newContext.TokenCache = AzureSession.Instance.TokenCache;

            var rmProfile = profile as AzureRmProfile;

            if (rmProfile != null)
            {
                rmProfile.TrySetDefaultContext(name, newContext);
            }
            else
            {
                profile.DefaultContext = newContext;
            }
        }
Пример #6
0
        public TClient CreateClient <TClient>(IAzureContextContainer container, IAzureSubscription subscription, string endpoint) where TClient : ServiceClient <TClient>
        {
            var profile = container as AzureSMProfile;

            if (subscription == null)
            {
                throw new ArgumentException(Commands.Common.Properties.Resources.InvalidDefaultSubscription);
            }

            if (profile == null)
            {
                profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            }

            SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription.Id.ToString(), "fake_token");

            if (HttpMockServer.GetCurrentMode() != HttpRecorderMode.Playback)
            {
                ProfileClient profileClient = new ProfileClient(profile);
                AzureContext  context       = new AzureContext(
                    subscription,
                    profileClient.GetAccount(subscription.GetAccount()),
                    profileClient.GetEnvironmentOrDefault(subscription.GetEnvironment())
                    );

                creds = AzureSession.Instance.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
            }

            Uri endpointUri = profile.EnvironmentTable[subscription.GetEnvironment()].GetEndpointAsUri(endpoint);

            return(CreateCustomClient <TClient>(creds, endpointUri));
        }
        /// <summary>
        /// Registers resource providers for Sparta.
        /// </summary>
        /// <typeparam name="T">The client type</typeparam>
        private void RegisterResourceManagerProviders <T>(IAzureContextContainer profile)
        {
            var providersToRegister            = RequiredResourceLookup.RequiredProvidersForResourceManager <T>();
            var registeredProviders            = profile.DefaultContext.Subscription.GetPropertyAsArray(AzureSubscription.Property.RegisteredResourceProviders);
            var unregisteredProviders          = providersToRegister.Where(p => !registeredProviders.Contains(p)).ToList();
            var successfullyRegisteredProvider = new List <string>();
            SubscriptionCloudCredentials creds = AzureSession.Instance.AuthenticationFactory.GetSubscriptionCloudCredentials(profile.DefaultContext);

            if (unregisteredProviders.Count > 0)
            {
                using (var client = ClientFactory.CreateCustomClient <ResourceManagementClient>(
                           creds,
                           profile.DefaultContext.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    foreach (string provider in unregisteredProviders)
                    {
                        try
                        {
                            client.Providers.Register(provider);
                            successfullyRegisteredProvider.Add(provider);
                        }
                        catch
                        {
                            // Ignore this as the user may not have access to service management endpoint or the provider is already registered
                        }
                    }
                }
            }
        }
 public static bool HasTokenCache(this IAzureContextContainer container)
 {
     return(container != null &&
            container.DefaultContext != null &&
            container.DefaultContext.TokenCache != null &&
            container.DefaultContext.TokenCache.CacheData != null &&
            container.DefaultContext.TokenCache.CacheData.Length > 0);
 }
        public void ApplyArm <TClient>(TClient client, IAzureContextContainer container, string endpoint) where TClient : Rest.ServiceClient <TClient>
        {
            Debug.Assert(ClientFactory != null);

            if (endpoint == AzureEnvironment.Endpoint.ResourceManager)
            {
                RegisterResourceManagerProviders <TClient>(container);
            }
        }
 public override void SetTokenCacheForProfile(IAzureContextContainer profile)
 {
     base.SetTokenCacheForProfile(profile);
     if (profile.HasTokenCache())
     {
         var cache = TokenCache.DefaultShared;
         cache.Deserialize(profile.GetTokenCache().CacheData);
         AzureSession.Instance.TokenCache = new AuthenticationStoreTokenCache(cache);
     }
 }
Пример #11
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
        ///     required current subscription.
        /// </summary>
        /// <param name="azureSubscription">Azure Subscription</param>
        public PSAsrComputeManagementClient(
            IAzureContextContainer azureProfile)
        {
            AzureContext = (AzureContext)azureProfile.DefaultContext;

            this.computeManagementClient = AzureSession.Instance.ClientFactory
                                           .CreateArmClient <Common.Compute.Version2016_04_preview.ComputeManagementClient>(
                AzureContext,
                AzureEnvironment.Endpoint.ResourceManager);
        }
        public virtual TClient CreateClient <TClient>(IAzureContextContainer container, string endpoint) where TClient : ServiceClient <TClient>
        {
            TClient client = CreateClient <TClient>(container.DefaultContext, endpoint);

            foreach (IClientAction action in GetActions())
            {
                action.Apply <TClient>(client, container, endpoint);
            }

            return(client);
        }
        public static IAzureTokenCache GetTokenCache(this IAzureContextContainer container)
        {
            IAzureTokenCache result = null;

            if (HasTokenCache(container))
            {
                result = container.DefaultContext.TokenCache;
            }

            return(result);
        }
Пример #14
0
        public override void SetTokenCacheForProfile(IAzureContextContainer profile)
        {
            base.SetTokenCacheForProfile(profile);
            var session = AzureSession.Instance;
            var cache   = new ProtectedFileTokenCache(Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile), session.DataStore);

            session.TokenCache = cache;
            if (profile.HasTokenCache())
            {
                cache.Deserialize(profile.GetTokenCache().CacheData);
            }

            profile.SetTokenCache(cache);
        }
        /// <summary>
        /// Get the current storage account
        /// </summary>
        /// <returns>True if it need to init the service channel, otherwise false</returns>
        internal virtual bool TryGetStorageAccount(IAzureContextContainer profile, out string account)
        {
            account = null;
            bool result = false;

            //Storage Context is empty and have already set the current storage account in subscription
            if (Context == null && profile != null && profile.DefaultContext != null && profile.DefaultContext.Subscription != null && profile.DefaultContext.Subscription != null)
            {
                account = profile.DefaultContext.Subscription.GetProperty(AzureSubscription.Property.StorageAccount);
                result  = !string.IsNullOrWhiteSpace(account);
            }

            return(result);
        }
        /// <summary>
        /// Get the current storage account
        /// </summary>
        /// <returns>True if it need to init the service channel, otherwise false</returns>
        internal virtual bool TryGetStorageAccount(IAzureContextContainer profile, out string account)
        {
            account = null;
            //Storage Context is empty and have already set the current storage account in subscription
            if (Context != null || profile?.DefaultContext?.Subscription == null)
            {
                return(false);
            }

            account = profile.DefaultContext.GetCurrentStorageAccountConnectionString();
            var result = !string.IsNullOrWhiteSpace(account);

            return(result);
        }
        public void Apply <TClient>(TClient client, IAzureContextContainer container, string endpoint) where TClient : ServiceClient <TClient>
        {
            var profile = container as AzureSMProfile;

            Debug.Assert(ClientFactory != null);

            if (endpoint == AzureEnvironment.Endpoint.ServiceManagement)
            {
                RegisterServiceManagementProviders <TClient>(profile);
            }
            else if (endpoint == AzureEnvironment.Endpoint.ResourceManager)
            {
                RegisterResourceManagerProviders <TClient>(profile);
            }
        }
Пример #18
0
        private static void RunDataProfileTest(IAzureContextContainer rmProfile, IAzureContextContainer smProfile, Action testAction)
        {
            AzureSession.Instance.DataStore = new MemoryDataStore();
            var savedRmProfile = AzureRmProfileProvider.Instance.Profile;

            try
            {
                AzureRmProfileProvider.Instance.Profile = rmProfile;
                testAction();
            }
            finally
            {
                AzureRmProfileProvider.Instance.Profile = savedRmProfile;
            }
        }
Пример #19
0
 public AzKeyStore(IAzureContextContainer profile)
 {
     if (profile != null && profile.Accounts != null)
     {
         foreach (var account in profile.Accounts)
         {
             if (account != null && account.ExtendedProperties.ContainsKey(AzureAccount.Property.ServicePrincipalSecret))
             {
                 IKeyStoreKey keyStoreKey = new ServicePrincipalKey(AzureAccount.Property.ServicePrincipalSecret, account.Id
                                                                    , account.GetTenants().FirstOrDefault());
                 var servicePrincipalSecret = account.ExtendedProperties[AzureAccount.Property.ServicePrincipalSecret];
                 _credentials[keyStoreKey] = servicePrincipalSecret.ConvertToSecureString();
             }
         }
     }
 }
        public IAzureContextContainer CopyForContextOverriding(IAzureContextContainer contextContainer)
        {
            var profile = contextContainer as AzureRmProfile;

            return(new AzureRmProfile()
            {
                DefaultContextKey = profile.DefaultContextKey,
                EnvironmentTable = profile.EnvironmentTable,
                // Contexts need a new instance else any change to DefaultContext will affect the original profile
                Contexts = new ConcurrentDictionary <string, IAzureContext>(profile.Contexts, StringComparer.CurrentCultureIgnoreCase),
                ShouldRefreshContextsFromCache = profile.ShouldRefreshContextsFromCache,
                // ProfilePath is not copied because
                // 1. it's protected setter
                // 2. copy won't be written back to disk, so it's not useful
                ExtendedProperties = profile.ExtendedProperties
            });
        }
Пример #21
0
 public AzureRmServicePrincipalKeyStore(IAzureContextContainer profile)
 {
     _credentials = new Dictionary <string, SecureString>();
     if (profile != null && profile.Accounts != null)
     {
         foreach (var account in profile.Accounts)
         {
             if (account != null && account.ExtendedProperties.ContainsKey(AzureAccount.Property.ServicePrincipalSecret))
             {
                 var appId    = account.Id;
                 var tenantId = account.GetTenants().FirstOrDefault();
                 var key      = CreateKey(appId, tenantId);
                 var servicePrincipalSecret = account.ExtendedProperties[AzureAccount.Property.ServicePrincipalSecret];
                 _credentials[key] = ConvertToSecureString(servicePrincipalSecret);
             }
         }
     }
 }
        /// <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 IAzureContextContainer profile, IAzureContext newContext)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile", Resources.ProfileCannotBeNull);
            }

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

            if (newContext.TokenCache != null && newContext.TokenCache.CacheData != null && newContext.TokenCache.CacheData.Length > 0)
            {
                AzureSession.Instance.TokenCache.CacheData = newContext.TokenCache.CacheData;
            }

            newContext.TokenCache  = AzureSession.Instance.TokenCache;
            profile.DefaultContext = newContext;
        }
        /// <summary>
        /// Set the context for the current profile, preserving token cache information.
        /// After MSAL, token cache is no longer stored in contexts. So this method roughly equals to TrySetDefaultContext().
        /// </summary>
        /// <param name="profile">The profile to change the context for</param>
        /// <param name="newContext">The new context, with no token cache information.</param>
        /// <param name="name"></param>
        public static void SetContextWithCache(this IAzureContextContainer profile, IAzureContext newContext, string name = null)
        {
            if (profile == null)
            {
                throw new ArgumentNullException("profile", Resources.ProfileCannotBeNull);
            }

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

            var rmProfile = profile as AzureRmProfile;

            if (rmProfile != null)
            {
                rmProfile.TrySetDefaultContext(name, newContext);
            }
            else
            {
                profile.DefaultContext = newContext;
            }
        }
Пример #24
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
        ///     required current subscription.
        /// </summary>
        /// <param name="azureSubscription">Azure Subscription</param>
        public PSRecoveryServicesClient(
            IAzureContextContainer azureProfile)
        {
            AzureContext = (AzureContext)azureProfile.DefaultContext;

            var resourceNamespace = ARMResourceTypeConstants
                                    .RecoveryServicesResourceProviderNameSpace;
            var resourceType = ARMResourceTypeConstants.RecoveryServicesVault;

            // Get Resource provider namespace and type from config only if Vault context is not set
            // (hopefully it is required only for Vault related cmdlets)
            if (string.IsNullOrEmpty(asrVaultCreds.ResourceNamespace) ||
                string.IsNullOrEmpty(asrVaultCreds.ARMResourceType))
            {
                Utilities.UpdateCurrentVaultContext(
                    new ASRVaultCreds
                {
                    ResourceNamespace = resourceNamespace,
                    ARMResourceType   = resourceType
                });
            }

            if (null == endPointUri)
            {
                endPointUri =
                    azureProfile.DefaultContext.Environment.GetEndpointAsUri(
                        AzureEnvironment.Endpoint.ResourceManager);
            }

            cloudCredentials = AzureSession.Instance.AuthenticationFactory
                               .GetSubscriptionCloudCredentials(azureProfile.DefaultContext);
            this.recoveryServicesVaultClient = AzureSession.Instance.ClientFactory
                                               .CreateArmClient <RecoveryServicesClient>(
                AzureContext,
                AzureEnvironment.Endpoint.ResourceManager);
        }
Пример #25
0
        private static void RunDataProfileTest(IAzureContextContainer rmProfile, IAzureContextContainer smProfile, Action testAction)
        {
            AzureSession.Instance.DataStore = new MemoryDataStore();
            var savedRmProfile = AzureRmProfileProvider.Instance.Profile;

#if !NETSTANDARD
            var savedSmProfile = AzureSMProfileProvider.Instance.Profile;
#endif
            try
            {
                AzureRmProfileProvider.Instance.Profile = rmProfile;
#if !NETSTANDARD
                AzureSMProfileProvider.Instance.Profile = smProfile;
#endif
                testAction();
            }
            finally
            {
                AzureRmProfileProvider.Instance.Profile = savedRmProfile;
#if !NETSTANDARD
                AzureSMProfileProvider.Instance.Profile = savedSmProfile;
#endif
            }
        }
 public TClient CreateClient <TClient>(IAzureContextContainer profile, string endpoint) where TClient : ServiceClient <TClient>
 {
     return(CreateClient <TClient>(profile, profile.DefaultContext.Subscription, endpoint));
 }
Пример #27
0
 public TClient CreateClient <TClient>(IAzureContextContainer profile, IAzureSubscription subscription, string endpoint) where TClient : Hyak.Common.ServiceClient <TClient>
 {
     throw new NotImplementedException();
 }
 public abstract void SetTokenCacheForProfile(IAzureContextContainer profile);
        /// <summary>
        /// Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
        /// required current subscription.
        /// </summary>
        /// <param name="azureSubscription">Azure Subscription</param>
        public PSRecoveryServicesClient(IAzureContextContainer azureProfile)
        {
            System.Configuration.Configuration siteRecoveryConfig = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

            System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)siteRecoveryConfig.GetSection("appSettings");

            string resourceNamespace = string.Empty;
            string resourceType      = string.Empty;

            // Get Resource provider namespace and type from config only if Vault context is not set
            // (hopefully it is required only for Vault related cmdlets)
            if (string.IsNullOrEmpty(asrVaultCreds.ResourceNamespace) ||
                string.IsNullOrEmpty(asrVaultCreds.ARMResourceType))
            {
                if (appSettings.Settings.Count == 0)
                {
                    resourceNamespace = "Microsoft.SiteRecovery"; // ProviderNameSpace for Production is taken as default
                    resourceType      = ARMResourceTypeConstants.SiteRecoveryVault;
                }
                else
                {
                    resourceNamespace =
                        null == appSettings.Settings["ProviderNamespace"]
                        ? "Microsoft.SiteRecovery"
                        : appSettings.Settings["ProviderNamespace"].Value;
                    resourceType =
                        null == appSettings.Settings["ResourceType"]
                        ? ARMResourceTypeConstants.SiteRecoveryVault
                        : appSettings.Settings["ResourceType"].Value;
                }

                Utilities.UpdateCurrentVaultContext(new ASRVaultCreds()
                {
                    ResourceNamespace = resourceNamespace,
                    ARMResourceType   = resourceType
                });
            }

            if (null == endPointUri)
            {
                if (appSettings.Settings.Count == 0)
                {
                    endPointUri = azureProfile.DefaultContext.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager);
                }
                else
                {
                    if (null == appSettings.Settings["RDFEProxy"])
                    {
                        endPointUri = azureProfile.DefaultContext.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager);
                    }
                    else
                    {
                        // Setting Endpoint to RDFE Proxy
                        if (null == ServicePointManager.ServerCertificateValidationCallback)
                        {
                            ServicePointManager.ServerCertificateValidationCallback =
                                IgnoreCertificateErrorHandler;
                        }

                        endPointUri = new Uri(appSettings.Settings["RDFEProxy"].Value);
                    }
                }
            }

            cloudCredentials            = AzureSession.Instance.AuthenticationFactory.GetSubscriptionCloudCredentials(azureProfile.DefaultContext);
            this.recoveryServicesClient =
                AzureSession.Instance.ClientFactory.CreateCustomClient <SiteRecoveryVaultManagementClient>(
                    asrVaultCreds.ResourceNamespace,
                    asrVaultCreds.ARMResourceType,
                    cloudCredentials,
                    azureProfile.DefaultContext.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager));
        }
        /// <summary>
        /// Get the list of subscriptions associated with the given account
        /// </summary>
        /// <param name="account">The account to look for</param>
        /// <param name="profile">The profile to search</param>
        /// <returns>A list of subscriptions available to the given account</returns>
        public static List <IAzureSubscription> GetSubscriptions(this IAzureAccount account, IAzureContextContainer profile)
        {
            string[] subscriptions = new string[0];
            List <IAzureSubscription> subscriptionsList = new List <IAzureSubscription>();

            if (account.IsPropertySet(AzureAccount.Property.Subscriptions))
            {
                subscriptions = account.GetSubscriptions();
            }

            foreach (var subscription in subscriptions)
            {
                var foundSubscription = profile.Subscriptions.FirstOrDefault((s) => string.Equals(s.Id, subscription, StringComparison.OrdinalIgnoreCase));
                if (foundSubscription != null)
                {
                    subscriptionsList.Add(foundSubscription);
                }
            }

            return(subscriptionsList);
        }