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 auth rules for a relay and return <see cref="HybridConnectionDetails"/> instance containing details of hybrid connection.
        /// </summary>
        /// <param name="rgName">Name of the Resource Group.</param>
        /// <param name="hybridConnectionName">Hybrid connection name.</param>
        /// <param name="relayManagementClient">The relay management client.</param>
        /// <param name="relayNamespace">The selected relay.</param>
        private static async Task <HybridConnectionDetails> GetHybridConnectionDetailsAsync(
            string rgName,
            string hybridConnectionName,
            RelayManagementClient relayManagementClient,
            RelayNamespaceInner relayNamespace)
        {
            List <AuthorizationRuleInner>  relayAuthRuleList = new List <AuthorizationRuleInner>();
            IPage <AuthorizationRuleInner> resp = await relayManagementClient.Namespaces.ListAuthorizationRulesAsync(rgName, relayNamespace.Name).ConfigureAwait(false);

            relayAuthRuleList.AddRange(resp);

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

                relayAuthRuleList.AddRange(resp);
            }

            AuthorizationRuleInner selectedAuthRule = relayAuthRuleList.FirstOrDefault(rule => rule.Rights != null && rule.Rights.Contains(AccessRights.Listen) && rule.Rights.Contains(AccessRights.Manage) && rule.Rights.Contains(AccessRights.Send));

            if (selectedAuthRule == null)
            {
                throw new InvalidOperationException("Failed to find a suitable Authorization rule to use. Please create an Authorization rule with Listen, Manage and Send rights and retry the operation");
            }
            else
            {
                AccessKeysInner keyInfo = await relayManagementClient.Namespaces.ListKeysAsync(
                    rgName,
                    relayNamespace.Name,
                    selectedAuthRule.Name).ConfigureAwait(false);

                return(new HybridConnectionDetails
                {
                    HybridConnectionKeyName = keyInfo.KeyName,
                    HybridConnectionName = hybridConnectionName,
                    HybridConnectionSharedKey = keyInfo.PrimaryKey,
                    RelayUrl = relayNamespace.ServiceBusEndpoint,
                });
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Handles the SelectionChanged event of the AzureRelayList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="SelectionChangedEventArgs"/> instance containing the event data.</param>
        private void AzureRelayList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RelayNamespaceInner selectedAzureRelay = (sender as ComboBox).SelectedItem as RelayNamespaceInner;

            // Selected Relay Id is null when it is the value we added manually i.e. newRelay above.
            if (selectedAzureRelay.Id == null)
            {
                this.lblAzureRelayName.Visibility = Visibility.Visible;

                if (!string.IsNullOrEmpty(this.txtAzureRelayName.Text))
                {
                    this.btnDone.IsEnabled = true;
                }

                return;
            }
            else
            {
                this.lblAzureRelayName.Visibility = Visibility.Collapsed;
                this.btnDone.IsEnabled            = true;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Handles the Click event of the Done control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void Done_Click(object sender, RoutedEventArgs e)
        {
            this.progressBar.Visibility = Visibility.Visible;
            this.btnDone.IsEnabled      = false;
            RM.Models.SubscriptionInner selectedSubscription = (this.comboSubscriptionList as ComboBox).SelectedItem as RM.Models.SubscriptionInner;
            RelayNamespaceInner         selectedAzureRelay   = (this.comboAzureRelayList as ComboBox).SelectedItem as RelayNamespaceInner;
            string selectedLocation = this.listBoxSubscriptionLocations.SelectedItem.ToString();

            string newRelayName = this.txtAzureRelayName.Text;

            // Case 1. When user used existing Relay.
            Thread existingAzureRelayThread = new Thread(new ThreadStart(() =>
            {
                try
                {
                    HybridConnectionDetails hybridConnectionDetails = this.relayResourceManager.GetHybridConnectionAsync(selectedSubscription, selectedAzureRelay, Environment.MachineName).ConfigureAwait(false).GetAwaiter().GetResult();

                    this.SetApplicationData(hybridConnectionDetails);
                }
                catch (Exception ex)
                {
                    this.logger.LogError(ex, "Failed to connect to relay namespace");

                    this.Dispatcher.Invoke(() => MessageBox.Show("Failed to connect to Azure Relay namespace!!", "Azure Error", MessageBoxButton.OKCancel, MessageBoxImage.Error));
                }
            }));

            // Case 2. When user created a new Relay.
            Thread newAzureRelayThread = new Thread(new ThreadStart(() =>
            {
                try
                {
                    if (string.IsNullOrEmpty(newRelayName))
                    {
                        MessageBox.Show("Please enter the name for Azure Relay.");
                        this.Dispatcher.Invoke(() =>
                        {
                            this.progressBar.Visibility = Visibility.Hidden;
                            this.btnDone.IsEnabled      = true;
                        });
                        return;
                    }

                    if (newRelayName.Length < 6)
                    {
                        MessageBox.Show("Name of Azure Relay must be at least 6 characters.");
                        this.Dispatcher.Invoke(() =>
                        {
                            this.progressBar.Visibility = Visibility.Hidden;
                            this.btnDone.IsEnabled      = true;
                        });
                        return;
                    }

                    HybridConnectionDetails hybridConnectionDetails = this.relayResourceManager.CreateHybridConnectionAsync(
                        selectedSubscription,
                        newRelayName,
                        Environment.MachineName,
                        selectedLocation).ConfigureAwait(false).GetAwaiter().GetResult();

                    this.SetApplicationData(hybridConnectionDetails);
                }
                catch (CloudException cloudEx)
                {
                    this.logger.LogError(cloudEx, "Cloud exception while creating Azure Relay namespace.");

                    this.Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show(cloudEx.Message, "Azure Error", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                        this.progressBar.Visibility = Visibility.Hidden;
                        this.btnDone.IsEnabled      = true;
                    });
                }
                catch (Exception ex)
                {
                    this.logger.LogError(ex, "Failed to create new Azure Relay namespace");

                    this.Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show("Failed to create new Azure Relay namespace!!", "Azure Error", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                        this.progressBar.Visibility = Visibility.Hidden;
                        this.btnDone.IsEnabled      = true;
                    });
                }
            }));

            // If the user selected to new Relay entry we added.
            if (selectedAzureRelay.Id == null)
            {
                newAzureRelayThread.Start();
            }
            else
            {
                existingAzureRelayThread.Start();
            }
        }
Esempio n. 5
0
 /// <summary>
 /// Create Azure Relay namespace.
 /// </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='parameters'>
 /// Parameters supplied to create a Namespace Resource.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <RelayNamespaceInner> BeginCreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, RelayNamespaceInner parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Esempio n. 6
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));
        }