This repository was archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProgram.cs
More file actions
289 lines (247 loc) · 12.4 KB
/
Program.cs
File metadata and controls
289 lines (247 loc) · 12.4 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//Microsoft Data Catalog team sample
using System;
using System.Text;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net;
using System.IO;
using System.Data;
using System.ServiceModel;
using System.Threading.Tasks;
using GetStartedADCExtensions;
//Install-Package EnterpriseLibrary.TransientFaultHandling
using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;
using ConsoleApplication.Utilities;
namespace ConsoleApplication
{
class Program
{
//TODO: Change {ClientID} to your app client ID
static string clientIDFromAzureAppRegistration = "{ClientID}";
//Note: To find the Catalog name, sign into Azure Data Catalog, and choose User. You will see the Catalog name.
static string catalogName = "DefaultCatalog";
static AuthenticationResult authResult = AccessToken().Result;
static string sampleRootPath = string.Empty;
static RetryPolicy retryPolicy;
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
sampleRootPath = di.Parent.Parent.FullName;
string upn = authResult.UserInfo.DisplayableId;
//Register the data source container
string jsonContainerTemplate = new StreamReader(string.Format(@"{0}\AdHocContainerSample.json", sampleRootPath)).ReadToEnd();
string jsonContainerPayload = string.Format(jsonContainerTemplate, upn);
retryPolicy = new RetryPolicy(
new HttpRequestTransientErrorDetectionStrategy(),
5,
TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(500)
);
//To register a container, use "containers" as view type
string containerId = RegisterDataAsset(catalogName, jsonContainerPayload, "containers");
RegisterDataAssets(containerId);
Console.WriteLine();
Console.WriteLine("Data assets registered from Excel table. Press Enter");
Console.ReadLine();
}
//Get access token:
// To call a Data Catalog REST operation, create an instance of AuthenticationContext and call AcquireToken
// AuthenticationContext is part of the Active Directory Authentication Library NuGet package
// To install the Active Directory Authentication Library NuGet package in Visual Studio,
// run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the NuGet Package Manager Console.
static async Task<AuthenticationResult> AccessToken()
{
if (authResult == null)
{
//Resource Uri for Data Catalog API
string resourceUri = "https://api.azuredatacatalog.com";
//To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID
string clientId = clientIDFromAzureAppRegistration;
//A redirect uri gives AAD more details about the specific application that it will authenticate.
//Since a client app does not have an external service to redirect to, this Uri is the standard placeholder for a client app.
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
// Create an instance of AuthenticationContext to acquire an Azure access token
// OAuth2 authority Uri
string authorityUri = "https://login.windows.net/common/oauth2/authorize";
AuthenticationContext authContext = new AuthenticationContext(authorityUri);
// Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
// AcquireToken takes a Client Id that Azure AD creates when you register your client app.
authResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always));
}
return authResult;
}
//Register data assets from an Excel table
static void RegisterDataAssets(string containerId)
{
string name = string.Empty;
string description = string.Empty;
//Get the Excel workbook path, Sheet Name, and Table Name
DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
string path = String.Format(@"{0}\Ad Hoc Data Catalog.xlsx", di.Parent.Parent.FullName);
string sheetName = "AdventureWorks2014";
string tableName = "Table1";
//ExcelTableToDataTable() is an Extension method which converts an Excel Table to a Data Table
DataTable dt = new DataTable();
dt.ExcelTableToDataTable(path, sheetName, tableName);
//Get the Data Asset JSON template
string jsonAssetTemplate = new StreamReader(string.Format(@"{0}\AdHocSample.json", sampleRootPath)).ReadToEnd();
string jsonAssetPayload = string.Empty;
//Get all DataTable Rows
DataRowCollection rows = dt.Rows;
//Register each table from the Excel Workbook
foreach (DataRow row in rows)
{
name = row["Table"].ToString();
description = row["Description"].ToString();
//Create the JSON payload from Table column
jsonAssetPayload = string.Format(jsonAssetTemplate, containerId, name, authResult.UserInfo.DisplayableId);
//Use the container id returned from the registration of the container to register the asset.
//To register a data asset, use "tables" as view type
string assetUrl = RegisterDataAsset(catalogName, jsonAssetPayload, "tables");
Console.WriteLine("Data Asset Registered: {0} - {1}", name, assetUrl);
//Annotate a description
AnnotateDataAsset(assetUrl, "descriptions", DescriptionJson(description));
Console.WriteLine("Data Asset Description Annotated: {0}", assetUrl);
}
}
// Register data asset:
// The Register Data Asset operation registers a new data asset
// or updates an existing one if an asset with the same identity already exists.
// To register a data asset:
// 1. Register a data source container. viewType = containers
// 2. Register a data asset using a container id. viewType = tables
private static string RegisterDataAsset(string catalogName, string json, string viewType)
{
string location = string.Empty;
string publishResultStatus = string.Empty;
string fullUri = string.Format("https://api.azuredatacatalog.com/catalogs/{0}/views/{1}?api-version=2016-03-30", catalogName, viewType);
//Create a POST WebRequest as a Json content type
HttpWebRequest request = System.Net.WebRequest.Create(fullUri) as System.Net.HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
try
{
using (var httpWebResponse = retryPolicy.ExecuteAction(() => SetRequestAndGetResponse(request, json)))
{
publishResultStatus = httpWebResponse.StatusDescription;
//Get the Response header which contains the data asset ID
//The format is: tables/{data asset ID}
location = httpWebResponse.Headers["Location"];
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.Status);
if (ex.Response != null)
{
// can use ex.Response.Status, .StatusDescription
if (ex.Response.ContentLength != 0)
{
using (var stream = ex.Response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
location = null;
}
return location;
}
//Annotate Data Asset:
// The Annotate Data Asset operation annotates an asset.
private static string AnnotateDataAsset(string viewUrl, string nestedViewName, string json)
{
string responseString = string.Empty;
string fullUri = string.Format("{0}/{1}?api-version=2016-03-30", viewUrl, nestedViewName);
//Create a POST WebRequest as a Json content type
HttpWebRequest request = System.Net.WebRequest.Create(fullUri) as System.Net.HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
try
{
using (var httpWebResponse = retryPolicy.ExecuteAction(() => SetRequestAndGetResponse(request, json)))
{
StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream());
responseString = reader.ReadToEnd();
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.Status);
if (ex.Response != null)
{
// can use ex.Response.Status, .StatusDescription
if (ex.Response.ContentLength != 0)
{
using (var stream = ex.Response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
responseString = null;
}
return responseString;
}
static HttpWebResponse SetRequestAndGetResponse(HttpWebRequest request, string payload = null)
{
while (true)
{
//Add a guid to help with diagnostics
string guid = Guid.NewGuid().ToString();
request.Headers.Add("x-ms-client-request-id", guid);
//To authorize the operation call, you need an access token which is part of the Authorization header
request.Headers.Add("Authorization", AccessToken().Result.CreateAuthorizationHeader());
//Set to false to be able to intercept redirects
request.AllowAutoRedirect = false;
if (!string.IsNullOrEmpty(payload))
{
byte[] byteArray = Encoding.UTF8.GetBytes(payload);
request.ContentLength = byteArray.Length;
request.ContentType = "application/json";
//Write JSON byte[] into a Stream
request.GetRequestStream().Write(byteArray, 0, byteArray.Length);
}
else
{
request.ContentLength = 0;
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// Requests to **Azure Data Catalog (ADC)** may return an HTTP 302 response to indicate
// redirection to a different endpoint. In response to a 302, the caller must re-issue
// the request to the URL specified by the Location response header.
if (response.StatusCode == HttpStatusCode.Redirect)
{
string redirectedUrl = response.Headers["Location"];
HttpWebRequest nextRequest = WebRequest.Create(redirectedUrl) as HttpWebRequest;
nextRequest.Method = request.Method;
request = nextRequest;
}
else
{
return response;
}
}
}
// Description JSON
private static string DescriptionJson(string description)
{
return string.Format(@"
{{
""properties"" : {{
""key"": ""{0}"",
""fromSourceSystem"": false,
""description"": ""{1}""
}}
}}
", Guid.NewGuid().ToString("N"), description);
}
}
}