How to create a Hybrid connection dynamically through code

354 Views Asked by At

I am using Azure Event grid service to be used for notifications. Here I want to create new hybrid connection in a Relay namespace using C# code when a user logs in. How can I do that?

2

There are 2 best solutions below

0
On

Thanks for sharing this, it was a great help starting on this.

That package is now deprecated so here is an updated version using the new Azure.ResourceManager.* packages.

using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Relay;


namespace My.Common.Helpers;

public class AzureManagement
{
    private readonly string _tenantId;
    private readonly string _subscriptionId;
    private readonly string _clientId;
    private readonly string _clientSecret;

    public AzureManagement(string tenantId, string subscriptionId, string clientId, string clientSecret)
    {
        _tenantId       = tenantId;
        _subscriptionId = subscriptionId;
        _clientId       = clientId;
        _clientSecret   = clientSecret;
    }

    /// <summary>
    /// Get App Registration Credential
    /// </summary>
    /// <remarks>
    /// Add App Registration as Role Assignment (e.g. Contributor) to Subscription
    /// </remarks>
    private ClientSecretCredential GetClientSecretCredential()
    {
        return new ClientSecretCredential(_tenantId, _clientId, _clientSecret);
    }

    #region Relay

    /// <summary>
    /// Create a Relay Hybrid Connection
    /// </summary>
    public async Task CreateRelayHybridConnection(string resourceGroupName, string namespaceName, string connectionName)
    {
        RelayNamespaceResource relayNamespace = await GetRelayNamespace(resourceGroupName, namespaceName);

        RelayHybridConnectionCollection relayHybridConnections = relayNamespace.GetRelayHybridConnections();
        if (!relayHybridConnections.Exists(connectionName))
        {
            RelayHybridConnectionData relayHybridConnectionData = new RelayHybridConnectionData();
            relayHybridConnectionData.IsClientAuthorizationRequired = true;

            relayHybridConnections.CreateOrUpdate(WaitUntil.Completed, connectionName, relayHybridConnectionData);
        }
    }

    /// <summary>
    /// Delete Relay Hybrid Connection
    /// </summary>
    public async void DeleteRelayHybridConnection(string resourceGroupName, string namespaceName, string connectionName)
    {
        RelayNamespaceResource relayNamespace = await GetRelayNamespace(resourceGroupName, namespaceName);

        RelayHybridConnectionCollection relayHybridConnections = relayNamespace.GetRelayHybridConnections();
        if (!relayHybridConnections.Exists(connectionName))
        {
            RelayHybridConnectionResource relayHybridConnection = await relayHybridConnections.GetAsync(connectionName);

            await relayHybridConnection.DeleteAsync(WaitUntil.Completed);
        }
    }

    /// <summary>
    /// Get Relay Namespace
    /// </summary>
    private async Task<RelayNamespaceResource> GetRelayNamespace(string resourceGroupName, string relayNamespace)
    {
        ArmClient client = new ArmClient(GetClientSecretCredential());

        SubscriptionCollection subscriptions = client.GetSubscriptions();
        SubscriptionResource subscription = await subscriptions.GetAsync(_subscriptionId);

        ResourceGroupCollection resourceGroups = subscription.GetResourceGroups();
        ResourceGroupResource resourceGroup = await resourceGroups.GetAsync(resourceGroupName);

        return await resourceGroup.GetRelayNamespaceAsync(relayNamespace);
    }

    #endregion
}
0
On

After much workaround, I finally found a way to do this. We can use Microsoft's Microsoft.Azure.Management.Relay Nuget package.

public static HybridConnection CreateHybridConnection(string clientId, string tenantId, string clientSecret, string subscriptionId)
        {
            var credentials = ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret).GetAwaiter().GetResult();
            DelegatingHandler[] handlers = null;
            var client = new RelayManagementClient(credentials, handlers);
            client.SubscriptionId = subscriptionId;
            var connection = new HybridConnection(requiresClientAuthorization: true);
            return client.HybridConnections.CreateOrUpdateAsync(<resourceGroupName>, <relayNameSpace>, "My Hybrid Connection", connection).GetAwaiter().GetResult();
        }