-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Program.cs
316 lines (249 loc) · 12.1 KB
/
Program.cs
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
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Extensions.Configuration;
using Microsoft.PowerPlatform.Dataverse.Client;
using Microsoft.Xrm.Sdk;
using System.Text;
namespace PowerPlatform.Dataverse.CodeSamples
{
/// <summary>
/// Demonstrates working with data in file columns.
/// </summary>
/// <remarks>Set the appropriate Url and Username values for your test
/// environment in the appsettings.json file before running this program.
/// You will be prompted in the default browser to enter a password.</remarks>
/// <see cref="https://learn.microsoft.com/power-apps/developer/data-platform/xrm-tooling/use-connection-strings-xrm-tooling-connect#connection-string-parameters"/>
/// <permission cref="https://github.com/microsoft/PowerApps-Samples/blob/master/LICENSE"
/// <author>Jim Daly</author>
class Program
{
/// <summary>
/// Contains the application's configuration settings.
/// </summary>
IConfiguration Configuration { get; }
/// <summary>
/// Constructor. Loads the application configuration settings from a JSON file.
/// </summary>
Program()
{
// Get the path to the appsettings file. If the environment variable is set,
// use that file path. Otherwise, use the runtime folder's settings file.
string? path = Environment.GetEnvironmentVariable("DATAVERSE_APPSETTINGS");
if (path == null) path = "appsettings.json";
// Load the app's configuration settings from the JSON file.
Configuration = new ConfigurationBuilder()
.AddJsonFile(path, optional: false, reloadOnChange: true)
.Build();
}
static void Main()
{
Program app = new();
// Create a Dataverse service client using the default connection string.
ServiceClient serviceClient =
new(app.Configuration.GetConnectionString("default"));
string entityLogicalName = "account";
string fileColumnSchemaName = "sample_FileColumn";
string fileColumnLogicalName = fileColumnSchemaName.ToLower();
string fileName = "25mb.pdf";
string filePath = $"Files\\{fileName}";
FileInfo fileInfo = new(filePath);
string fileMimeType = "application/pdf";
int fileColumnMaxSizeInKb;
Guid? fileId = null;
// Create the File Column
Utility.CreateFileColumn(serviceClient, entityLogicalName, fileColumnSchemaName);
// Update the MaxSizeInKB: Comment this line to get error about file too large for column.
Utility.UpdateFileColumnMaxSizeInKB(serviceClient, entityLogicalName, fileColumnSchemaName.ToLower(), 100 * 1024);
//Get the configured size of the column in KB
fileColumnMaxSizeInKb = Utility.GetFileColumnMaxSizeInKb(serviceClient, entityLogicalName, fileColumnSchemaName.ToLower());
#region create account record
Entity account = new("account")
{
Attributes = {
{ "name", "Test account for file data sample"}
}
};
Guid accountid = serviceClient.Create(account);
EntityReference accountReference = new("account", accountid);
Console.WriteLine($"Created account record with accountid:{accountid}");
#endregion create account record
Console.WriteLine($"Uploading file {filePath} ...");
// Upload the file
try
{
fileId = UploadFile(service: serviceClient,
entityReference: accountReference,
fileAttributeName: fileColumnLogicalName,
fileInfo: fileInfo,
fileMimeType: fileMimeType,
fileColumnMaxSizeInKb: fileColumnMaxSizeInKb);
Console.WriteLine($"Uploaded file {filePath}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// Download the file
if (fileId.HasValue) {
Console.WriteLine($"Downloading file...");
byte[] downloadedFile = DownloadFile(
service: serviceClient,
entityReference: accountReference,
fileAttributeName: fileColumnLogicalName);
// File written to FileOperations\bin\Debug\net6.0
File.WriteAllBytes($"downloaded-{fileName}", downloadedFile);
Console.WriteLine($"Downloaded the file to {Environment.CurrentDirectory}//downloaded-{fileName}.");
// Delete the file
DeleteFileRequest deleteFileRequest = new()
{
FileId = fileId.Value
};
serviceClient.Execute(deleteFileRequest);
Console.WriteLine("Deleted file using FileId.");
// There is no other way to delete a file using the SDK.
}
// Delete the account record
serviceClient.Delete(accountReference.LogicalName, accountReference.Id);
Console.WriteLine("Deleted the account record.");
// Delete the file column
Utility.DeleteFileColumn(serviceClient, entityLogicalName, fileColumnSchemaName);
Console.WriteLine("\nSample complete.");
}
/// <summary>
/// Uploads a file
/// </summary>
/// <param name="service">The service</param>
/// <param name="entityReference">A reference to the record with the file column</param>
/// <param name="fileAttributeName">The name of the file column</param>
/// <param name="fileInfo">Information about the file to upload.</param>
/// <param name="fileMimeType">The mime type of the file, if known.</param>
/// <param name="fileColumnMaxSizeInKb">The size limit of the column, if known.</param>
/// <returns></returns>
static Guid UploadFile(
IOrganizationService service,
EntityReference entityReference,
string fileAttributeName,
FileInfo fileInfo,
string fileMimeType = null,
int? fileColumnMaxSizeInKb = null)
{
// Initialize the upload
InitializeFileBlocksUploadRequest initializeFileBlocksUploadRequest = new()
{
Target = entityReference,
FileAttributeName = fileAttributeName,
FileName = fileInfo.Name
};
var initializeFileBlocksUploadResponse =
(InitializeFileBlocksUploadResponse)service.Execute(initializeFileBlocksUploadRequest);
string fileContinuationToken = initializeFileBlocksUploadResponse.FileContinuationToken;
// Capture blockids while uploading
List<string> blockIds = new();
using Stream uploadFileStream = fileInfo.OpenRead();
int blockSize = 4 * 1024 * 1024; // 4 MB
byte[] buffer = new byte[blockSize];
int bytesRead = 0;
long fileSize = fileInfo.Length;
if (fileColumnMaxSizeInKb.HasValue && (fileInfo.Length/1024) > fileColumnMaxSizeInKb.Value) {
throw new Exception($"The file is too large to be uploaded to this column.");
}
// The number of iterations that will be required:
// int blocksCount = (int)Math.Ceiling(fileSize / (float)blockSize);
int blockNumber = 0;
// While there is unread data from the file
while ((bytesRead = uploadFileStream.Read(buffer, 0, buffer.Length)) > 0)
{
// The file or final block may be smaller than 4MB
if (bytesRead < buffer.Length)
{
Array.Resize(ref buffer, bytesRead);
}
blockNumber++;
//string blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(blockNumber.ToString().PadLeft(16, '0')));
string blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()));
blockIds.Add(blockId);
// Prepare the request
UploadBlockRequest uploadBlockRequest = new()
{
BlockData = buffer,
BlockId = blockId,
FileContinuationToken = fileContinuationToken,
};
// Send the request
service.Execute(uploadBlockRequest);
}
// Try to get the mimetype if not provided.
if (string.IsNullOrEmpty(fileMimeType))
{
var provider = new FileExtensionContentTypeProvider();
if (!provider.TryGetContentType(fileInfo.Name, out fileMimeType))
{
fileMimeType = "application/octet-stream";
}
}
// Commit the upload
CommitFileBlocksUploadRequest commitFileBlocksUploadRequest = new()
{
BlockList = blockIds.ToArray(),
FileContinuationToken = fileContinuationToken,
FileName = fileInfo.Name,
MimeType = fileMimeType
};
var commitFileBlocksUploadResponse =
(CommitFileBlocksUploadResponse)service.Execute(commitFileBlocksUploadRequest);
return commitFileBlocksUploadResponse.FileId;
}
/// <summary>
/// Downloads a file
/// </summary>
/// <param name="service">The service</param>
/// <param name="entityReference">A reference to the record with the file column</param>
/// <param name="fileAttributeName">The name of the file column</param>
/// <returns></returns>
private static byte[] DownloadFile(
IOrganizationService service,
EntityReference entityReference,
string fileAttributeName)
{
InitializeFileBlocksDownloadRequest initializeFileBlocksDownloadRequest = new()
{
Target = entityReference,
FileAttributeName = fileAttributeName
};
var initializeFileBlocksDownloadResponse =
(InitializeFileBlocksDownloadResponse)service.Execute(initializeFileBlocksDownloadRequest);
string fileContinuationToken = initializeFileBlocksDownloadResponse.FileContinuationToken;
long fileSizeInBytes = initializeFileBlocksDownloadResponse.FileSizeInBytes;
List<byte> fileBytes = new((int)fileSizeInBytes);
long offset = 0;
long blockSizeDownload = 4 * 1024 * 1024; // 4 MB
// File size may be smaller than defined block size
if (fileSizeInBytes < blockSizeDownload)
{
blockSizeDownload = fileSizeInBytes;
}
while (fileSizeInBytes > 0)
{
// Prepare the request
DownloadBlockRequest downLoadBlockRequest = new()
{
BlockLength = blockSizeDownload,
FileContinuationToken = fileContinuationToken,
Offset = offset
};
// Send the request
var downloadBlockResponse =
(DownloadBlockResponse)service.Execute(downLoadBlockRequest);
// Add the block returned to the list
fileBytes.AddRange(downloadBlockResponse.Data);
// Subtract the amount downloaded,
// which may make fileSizeInBytes < 0 and indicate
// no further blocks to download
fileSizeInBytes -= (int)blockSizeDownload;
// Increment the offset to start at the beginning of the next block.
offset += blockSizeDownload;
}
return fileBytes.ToArray();
}
}
}