-
Notifications
You must be signed in to change notification settings - Fork 144
/
PnPPackage.cs
487 lines (427 loc) · 17.9 KB
/
PnPPackage.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
using PnP.Framework.Provisioning.Connectors.OpenXML.Model;
using Portable.Xaml;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
namespace PnP.Framework.Provisioning.Connectors.OpenXML
{
/// <summary>
/// Defines a PnP OpenXML package file
/// </summary>
public partial class PnPPackage : IDisposable
{
#region Constant strings
// site template xaml
public const string R_PROVISIONINGTEMPLATE_MANIFEST = "http://schemas.dev.office.com/pnp/provisioningtemplate/v1/manifest";
public const string R_PROVISIONINGTEMPLATE_BODY = "http://schemas.dev.office.com/pnp/provisioningtemplate/v1/body";
public const string R_PROVISIONINGTEMPLATE_PROPERTIES = "http://schemas.dev.office.com/pnp/provisioningtemplate/v1/properties";
public const string R_PROVISIONINGTEMPLATE_FILES_MAP = "http://schemas.dev.office.com/pnp/provisioningtemplate/v1/files.map";
// supporting files
public const string R_PROVISIONINGTEMPLATE_FILES_ORIGIN = "http://schemas.dev.office.com/pnp/provisioningtemplate/v1/files.origin";
public const string R_PROVISIONINGTEMPLATE_FILE = "http://schemas.dev.office.com/pnp/provisioningtemplate/v1/file";
// content types
public const string CT_PROVISIONINGTEMPLATE_MANIFEST = "application/pnpprovisioningtemplate.manifest";
public const string CT_PROVISIONINGTEMPLATE_BODY = "application/pnpprovisioningtemplate.body";
public const string CT_PROVISIONINGTEMPLATE_PROPERTIES = "application/pnpprovisioningtemplate.properties";
public const string CT_PROVISIONINGTEMPLATE_FILES_MAP = "application/pnpprovisioningtemplate.files.map";
public const string CT_ORIGIN = "application/pnpprovisioningtemplate.origin";
public const string CT_FILE = "application/unknown";
// URLs
public static string U_PROVISIONINGTEMPLATE_MANIFEST = "/manifest.xml";
public static string U_DIR_PROVISIONINGTEMPLATE = "/ProvisioningTemplate/";
public static string U_PROVISIONINGTEMPLATE_PROPERTIES = U_DIR_PROVISIONINGTEMPLATE + "props.xml";
public static string U_PROVISIONINGTEMPLATE_FILES_MAP = U_DIR_PROVISIONINGTEMPLATE + "files-map.xml";
public static string U_FILES_ORIGIN = "/files.origin";
public static string U_DIR_FILES = "/Files/";
// file extensions
public const string EXT_PROVISIONINGTEMPLATE = ".pnp";
#endregion
public const CompressionOption PACKAGE_COMPRESSION_LEVEL = CompressionOption.Maximum;
#region Public Properties
/// <summary>
/// The complete package object
/// </summary>
public Package Package { get; private set; }
/// <summary>
/// The Manifest Part of the package file
/// </summary>
public PackagePart ManifestPart
{
get
{
return GetSinglePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_MANIFEST, null);
}
}
/// <summary>
/// The Manifest of the package file
/// </summary>
public PnPManifest Manifest
{
get
{
return GetXamlSerializedPackagePartValue<PnPManifest>(ManifestPart);
}
set
{
PackagePart manifestPart = EnsurePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_MANIFEST, CT_PROVISIONINGTEMPLATE_MANIFEST, U_PROVISIONINGTEMPLATE_MANIFEST, null);
SetXamlSerializedPackagePartValue(value, manifestPart);
}
}
/// <summary>
/// The Properties of the package
/// </summary>
public PnPProperties Properties
{
get
{
PackagePart propsPart = GetSinglePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_PROPERTIES, ManifestPart);
return GetXamlSerializedPackagePartValue<PnPProperties>(propsPart);
}
set
{
PackagePart propsPart = EnsurePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_PROPERTIES, CT_PROVISIONINGTEMPLATE_PROPERTIES, U_PROVISIONINGTEMPLATE_PROPERTIES, ManifestPart);
SetXamlSerializedPackagePartValue(value, propsPart);
}
}
/// <summary>
/// The File Map for files stored in the OpenXML file
/// </summary>
public PnPFilesMap FilesMap
{
get
{
PackagePart propsPart = GetSinglePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_FILES_MAP, ManifestPart);
return GetXamlSerializedPackagePartValue<PnPFilesMap>(propsPart);
}
set
{
PackagePart propsPart = EnsurePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_FILES_MAP, CT_PROVISIONINGTEMPLATE_FILES_MAP, U_PROVISIONINGTEMPLATE_FILES_MAP, ManifestPart);
SetXamlSerializedPackagePartValue(value, propsPart);
}
}
/// <summary>
/// The Files origin
/// </summary>
public PackagePart FilesOriginPart
{
get
{
return GetSinglePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_FILES_ORIGIN, ManifestPart);
}
}
/// <summary>
/// The Files Parts of the package
/// </summary>
public IList<PackagePart> FilesPackageParts
{
get
{
return GetAllPackagePartsWithRelationshipType(R_PROVISIONINGTEMPLATE_FILE, FilesOriginPart);
}
}
/// <summary>
/// The Files of the package
/// </summary>
public IDictionary<String, PnPPackageFileItem> Files
{
get
{
Dictionary<string, PnPPackageFileItem> result = new Dictionary<string, PnPPackageFileItem>();
var map = FilesMap?.Map;
List<PackagePart> fileParts = GetAllPackagePartsWithRelationshipType(R_PROVISIONINGTEMPLATE_FILE, FilesOriginPart);
foreach (PackagePart p in fileParts)
{
string fileName = p.Uri.ToString().Remove(0, U_DIR_FILES.Length);
string folder = fileName.LastIndexOf('/') >= 0 ?
fileName.Substring(0, fileName.LastIndexOf('/')) : string.Empty;
fileName = fileName.Substring(fileName.LastIndexOf('/') + 1);
if (string.IsNullOrEmpty(folder) && map != null && map.ContainsKey(fileName))
{
//try get folder from original name
var originalName = map[fileName].Replace(@"\", "/");
folder = originalName.LastIndexOf('/') >= 0 ?
originalName.Substring(0, originalName.LastIndexOf('/')) : string.Empty;
}
Byte[] content = ReadPackagePartBytes(p);
result[fileName] = new PnPPackageFileItem
{
Name = fileName,
Folder = folder,
Content = content,
};
}
return result;
}
}
#endregion
#region Package Handling methods
/// <summary>
/// Opens the package and returns it based on the path
/// </summary>
/// <param name="path">Path of the package</param>
/// <param name="mode">File Mode of the package</param>
/// <param name="access">File Access</param>
/// <returns>Package</returns>
public static PnPPackage Open(string path, FileMode mode, FileAccess access)
{
PnPPackage package = new PnPPackage
{
Package = Package.Open(path, mode, access)
};
package.EnsureMandatoryPackageComponents();
return package;
}
/// <summary>
/// Opens the package and returns it based on the stream
/// </summary>
/// <param name="stream">The stream</param>
/// <param name="mode">File Mode of the package</param>
/// <param name="access">File Access</param>
/// <returns>Package</returns>
public static PnPPackage Open(Stream stream, FileMode mode, FileAccess access)
{
PnPPackage package = new PnPPackage
{
Package = Package.Open(stream, mode, access)
};
package.EnsureMandatoryPackageComponents();
return package;
}
/// <summary>
/// Adds file to the package
/// </summary>
/// <param name="fileName">Name of the file</param>
/// <param name="value">Value of the file</param>
public void AddFile(string fileName, Byte[] value)
{
fileName = fileName.TrimStart('/');
string uriStr = U_DIR_FILES + fileName;
PackagePart part = CreatePackagePart(R_PROVISIONINGTEMPLATE_FILE, CT_FILE, uriStr, FilesOriginPart);
SetPackagePartValue(value, part);
}
/// <summary>
/// Clear the files having package parts with specific relationship type
/// </summary>
public void ClearFiles()
{
ClearPackagePartsWithRelationshipType(R_PROVISIONINGTEMPLATE_FILE, FilesOriginPart);
}
#endregion
#region Package Helper Methods
private void EnsureMandatoryPackageComponents()
{
// Manifest
EnsurePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_MANIFEST, CT_PROVISIONINGTEMPLATE_MANIFEST, U_PROVISIONINGTEMPLATE_MANIFEST, null);
// Properties
EnsurePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_PROPERTIES, CT_PROVISIONINGTEMPLATE_PROPERTIES, U_PROVISIONINGTEMPLATE_PROPERTIES, ManifestPart);
// Files origin
EnsurePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_FILES_ORIGIN, CT_ORIGIN, U_FILES_ORIGIN, ManifestPart);
// Files map
EnsurePackagePartWithRelationshipType(R_PROVISIONINGTEMPLATE_FILES_MAP, CT_PROVISIONINGTEMPLATE_FILES_MAP, U_PROVISIONINGTEMPLATE_FILES_MAP, ManifestPart);
}
private PackagePart EnsurePackagePartWithRelationshipType(string relType, string contentType, string uriStr, PackagePart parent)
{
PackagePart part = GetSinglePackagePartWithRelationshipType(relType, parent);
if (part == null)
{
part = CreatePackagePart(relType, contentType, uriStr, parent);
}
return part;
}
private PackagePart EnsurePackagePartWithUri(string relType, string contentType, string uriStr, PackagePart parent)
{
Uri partUri = new Uri(uriStr, UriKind.Relative);
PackagePart part = null;
try
{
part = Package.GetPart(partUri);
}
catch { }
if (part == null)
{
part = CreatePackagePart(relType, contentType, uriStr, parent);
}
return part;
}
private PackagePart GetSinglePackagePartWithRelationshipType(string relType, PackagePart parent)
{
PackageRelationshipCollection rels = parent == null ? Package.GetRelationshipsByType(relType) : parent.GetRelationshipsByType(relType);
PackageRelationship rel = null;
foreach (PackageRelationship r in rels)
{
if (r.TargetMode == TargetMode.Internal)
{
rel = r;
break;
}
}
if (rel != null)
{
return Package.GetPart(rel.TargetUri);
}
return null;
}
private List<PackagePart> GetAllPackagePartsWithRelationshipType(string relType, PackagePart parent)
{
PackageRelationshipCollection rels = parent == null ? Package.GetRelationshipsByType(relType) : parent.GetRelationshipsByType(relType);
List<PackagePart> pkgList = new List<PackagePart>();
foreach (PackageRelationship rel in rels)
{
if (rel.TargetMode == TargetMode.Internal)
pkgList.Add(Package.GetPart(rel.TargetUri));
}
return pkgList;
}
private T GetXamlSerializedPackagePartValue<T>(PackagePart part) where T : class
{
if (part == null)
{
return null;
}
T obj = null;
using (Stream stream = part.GetStream(FileMode.Open))
{
using (var streamReader = new StreamReader(stream))
{
var textContent = streamReader.ReadToEnd();
if (textContent.Contains("clr-namespace:OfficeDevPnP.Core.Framework.Provisioning.Connectors.OpenXML.Model;assembly=OfficeDevPnP.Core"))
{
textContent = textContent.Replace("clr-namespace:OfficeDevPnP.Core.Framework.Provisioning.Connectors.OpenXML.Model;assembly=OfficeDevPnP.Core", "clr-namespace:PnP.Framework.Provisioning.Connectors.OpenXML.Model;assembly=PnP.Framework");
var contentBytes = System.Text.Encoding.UTF8.GetBytes(textContent);
using (var memoryStream = new MemoryStream(contentBytes))
{
obj = (T)XamlServices.Load(memoryStream);
}
}
else
{
stream.Seek(0, SeekOrigin.Begin);
if (stream.Length == 0)
{
return null;
}
obj = (T)XamlServices.Load(stream);
}
}
}
return obj;
}
private void SetXamlSerializedPackagePartValue(object value, PackagePart part)
{
if (value == null)
return;
using (Stream stream = part.GetStream(FileMode.Create))
{
string partStr = XamlServices.Save(value);
using (stream)
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(partStr);
}
}
}
}
private void SetPackagePartValue(Byte[] value, PackagePart part)
{
if (value == null)
{
value = new byte[] { };
}
using (Stream stream = part.GetStream(FileMode.OpenOrCreate))
{
//using (stream)
//{
stream.Write(value, 0, value.Length);
//}
}
}
private PackagePart CreatePackagePart(string relType, string contentType, string uriStr, PackagePart parent)
{
// create part & relationship
Uri uri = GetUri(uriStr);
PackagePart part = Package.CreatePart(uri, contentType, PACKAGE_COMPRESSION_LEVEL);
if (parent == null)
{
Package.CreateRelationship(uri, TargetMode.Internal, relType);
}
else
{
parent.CreateRelationship(uri, TargetMode.Internal, relType);
}
return part;
}
private void ClearPackagePartsWithRelationshipType(string relType, PackagePart parent)
{
ClearPackagePartsWithRelationshipType(relType, parent, null);
}
private void ClearPackagePartsWithRelationshipType(string relType, PackagePart parent, string partUri)
{
PackageRelationshipCollection rels = parent == null ? Package.GetRelationshipsByType(relType) : parent.GetRelationshipsByType(relType);
List<string> relIds = new List<string>();
foreach (PackageRelationship r in rels)
{
if (r.TargetMode == TargetMode.Internal)
{
if (partUri == null || r.TargetUri.ToString() == partUri)
{
Package.DeletePart(r.TargetUri);
relIds.Add(r.Id);
}
}
}
foreach (string relId in relIds)
{
if (parent == null)
{
Package.DeleteRelationship(relId);
}
else
{
parent.DeleteRelationship(relId);
}
}
}
private List<byte[]> ReadPackagePartListBytes(List<PackagePart> partList)
{
List<byte[]> result = new List<byte[]>();
if (partList != null)
{
foreach (PackagePart p in partList)
{
result.Add(ReadPackagePartBytes(p));
}
}
return result;
}
private Byte[] ReadPackagePartBytes(PackagePart part)
{
if (part == null)
return null;
Byte[] bytes;
using (Stream stream = part.GetStream())
{
long size = stream.Length;
//TODO: fix method to support long streams
if (size > Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(part), "Long streams are not supported.");
bytes = new byte[size];
stream.Read(bytes, 0, (int)size);
}
return bytes;
}
#endregion
#region Generic Helper methods
private Uri GetUri(string uriStr)
{
return new Uri(uriStr, UriKind.Relative);
}
#endregion
void IDisposable.Dispose()
{
if (Package != null)
Package.Close();
}
}
}