forked from content-manager-sdk/Community
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
351 lines (260 loc) · 9.23 KB
/
Copy pathProgram.cs
File metadata and controls
351 lines (260 loc) · 9.23 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
using HP.HPTRIM.ServiceModel;
using Microsoft.Identity.Client;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Threading.Tasks;
namespace ConsoleServiceAPIClient
{
class Program
{
private static JsonHttpClient _trimClient;
private static HttpClient _httpClient;
static IPublicClientApplication _app;
static async Task<string> getAuthToken()
{
string clientId = System.Configuration.ConfigurationManager.AppSettings["clientId"];
string tenantId = System.Configuration.ConfigurationManager.AppSettings["tenantId"];
if (_app == null)
{
_app = PublicClientApplicationBuilder.Create(clientId)
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
.Build();
TokenCacheHelper.EnableSerialization(_app.UserTokenCache);
}
var accounts = await _app.GetAccountsAsync();
AuthenticationResult result;
var scopes = new string[] { "User.Read", "offline_access", "openid", "profile" };
try
{
result = await _app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilent.
// This indicates you need to call AcquireTokenInteractive to acquire a token
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
result = await _app.AcquireTokenInteractive(scopes)
.ExecuteAsync();
}
catch (MsalException msalex)
{
Console.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
throw;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}");
throw;
}
return result.IdToken;
}
static async Task<JsonHttpClient> getServiceClient()
{
string token = await getAuthToken();
if (_trimClient == null)
{
// repalce the URL with the URL to your ServiceAPI instance
_trimClient = new JsonHttpClient("https://MyDev/ServiceAPI");
}
_trimClient.Headers["Authorization"] = $"Bearer {token}";
return _trimClient;
}
static async Task<HttpClient> getHttpClient()
{
string token = await getAuthToken();
if (_httpClient == null)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return _httpClient;
}
static async Task Main(string[] args)
{
var stopWatch = Stopwatch.StartNew();
// await recordTypeSearch();
// await getRecordUri();
// await getRecordTitle();
// await createRecord();
//await recordSearch();
//await streamSearch();
//await createRecordWithDocument();
// await getDocument();
//await uploadFileAndCreateRecord();
await uploadBinaryFileAndCreateRecord();
Console.WriteLine(stopWatch.ElapsedMilliseconds);
Console.ReadKey();
}
private async static Task recordTypeSearch()
{
var trimClient = await getServiceClient();
var response = trimClient.Get<RecordTypesResponse>(new RecordTypes() { q = "all" });
Console.WriteLine(response.Results[0].Uri );
}
private async static Task getRecordUri()
{
var trimClient = await getServiceClient();
var response = trimClient.Get<RecordsResponse>(new RecordFind() { Id = "REC_1" });
Console.WriteLine(response.Results[0].Uri);
}
private async static Task getRecordTitle()
{
var trimClient = await getServiceClient();
var response = trimClient.Get<RecordsResponse>(new RecordFind()
{
Id = "REC_1",
Properties = new List<string>() { $"{PropertyIds.RecordTitle}" }
});
Console.WriteLine(response.Results[0].Title);
}
private async static Task createRecord()
{
var trimClient = await getServiceClient();
var record = new Record()
{
RecordType = new RecordTypeRef() { FindBy = "Document" },
Title = "my test",
Properties = new List<string>() { $"{PropertyIds.RecordTitle}" }
};
var response = trimClient.Post<RecordsResponse>(record);
Console.WriteLine(response.Results[0].Title);
}
private async static Task recordSearch()
{
var trimClient = await getServiceClient();
var response = trimClient.Get<RecordsResponse>(new Records()
{
q = "all",
Properties = new List<string>() { $"{PropertyIds.RecordOwnerLocation}" },
ResultsOnly = true,
PropertyValue = PropertyType.String,
pageSize = 100
});
foreach (var record in response.Results)
{
Console.WriteLine(record.OwnerLocation.StringValue);
}
}
private async static Task streamSearch()
{
var trimClient = await getServiceClient();
var response = trimClient.Get<RecordsResponse>(new TrimStreamSearch()
{
TrimType = BaseObjectTypes.Record,
q = "all",
Properties = new List<string>() { $"{PropertyIds.RecordOwnerLocation}", $"{PropertyIds.RecordTitle}" },
pageSize = 100,
});
foreach (var record in response.Results)
{
Console.WriteLine(record.Uri);
Console.WriteLine(record.OwnerLocation);
}
}
private async static Task createRecordWithDocument()
{
var trimClient = await getServiceClient();
var record = new Record()
{
RecordType = new RecordTypeRef() { FindBy = "Document" },
Title = "my test document",
Properties = new List<string>() { $"{PropertyIds.RecordTitle}" }
};
using (FileStream filestream = new FileStream("d:\\junk\\trim.png", FileMode.Open))
{
var uploadFile = new ServiceStack.UploadFile("trim.png", filestream);
uploadFile.ContentType = "image/png";
var response = trimClient.PostFilesWithRequest<RecordsResponse>(record, new ServiceStack.UploadFile[] { uploadFile });
Console.WriteLine(response.Results[0].Title);
}
}
private async static Task uploadFileAndCreateRecord()
{
var trimClient = await getServiceClient();
var httpClient = await getHttpClient();
HP.HPTRIM.ServiceModel.UploadFile uploadFileRequest = new HP.HPTRIM.ServiceModel.UploadFile();
string url = trimClient.ResolveTypedUrl("POST", uploadFileRequest);
using (var fileStream = File.OpenRead("d:\\junk\\trim.png"))
using (var formContent = new MultipartFormDataContent("NKdKd9Yk"))
using (var streamContent = new StreamContent(fileStream))
{
formContent.Headers.ContentType.MediaType = "multipart/form-data";
formContent.Add(streamContent, "Files", "trim.png");
var uploadedFileResponse = await httpClient.PostAsync(url, formContent);
var uploadedJson = await uploadedFileResponse.Content.ReadAsStringAsync();
var uploadedFile = uploadedJson.FromJson<UploadFileResponse>();
var record = new Record()
{
RecordType = new RecordTypeRef() { FindBy = "Document" },
Title = "my test document",
Properties = new List<string>() { $"{PropertyIds.RecordTitle}" },
FilePath = uploadedFile.FilePath
};
var response = await trimClient.PostAsync<RecordsResponse>(record);
Console.WriteLine(response.Results[0].Title);
}
}
private async static Task uploadBinaryFileAndCreateRecord()
{
var trimClient = await getServiceClient();
var httpClient = await getHttpClient();
HP.HPTRIM.ServiceModel.UploadFile uploadFileRequest = new HP.HPTRIM.ServiceModel.UploadFile();
string url = trimClient.ResolveTypedUrl("POST", uploadFileRequest);
using (var fileStream = File.OpenRead("d:\\junk\\trim.png"))
using (var streamContent = new StreamContent(fileStream))
{
streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/png");
var uploadedFileResponse = await httpClient.PostAsync(url + "/trim.png", streamContent);
var uploadedJson = await uploadedFileResponse.Content.ReadAsStringAsync();
var uploadedFile = uploadedJson.FromJson<UploadFileResponse>();
var record = new Record()
{
RecordType = new RecordTypeRef() { FindBy = "Document" },
Title = "my test document",
Properties = new List<string>() { $"{PropertyIds.RecordTitle}" },
FilePath = uploadedFile.FilePath
};
var response = await trimClient.PostAsync<RecordsResponse>(record);
Console.WriteLine(response.Results[0].Title);
}
}
private async static Task getDocument()
{
var trimClient = await getServiceClient();
var httpClient = await getHttpClient();
var recordDownload = new RecordDownload()
{
Id = "REC_1",
DownloadType = DownloadType.Document
};
string url = trimClient.ResolveTypedUrl("GET", recordDownload);
var response = await httpClient.GetAsync(url).ConfigureAwait(false);
string fileName = "test.dat";
IEnumerable<string> values;
if (response.Content.Headers.TryGetValues("Content-Disposition", out values))
{
ContentDisposition contentDisposition = new ContentDisposition(values.First());
fileName = contentDisposition.FileName;
}
using (var fileStream = File.Create(Path.Combine($"C:\\junk\\{fileName}")))
{
var stream = await response.Content.ReadAsStreamAsync();
stream.CopyTo(fileStream);
}
}
}
}