aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Web/SQLServer/SQLServerManager.cs
blob: 8bc84f7b52cd1d22b0a812e2a8c49a698d60c500 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tango.Web.SQLServer
{
    public class SQLServerManager
    {
        private String _service_root = $"https://login.microsoftonline.com/{WebConfig.TENANT_ID}";

        public AuthenticationResult GetAccessToken()
        {
            var authContext = new AuthenticationContext(_service_root);
            authContext.TokenCache.Clear();
            ClientCredential clientCredentials = new ClientCredential(WebConfig.CLIENT_ID, WebConfig.APP_SECRET);
            AuthenticationResult authResult = authContext.AcquireTokenAsync("https://database.windows.net/", clientCredentials).Result;
            return authResult;
        }

        public SqlConnection CreateSqlConnection(String accessToken, String catalog)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "twine.database.windows.net";
            builder.InitialCatalog = catalog;
            builder.MultipleActiveResultSets = true;
            builder.ApplicationName = "EntityFramework";

            SqlConnection sqlConnection = new SqlConnection(builder.ConnectionString);
            sqlConnection.AccessToken = accessToken;

            return sqlConnection;
        }
    }
}