Esempio n. 1
0
        /// <summary>
        /// Get hybrid connection details async.
        /// </summary>
        /// <param name="subscription">Selected subscription.</param>
        /// <param name="relayNamespace">Selected relay namespace.</param>
        /// <param name="hybridConnectionName">Hybrid connection name.</param>
        /// <returns>Hybrid connection details.</returns>
        public async Task <HybridConnectionDetails> GetHybridConnectionAsync(
            SubscriptionInner subscription,
            RelayNamespaceInner relayNamespace,
            string hybridConnectionName)
        {
            string accessToken = this.userAuthenticator.GetSubscriptionSpecificUserToken(subscription);

            TokenCredentials      tokenCredentials      = new TokenCredentials(accessToken);
            RelayManagementClient relayManagementClient = new RelayManagementClient(tokenCredentials)
            {
                SubscriptionId = subscription.SubscriptionId,
            };

            int    startIndex = relayNamespace.Id.IndexOf("resourceGroups", StringComparison.OrdinalIgnoreCase) + 15;
            string rgName     = rgName = relayNamespace.Id.Substring(startIndex, relayNamespace.Id.IndexOf('/', startIndex) - startIndex);

            List <HybridConnectionInner> hybridConnections = new List <HybridConnectionInner>();

            hybridConnections.AddRange(await relayManagementClient.HybridConnections.ListByNamespaceAsync(rgName, relayNamespace.Name).ConfigureAwait(false));

            // Create the hybrid connection if one does not exist.
            if (!hybridConnections.Any(connection => connection.Name.Equals(hybridConnectionName, StringComparison.OrdinalIgnoreCase)))
            {
                await relayManagementClient.HybridConnections.CreateOrUpdateAsync(rgName, relayNamespace.Name, hybridConnectionName, new HybridConnectionInner
                {
                    RequiresClientAuthorization = false,
                }).ConfigureAwait(false);
            }

            return(await AzureRelayResourceManager.GetHybridConnectionDetailsAsync(rgName, hybridConnectionName, relayManagementClient, relayNamespace).ConfigureAwait(false));
        }
Esempio n. 2
0
        /// <summary>
        /// Gets the relay namespaces present in a subscription.
        /// </summary>
        /// <param name="subscription">Subscription to get namespaces from.</param>
        /// <returns>List of relay namespaces.</returns>
        public async Task <List <RelayNamespaceInner> > GetRelayNamespacesAsync(SubscriptionInner subscription)
        {
            string accessToken = this.userAuthenticator.GetSubscriptionSpecificUserToken(subscription);

            TokenCredentials      tokenCredentials      = new TokenCredentials(accessToken);
            RelayManagementClient relayManagementClient = new RelayManagementClient(tokenCredentials)
            {
                SubscriptionId = subscription.SubscriptionId,
            };

            List <RelayNamespaceInner>  relayList = new List <RelayNamespaceInner>();
            IPage <RelayNamespaceInner> resp      = await relayManagementClient.Namespaces.ListAsync().ConfigureAwait(false);

            relayList.AddRange(resp);

            while (!string.IsNullOrEmpty(resp.NextPageLink))
            {
                resp = await relayManagementClient.Namespaces.ListNextAsync(resp.NextPageLink).ConfigureAwait(false);

                relayList.AddRange(resp);
            }

            return(relayList.OrderBy(relay => relay.Name).ToList());
        }
 /// <summary>
 /// Creates a topic subscription.
 /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639385.aspx" />
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Name of the Resource group within the Azure subscription.
 /// </param>
 /// <param name='namespaceName'>
 /// The namespace name
 /// </param>
 /// <param name='topicName'>
 /// The topic name.
 /// </param>
 /// <param name='subscriptionName'>
 /// The subscription name.
 /// </param>
 /// <param name='parameters'>
 /// Parameters supplied to create a subscription resource.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <SubscriptionInner> CreateOrUpdateAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, SubscriptionInner parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Esempio n. 4
0
 private ISubscription WrapModel(SubscriptionInner innerModel)
 {
     return(new SubscriptionImpl(innerModel, innerCollection));
 }
 /// <summary>
 /// Gets the subscription specific user token.
 /// </summary>
 /// <param name="subscription">The subscription.</param>
 /// <returns>Authentication token.</returns>
 public AuthenticationResult GetSubscriptionSpecificUserToken(SubscriptionInner subscription)
 {
     return(this.tenantBasedTokenMap[this.subscriptionToTenantMap[subscription].TenantId]);
 }
Esempio n. 6
0
        private async Task EnsureTopicIsCreated()
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
                _configuration["serviceBus:clientId"],
                _configuration["serviceBus:clientSecret"],
                _configuration["serviceBus:tenantId"],
                AzureEnvironment.AzureGlobalCloud);

            var serviceBusManager   = ServiceBusManager.Authenticate(credentials, _configuration["serviceBus:subscriptionId"]);
            var serviceBusNamespace = serviceBusManager.Namespaces.GetByResourceGroup(_configuration["serviceBus:resourceGroup"], _configuration["serviceBus:namespaceName"]);

            var topics = await serviceBusNamespace.Topics.ListAsync();

            var topicStoreCatalogReady = topics.FirstOrDefault(t => t.Name.Equals("StoreCatalogReady", StringComparison.InvariantCultureIgnoreCase));
            var topicUserWithLessOffer = topics.FirstOrDefault(t => t.Name.Equals("UserWithLessOffer", StringComparison.InvariantCultureIgnoreCase));

            var topicProductChanged        = topics.FirstOrDefault(t => t.Name.Equals("ProductChanged", StringComparison.InvariantCultureIgnoreCase));
            var topicProductionAreaChanged = topics.FirstOrDefault(t => t.Name.Equals("ProductionAreaChanged", StringComparison.InvariantCultureIgnoreCase));

            SubscriptionInner subscriptionInner = new SubscriptionInner()
            {
            };

            #region Send Messages
            if (topicStoreCatalogReady == null)
            {
                topicStoreCatalogReady = await serviceBusNamespace.Topics.Define("StoreCatalogReady")
                                         .WithSizeInMB(1024)
                                         .CreateAsync();
            }

            if (topicUserWithLessOffer == null)
            {
                topicUserWithLessOffer = await serviceBusNamespace.Topics.Define("UserWithLessOffer")
                                         .WithSizeInMB(1024)
                                         .CreateAsync();
            }
            #endregion

            #region Receive Messages
            if (topicProductChanged == null)
            {
                topicProductChanged = await serviceBusNamespace.Topics.Define("ProductChanged")
                                      .WithSizeInMB(1024)
                                      .CreateAsync();
            }

            if (topicProductionAreaChanged == null)
            {
                topicProductionAreaChanged = await serviceBusNamespace.Topics.Define("ProductionAreaChanged")
                                             .WithSizeInMB(1024)
                                             .CreateAsync();
            }
            #endregion

            /*Criação da subscrição no tópico de produção*/
            await topicProductChanged.Subscriptions.Define("StoreCatalog-ProductChanged").CreateAsync();

            /*Criação da subscrição no tópico de área de produção*/
            await topicProductionAreaChanged.Subscriptions.Define("StoreCatalog-ProductionAreaChanged").CreateAsync();
        }
Esempio n. 7
0
        private static async Task <ApplicationData> PerformInteractiveConfigurationAsync(
            IServiceProvider serviceProvider,
            string redirectionUrl = null)
        {
            Console.WriteLine("Please wait while we log you in...");

            UserAuthenticator userAuthenticator = serviceProvider.GetRequiredService <UserAuthenticator>();

            AzureRelayResourceManager relayResourceManager = serviceProvider.GetRequiredService <AzureRelayResourceManager>();

            await userAuthenticator.AuthenticateUserAsync().ConfigureAwait(false);

            Console.WriteLine("Please wait while we gather subscription information...");

            List <SubscriptionInner> userSubscriptions = await userAuthenticator.GetUserSubscriptionsAsync().ConfigureAwait(false);

            if (userSubscriptions.Count == 0)
            {
                Console.Error.WriteLine("No Azure subscriptions found");
                throw new InvalidOperationException("User has no associated subscriptions");
            }

            Console.WriteLine("Select the subscription you want to use");

            for (int i = 0; i < userSubscriptions.Count; i++)
            {
                Console.WriteLine($"{i + 1} - {userSubscriptions[i].DisplayName}({userSubscriptions[i].SubscriptionId})");
            }

            int selectedSubscriptionIndex = 0;

            while (true)
            {
                if (!int.TryParse(Console.ReadLine(), out selectedSubscriptionIndex))
                {
                    Console.Error.WriteLine("Invalid input. Please select the index.");
                    continue;
                }

                if (selectedSubscriptionIndex > userSubscriptions.Count || selectedSubscriptionIndex == 0)
                {
                    Console.Error.WriteLine("Invalid input. Select index out of allowed values");
                    continue;
                }

                break;
            }

            SubscriptionInner selectedSubscription = userSubscriptions[selectedSubscriptionIndex - 1];

            List <RelayNamespaceInner> relayNamespaces = await relayResourceManager.GetRelayNamespacesAsync(selectedSubscription).ConfigureAwait(false);

            int selectedRelayIndex = 0;

            if (relayNamespaces.Count != 0)
            {
                Console.WriteLine("Select the Azure Relay you want to use.");

                Console.WriteLine("0 - Create a new Azure Relay");
                for (int i = 0; i < relayNamespaces.Count; i++)
                {
                    Console.WriteLine($"{i + 1} - {relayNamespaces[i].Name}");
                }

                while (true)
                {
                    if (!int.TryParse(Console.ReadLine(), out selectedRelayIndex))
                    {
                        Console.Error.WriteLine("Invalid input. Please select the index.");
                        continue;
                    }

                    if (selectedRelayIndex > relayNamespaces.Count)
                    {
                        Console.Error.WriteLine("Invalid input. Select index out of allowed values");
                        continue;
                    }

                    break;
                }
            }

            HybridConnectionDetails hybridConnectionDetails = null;

            if (selectedRelayIndex == 0)
            {
                Console.Write("Enter the name for the new Azure Relay. This must be atleast 6 character long and globally unique. ");
                string relayName = Console.ReadLine();

                Console.WriteLine("Select the location for the new Relay from the list below");

                List <Location> subscriptionLocations = userAuthenticator.GetSubscriptionLocations(selectedSubscription).ToList();

                for (int i = 0; i < subscriptionLocations.Count; i++)
                {
                    Console.WriteLine($"{i + 1} - {subscriptionLocations[i].DisplayName}");
                }

                int selectedLocationIndex = 0;
                while (true)
                {
                    if (!int.TryParse(Console.ReadLine(), out selectedLocationIndex))
                    {
                        Console.Error.WriteLine("Invalid input. Please select the index.");
                        continue;
                    }

                    if (selectedRelayIndex > subscriptionLocations.Count || selectedLocationIndex == 0)
                    {
                        Console.Error.WriteLine("Invalid input. Select index out of allowed values");
                        continue;
                    }

                    break;
                }

                Console.WriteLine("Please wait while the new Relay is being created");
                hybridConnectionDetails = await relayResourceManager.CreateHybridConnectionAsync(
                    selectedSubscription,
                    relayName,
                    Environment.MachineName,
                    subscriptionLocations[selectedLocationIndex - 1].DisplayName).ConfigureAwait(false);
            }
            else
            {
                Console.WriteLine("Please wait while the details for Relay are fetched");
                hybridConnectionDetails = await relayResourceManager.GetHybridConnectionAsync(
                    selectedSubscription,
                    relayNamespaces[selectedRelayIndex - 1],
                    Environment.MachineName).ConfigureAwait(false);
            }

            if (string.IsNullOrEmpty(redirectionUrl))
            {
                Console.Write("Enter the endpoint to route requests to. Example http://localhost:4200 ");
                redirectionUrl = Console.ReadLine();
            }

            return(new ApplicationData
            {
                // DPAPI APIs used for encryption are only present on Windows.
                EnableCredentialEncryption = RuntimeInformation.IsOSPlatform(OSPlatform.Windows),
                EnabledPlugins = new HashSet <string>(),
                HybridConnectionKeyName = hybridConnectionDetails.HybridConnectionKeyName,
                HybridConnectionName = hybridConnectionDetails.HybridConnectionName,
                HybridConnectionSharedKey = hybridConnectionDetails.HybridConnectionSharedKey,
                HybridConnectionUrl = hybridConnectionDetails.RelayUrl,
                PluginSettingsMap = new Dictionary <string, Dictionary <string, string> >(),
                RedirectionUrl = redirectionUrl,
            });
        }
        /// <summary>
        /// Gets the list of locations enabled in a subscription.
        /// </summary>
        /// <param name="subscription">Subscription to look for in details.</param>
        /// <param name="preferredTenantId">Preferred tenant Id.</param>
        /// <returns>Collection of locations.</returns>
        private async Task <IEnumerable <Location> > GetLocationsForSubscriptionAsync(SubscriptionInner subscription, string preferredTenantId)
        {
            await this.TryUpdateTokenCacheForTenantAsync(preferredTenantId).ConfigureAwait(false);

            HashSet <string> secondaryTenantLookups;

            if (this.tenantBasedTokenMap.ContainsKey(preferredTenantId))
            {
                TokenCredentials subsCreds = new TokenCredentials(this.tenantBasedTokenMap[preferredTenantId].AccessToken);

                SubscriptionClient subscriptionClient = new SubscriptionClient(subsCreds);

                try
                {
                    return(await subscriptionClient.Subscriptions.ListLocationsAsync(subscription.SubscriptionId).ConfigureAwait(false));
                }
                catch (Exception ex)
                {
                    this.logger.LogWarning(
                        ex,
                        $"Preferred tenant based locations lookup for subscription with Id '{subscription.SubscriptionId}' used tenant '{preferredTenantId}'. Looping thru tenants.");

                    secondaryTenantLookups = this.GetTheTenantIdLookupForSubscriptionOnInvalidAuthenticationTokenError(ex as CloudException);
                }
            }
            else
            {
                secondaryTenantLookups = this.GetTheTenantIdLookupForSubscriptionOnInvalidAuthenticationTokenError();
            }

            // If we have reached this point. Either token acquire for preferred tenant failed or we hit an exception.
            foreach (string tenantId in secondaryTenantLookups)
            {
                await this.TryUpdateTokenCacheForTenantAsync(tenantId).ConfigureAwait(false);

                if (this.tenantBasedTokenMap.ContainsKey(tenantId))
                {
                    TokenCredentials subsCreds = new TokenCredentials(this.tenantBasedTokenMap[tenantId].AccessToken);

                    SubscriptionClient subscriptionClient = new SubscriptionClient(subsCreds);

                    try
                    {
                        return(await subscriptionClient.Subscriptions.ListLocationsAsync(subscription.SubscriptionId).ConfigureAwait(false));
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogWarning(
                            ex,
                            $"Lookup with TenantId '{tenantId}' failed for subscription with Id '{subscription.SubscriptionId}'. Moving on to next tenant.");
                    }
                }
            }

            // If we reach this point. We just all up failed to get locations in any possible way. Throwing exception so the subscription can be removed from the list.
            throw new UnauthorizedAccessException("Failed to get subscription location");
        }
 /// <summary>
 /// Gets the subscription specific user token.
 /// </summary>
 /// <param name="subscription">The subscription.</param>
 /// <returns>Authentication token.</returns>
 public string GetSubscriptionSpecificUserToken(SubscriptionInner subscription)
 {
     return(this.tenantBasedTokenMap[this.subscriptionToTenantMap[subscription].TenantId].AccessToken);
 }
 /// <summary>
 /// Gets the locations supported by a subscription.
 /// </summary>
 /// <param name="subscription">Selected subscription.</param>
 /// <returns>Locations supported by the subscription.</returns>
 public IEnumerable <Location> GetSubscriptionLocations(SubscriptionInner subscription)
 {
     return(this.subscriptionToLocationMap[subscription].OrderBy(loc => loc.Name));
 }
Esempio n. 11
0
        /// <summary>
        /// Creates a new hybrid connection and returns it's details.
        /// </summary>
        /// <param name="subscription">Subscription to create the relay under.</param>
        /// <param name="relayName">Relay name.</param>
        /// <param name="hybridConnectionName">Hybrid connection name.</param>
        /// <param name="locationName">Location for the new relay.</param>
        /// <returns>Hybrid connection details.</returns>
        public async Task <HybridConnectionDetails> CreateHybridConnectionAsync(
            SubscriptionInner subscription,
            string relayName,
            string hybridConnectionName,
            string locationName)
        {
            string accessToken = this.userAuthenticator.GetSubscriptionSpecificUserToken(subscription);

            TokenCredentials tokenCredentials = new TokenCredentials(accessToken);

            ResourceManagementClient resourceManagementClient = new ResourceManagementClient(tokenCredentials)
            {
                SubscriptionId = subscription.SubscriptionId,
            };

            RelayManagementClient relayManagementClient = new RelayManagementClient(tokenCredentials)
            {
                SubscriptionId = subscription.SubscriptionId,
            };

            ResourceGroupInner  resourceGroup  = null;
            RelayNamespaceInner relayNamespace = null;

            Location location = this.userAuthenticator.GetSubscriptionLocations(subscription).First(region =>
                                                                                                    region.DisplayName.Equals(locationName, StringComparison.OrdinalIgnoreCase) ||
                                                                                                    region.Name.Equals(locationName, StringComparison.OrdinalIgnoreCase));

            try
            {
                resourceGroup = await resourceManagementClient.ResourceGroups.GetAsync("TunnelRelay").ConfigureAwait(false);
            }
            catch (CloudException httpEx)
            {
                if (httpEx.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    resourceGroup = await resourceManagementClient.ResourceGroups.CreateOrUpdateAsync("TunnelRelay", new ResourceGroupInner
                    {
                        Location = location.Name,
                        Name     = "TunnelRelay",
                        Tags     = new Dictionary <string, string>()
                        {
                            { "CreatedBy", "TunnelRelayv2" }
                        },
                    }).ConfigureAwait(false);
                }
            }

            string rgName = resourceGroup.Name;

            relayNamespace = await relayManagementClient.Namespaces.CreateOrUpdateAsync(rgName, relayName, new RelayNamespaceInner
            {
                Location = resourceGroup.Location,
                Sku      = new Microsoft.Azure.Management.Relay.Fluent.Models.Sku(SkuTier.Standard),
                Tags     = new Dictionary <string, string>()
                {
                    { "CreatedBy", "TunnelRelayv2" }
                },
            }).ConfigureAwait(false);

            await relayManagementClient.HybridConnections.CreateOrUpdateAsync(rgName, relayName, hybridConnectionName, new HybridConnectionInner
            {
                RequiresClientAuthorization = false,
            }).ConfigureAwait(false);

            return(await AzureRelayResourceManager.GetHybridConnectionDetailsAsync(rgName, hybridConnectionName, relayManagementClient, relayNamespace).ConfigureAwait(false));
        }