Skip to content

Instantly share code, notes, and snippets.

@jamesbroome
Last active November 6, 2020 15:26
Show Gist options
  • Save jamesbroome/6be8b57980e3aa9bcfe3700326e986cf to your computer and use it in GitHub Desktop.
Save jamesbroome/6be8b57980e3aa9bcfe3700326e986cf to your computer and use it in GitHub Desktop.
using Microsoft.AnalysisServices.AdomdClient;
using Microsoft.AnalysisServices.Tabular;
using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace endjin.Demo
{
public class AasConnectionExamples
{
// Replace with real values, typically retrieve from config
public const string aasRegion = "uksouth";
public const string aasServerName = "endjindemo";
public const string aasDatabaseName = "endjindemomodel";
public const string tenantId = "00000000-0000-0000-0000-000000000000";
public async Task ConnectAndUseAdomdConnection()
{
using (var connection = new AdomdConnection(this.GetConnectionString(await this.GetTokenAsync())))
{
connection.Open();
// Do something with the open connection here
// e.g. use a AdomdDataAdapter to fill a table of results
// from executing a DAX query...
}
}
public async Task ConnectAndUseAmoConnection()
{
using (var server = new Server())
{
server.Connect(this.GetConnectionString(await this.GetTokenAsync()));
// Do something with the open connection here
// e.g. update the expression of a calculated column...
}
}
public async Task AuthenticateAndUseHttpClient()
{
var client = new HttpClient
{
BaseAddress = new Uri($"https://{aasRegion}.asazure.windows.net/servers/{aasServerName}/models/{aasDatabaseName}/")
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await this.GetTokenAsync());
// Do something with the http client here
// i.e. issue GET or POST request...
}
private async Task<string> GetTokenAsync()
{
// Use when running under Managed Identity to retrieve auth token
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var token = await azureServiceTokenProvider.GetAccessTokenAsync($"https://{aasRegion}.asazure.windows.net", tenantId);
return token;
}
private string GetConnectionString(string token)
{
return $"Provider=MSOLAP;" +
$"Data Source=asazure://{aasRegion}.asazure.windows.net/{aasServerName}:rw;" +
$"Initial Catalog={aasDatabaseName};" +
$"User ID=;" +
$"Password={token};" +
$"Persist Security Info=True;" +
$"Impersonation Level=Impersonate";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment