-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
FileService.cs
992 lines (845 loc) · 38 KB
/
FileService.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Strings;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Services.Implement
{
/// <summary>
/// Represents the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates
/// </summary>
public class FileService : RepositoryService, IFileService
{
private readonly IStylesheetRepository _stylesheetRepository;
private readonly IScriptRepository _scriptRepository;
private readonly ITemplateRepository _templateRepository;
private readonly IPartialViewRepository _partialViewRepository;
private readonly IPartialViewMacroRepository _partialViewMacroRepository;
private readonly IAuditRepository _auditRepository;
private readonly IShortStringHelper _shortStringHelper;
private readonly GlobalSettings _globalSettings;
private readonly IHostingEnvironment _hostingEnvironment;
private const string PartialViewHeader = "@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage";
private const string PartialViewMacroHeader = "@inherits Umbraco.Cms.Web.Common.Macros.PartialViewMacroPage";
public FileService(IScopeProvider uowProvider, ILoggerFactory loggerFactory, IEventMessagesFactory eventMessagesFactory,
IStylesheetRepository stylesheetRepository, IScriptRepository scriptRepository, ITemplateRepository templateRepository,
IPartialViewRepository partialViewRepository, IPartialViewMacroRepository partialViewMacroRepository,
IAuditRepository auditRepository, IShortStringHelper shortStringHelper, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment)
: base(uowProvider, loggerFactory, eventMessagesFactory)
{
_stylesheetRepository = stylesheetRepository;
_scriptRepository = scriptRepository;
_templateRepository = templateRepository;
_partialViewRepository = partialViewRepository;
_partialViewMacroRepository = partialViewMacroRepository;
_auditRepository = auditRepository;
_shortStringHelper = shortStringHelper;
_globalSettings = globalSettings.Value;
_hostingEnvironment = hostingEnvironment;
}
#region Stylesheets
/// <inheritdoc />
public IEnumerable<IStylesheet> GetStylesheets(params string[] paths)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _stylesheetRepository.GetMany(paths);
}
}
/// <inheritdoc />
public IStylesheet GetStylesheet(string path)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _stylesheetRepository.Get(path);
}
}
/// <inheritdoc />
public void SaveStylesheet(IStylesheet stylesheet, int userId = Constants.Security.SuperUserId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new StylesheetSavingNotification(stylesheet, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return;
}
_stylesheetRepository.Save(stylesheet);
scope.Notifications.Publish(new StylesheetSavedNotification(stylesheet, eventMessages).WithStateFrom(savingNotification));
Audit(AuditType.Save, userId, -1, "Stylesheet");
scope.Complete();
}
}
/// <inheritdoc />
public void DeleteStylesheet(string path, int userId = Constants.Security.SuperUserId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
IStylesheet stylesheet = _stylesheetRepository.Get(path);
if (stylesheet == null)
{
scope.Complete();
return;
}
EventMessages eventMessages = EventMessagesFactory.Get();
var deletingNotification = new StylesheetDeletingNotification(stylesheet, eventMessages);
if (scope.Notifications.PublishCancelable(deletingNotification))
{
scope.Complete();
return; // causes rollback
}
_stylesheetRepository.Delete(stylesheet);
scope.Notifications.Publish(new StylesheetDeletedNotification(stylesheet, eventMessages).WithStateFrom(deletingNotification));
Audit(AuditType.Delete, userId, -1, "Stylesheet");
scope.Complete();
}
}
/// <inheritdoc />
public void CreateStyleSheetFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_stylesheetRepository.AddFolder(folderPath);
scope.Complete();
}
}
/// <inheritdoc />
public void DeleteStyleSheetFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_stylesheetRepository.DeleteFolder(folderPath);
scope.Complete();
}
}
/// <inheritdoc />
public Stream GetStylesheetFileContentStream(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _stylesheetRepository.GetFileContentStream(filepath);
}
}
/// <inheritdoc />
public void SetStylesheetFileContent(string filepath, Stream content)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_stylesheetRepository.SetFileContent(filepath, content);
scope.Complete();
}
}
/// <inheritdoc />
public long GetStylesheetFileSize(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _stylesheetRepository.GetFileSize(filepath);
}
}
#endregion
#region Scripts
/// <inheritdoc />
public IEnumerable<IScript> GetScripts(params string[] names)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _scriptRepository.GetMany(names);
}
}
/// <inheritdoc />
public IScript GetScript(string name)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _scriptRepository.Get(name);
}
}
/// <inheritdoc />
public void SaveScript(IScript script, int userId = Constants.Security.SuperUserId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new ScriptSavingNotification(script, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return;
}
_scriptRepository.Save(script);
scope.Notifications.Publish(new ScriptSavedNotification(script, eventMessages).WithStateFrom(savingNotification));
Audit(AuditType.Save, userId, -1, "Script");
scope.Complete();
}
}
/// <inheritdoc />
public void DeleteScript(string path, int userId = Constants.Security.SuperUserId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
IScript script = _scriptRepository.Get(path);
if (script == null)
{
scope.Complete();
return;
}
EventMessages eventMessages = EventMessagesFactory.Get();
var deletingNotification = new ScriptDeletingNotification(script, eventMessages);
if (scope.Notifications.PublishCancelable(deletingNotification))
{
scope.Complete();
return;
}
_scriptRepository.Delete(script);
scope.Notifications.Publish(new ScriptDeletedNotification(script, eventMessages).WithStateFrom(deletingNotification));
Audit(AuditType.Delete, userId, -1, "Script");
scope.Complete();
}
}
/// <inheritdoc />
public void CreateScriptFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_scriptRepository.AddFolder(folderPath);
scope.Complete();
}
}
/// <inheritdoc />
public void DeleteScriptFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_scriptRepository.DeleteFolder(folderPath);
scope.Complete();
}
}
/// <inheritdoc />
public Stream GetScriptFileContentStream(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _scriptRepository.GetFileContentStream(filepath);
}
}
/// <inheritdoc />
public void SetScriptFileContent(string filepath, Stream content)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_scriptRepository.SetFileContent(filepath, content);
scope.Complete();
}
}
/// <inheritdoc />
public long GetScriptFileSize(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _scriptRepository.GetFileSize(filepath);
}
}
#endregion
#region Templates
/// <summary>
/// Creates a template for a content type
/// </summary>
/// <param name="contentTypeAlias"></param>
/// <param name="contentTypeName"></param>
/// <param name="userId"></param>
/// <returns>
/// The template created
/// </returns>
public Attempt<OperationResult<OperationResultType, ITemplate>> CreateTemplateForContentType(string contentTypeAlias, string contentTypeName, int userId = Constants.Security.SuperUserId)
{
var template = new Template(_shortStringHelper, contentTypeName,
//NOTE: We are NOT passing in the content type alias here, we want to use it's name since we don't
// want to save template file names as camelCase, the Template ctor will clean the alias as
// `alias.ToCleanString(CleanStringType.UnderscoreAlias)` which has been the default.
// This fixes: http://issues.umbraco.org/issue/U4-7953
contentTypeName);
EventMessages eventMessages = EventMessagesFactory.Get();
if (contentTypeAlias != null && contentTypeAlias.Length > 255)
{
throw new InvalidOperationException("Name cannot be more than 255 characters in length.");
}
// check that the template hasn't been created on disk before creating the content type
// if it exists, set the new template content to the existing file content
string content = GetViewContent(contentTypeAlias);
if (content != null)
{
template.Content = content;
}
using (IScope scope = ScopeProvider.CreateScope())
{
var savingEvent = new TemplateSavingNotification(template, eventMessages, true, contentTypeAlias);
if (scope.Notifications.PublishCancelable(savingEvent))
{
scope.Complete();
return OperationResult.Attempt.Fail<OperationResultType, ITemplate>(OperationResultType.FailedCancelledByEvent, eventMessages, template);
}
_templateRepository.Save(template);
scope.Notifications.Publish(new TemplateSavedNotification(template, eventMessages).WithStateFrom(savingEvent));
Audit(AuditType.Save, userId, template.Id, ObjectTypes.GetName(UmbracoObjectTypes.Template));
scope.Complete();
}
return OperationResult.Attempt.Succeed<OperationResultType, ITemplate>(OperationResultType.Success, eventMessages, template);
}
/// <summary>
/// Create a new template, setting the content if a view exists in the filesystem
/// </summary>
/// <param name="name"></param>
/// <param name="alias"></param>
/// <param name="content"></param>
/// <param name="masterTemplate"></param>
/// <param name="userId"></param>
/// <returns></returns>
public ITemplate CreateTemplateWithIdentity(string name, string alias, string content, ITemplate masterTemplate = null, int userId = Constants.Security.SuperUserId)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Name cannot be empty or contain only white-space characters", nameof(name));
}
if (name.Length > 255)
{
throw new ArgumentOutOfRangeException(nameof(name), "Name cannot be more than 255 characters in length.");
}
// file might already be on disk, if so grab the content to avoid overwriting
var template = new Template(_shortStringHelper, name, alias)
{
Content = GetViewContent(alias) ?? content
};
if (masterTemplate != null)
{
template.SetMasterTemplate(masterTemplate);
}
SaveTemplate(template, userId);
return template;
}
/// <summary>
/// Gets a list of all <see cref="ITemplate"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
public IEnumerable<ITemplate> GetTemplates(params string[] aliases)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _templateRepository.GetAll(aliases).OrderBy(x => x.Name);
}
}
/// <summary>
/// Gets a list of all <see cref="ITemplate"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
public IEnumerable<ITemplate> GetTemplates(int masterTemplateId)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _templateRepository.GetChildren(masterTemplateId).OrderBy(x => x.Name);
}
}
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its alias.
/// </summary>
/// <param name="alias">The alias of the template.</param>
/// <returns>The <see cref="ITemplate"/> object matching the alias, or null.</returns>
public ITemplate GetTemplate(string alias)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _templateRepository.Get(alias);
}
}
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its identifier.
/// </summary>
/// <param name="id">The identifier of the template.</param>
/// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns>
public ITemplate GetTemplate(int id)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _templateRepository.Get(id);
}
}
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its guid identifier.
/// </summary>
/// <param name="id">The guid identifier of the template.</param>
/// <returns>The <see cref="ITemplate"/> object matching the identifier, or null.</returns>
public ITemplate GetTemplate(Guid id)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
IQuery<ITemplate> query = Query<ITemplate>().Where(x => x.Key == id);
return _templateRepository.Get(query).SingleOrDefault();
}
}
/// <summary>
/// Gets the template descendants
/// </summary>
/// <param name="masterTemplateId"></param>
/// <returns></returns>
public IEnumerable<ITemplate> GetTemplateDescendants(int masterTemplateId)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _templateRepository.GetDescendants(masterTemplateId);
}
}
/// <summary>
/// Saves a <see cref="Template"/>
/// </summary>
/// <param name="template"><see cref="Template"/> to save</param>
/// <param name="userId"></param>
public void SaveTemplate(ITemplate template, int userId = Constants.Security.SuperUserId)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
if (string.IsNullOrWhiteSpace(template.Name) || template.Name.Length > 255)
{
throw new InvalidOperationException("Name cannot be null, empty, contain only white-space characters or be more than 255 characters in length.");
}
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new TemplateSavingNotification(template, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return;
}
_templateRepository.Save(template);
scope.Notifications.Publish(new TemplateSavedNotification(template, eventMessages).WithStateFrom(savingNotification));
Audit(AuditType.Save, userId, template.Id, UmbracoObjectTypes.Template.GetName());
scope.Complete();
}
}
/// <summary>
/// Saves a collection of <see cref="Template"/> objects
/// </summary>
/// <param name="templates">List of <see cref="Template"/> to save</param>
/// <param name="userId">Optional id of the user</param>
public void SaveTemplate(IEnumerable<ITemplate> templates, int userId = Constants.Security.SuperUserId)
{
ITemplate[] templatesA = templates.ToArray();
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new TemplateSavingNotification(templatesA, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return;
}
foreach (ITemplate template in templatesA)
{
_templateRepository.Save(template);
}
scope.Notifications.Publish(new TemplateSavedNotification(templatesA, eventMessages).WithStateFrom(savingNotification));
Audit(AuditType.Save, userId, -1, UmbracoObjectTypes.Template.GetName());
scope.Complete();
}
}
/// <summary>
/// Deletes a template by its alias
/// </summary>
/// <param name="alias">Alias of the <see cref="ITemplate"/> to delete</param>
/// <param name="userId"></param>
public void DeleteTemplate(string alias, int userId = Constants.Security.SuperUserId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
ITemplate template = _templateRepository.Get(alias);
if (template == null)
{
scope.Complete();
return;
}
EventMessages eventMessages = EventMessagesFactory.Get();
var deletingNotification = new TemplateDeletingNotification(template, eventMessages);
if (scope.Notifications.PublishCancelable(deletingNotification))
{
scope.Complete();
return;
}
_templateRepository.Delete(template);
scope.Notifications.Publish(new TemplateDeletedNotification(template, eventMessages).WithStateFrom(deletingNotification));
Audit(AuditType.Delete, userId, template.Id, ObjectTypes.GetName(UmbracoObjectTypes.Template));
scope.Complete();
}
}
private string GetViewContent(string fileName)
{
if (fileName.IsNullOrWhiteSpace())
{
throw new ArgumentNullException(nameof(fileName));
}
if (!fileName.EndsWith(".cshtml"))
{
fileName = $"{fileName}.cshtml";
}
Stream fs = _templateRepository.GetFileContentStream(fileName);
if (fs == null)
{
return null;
}
using (var view = new StreamReader(fs))
{
return view.ReadToEnd().Trim();
}
}
/// <inheritdoc />
public Stream GetTemplateFileContentStream(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _templateRepository.GetFileContentStream(filepath);
}
}
/// <inheritdoc />
public void SetTemplateFileContent(string filepath, Stream content)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_templateRepository.SetFileContent(filepath, content);
scope.Complete();
}
}
/// <inheritdoc />
public long GetTemplateFileSize(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _templateRepository.GetFileSize(filepath);
}
}
#endregion
#region Partial Views
public IEnumerable<string> GetPartialViewSnippetNames(params string[] filterNames)
{
var snippetPath = _hostingEnvironment.MapPathContentRoot($"{Constants.SystemDirectories.Umbraco}/PartialViewMacros/Templates/");
var files = Directory.GetFiles(snippetPath, "*.cshtml")
.Select(Path.GetFileNameWithoutExtension)
.Except(filterNames, StringComparer.InvariantCultureIgnoreCase)
.ToArray();
//Ensure the ones that are called 'Empty' are at the top
var empty = files.Where(x => Path.GetFileName(x).InvariantStartsWith("Empty"))
.OrderBy(x => x.Length)
.ToArray();
return empty.Union(files.Except(empty));
}
public void DeletePartialViewFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_partialViewRepository.DeleteFolder(folderPath);
scope.Complete();
}
}
public void DeletePartialViewMacroFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_partialViewMacroRepository.DeleteFolder(folderPath);
scope.Complete();
}
}
public IEnumerable<IPartialView> GetPartialViews(params string[] names)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _partialViewRepository.GetMany(names);
}
}
public IPartialView GetPartialView(string path)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _partialViewRepository.Get(path);
}
}
public IPartialView GetPartialViewMacro(string path)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _partialViewMacroRepository.Get(path);
}
}
public Attempt<IPartialView> CreatePartialView(IPartialView partialView, string snippetName = null, int userId = Constants.Security.SuperUserId) =>
CreatePartialViewMacro(partialView, PartialViewType.PartialView, snippetName, userId);
public Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, string snippetName = null, int userId = Constants.Security.SuperUserId) =>
CreatePartialViewMacro(partialView, PartialViewType.PartialViewMacro, snippetName, userId);
private Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, PartialViewType partialViewType, string snippetName = null, int userId = Constants.Security.SuperUserId)
{
string partialViewHeader;
switch (partialViewType)
{
case PartialViewType.PartialView:
partialViewHeader = PartialViewHeader;
break;
case PartialViewType.PartialViewMacro:
partialViewHeader = PartialViewMacroHeader;
break;
default:
throw new ArgumentOutOfRangeException(nameof(partialViewType));
}
string partialViewContent = null;
if (snippetName.IsNullOrWhiteSpace() == false)
{
//create the file
Attempt<string> snippetPathAttempt = TryGetSnippetPath(snippetName);
if (snippetPathAttempt.Success == false)
{
throw new InvalidOperationException("Could not load snippet with name " + snippetName);
}
using (var snippetFile = new StreamReader(System.IO.File.OpenRead(snippetPathAttempt.Result)))
{
var snippetContent = snippetFile.ReadToEnd().Trim();
//strip the @inherits if it's there
snippetContent = StripPartialViewHeader(snippetContent);
//Update Model.Content. to be Model. when used as PartialView
if(partialViewType == PartialViewType.PartialView)
{
snippetContent = snippetContent.Replace("Model.Content.", "Model.");
}
partialViewContent = $"{partialViewHeader}{Environment.NewLine}{snippetContent}";
}
}
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var creatingNotification = new PartialViewCreatingNotification(partialView, eventMessages);
if (scope.Notifications.PublishCancelable(creatingNotification))
{
scope.Complete();
return Attempt<IPartialView>.Fail();
}
IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
if (partialViewContent != null)
{
partialView.Content = partialViewContent;
}
repository.Save(partialView);
scope.Notifications.Publish(new PartialViewCreatedNotification(partialView, eventMessages).WithStateFrom(creatingNotification));
Audit(AuditType.Save, userId, -1, partialViewType.ToString());
scope.Complete();
}
return Attempt<IPartialView>.Succeed(partialView);
}
public bool DeletePartialView(string path, int userId = Constants.Security.SuperUserId) =>
DeletePartialViewMacro(path, PartialViewType.PartialView, userId);
public bool DeletePartialViewMacro(string path, int userId = Constants.Security.SuperUserId) =>
DeletePartialViewMacro(path, PartialViewType.PartialViewMacro, userId);
private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int userId = Constants.Security.SuperUserId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
IPartialView partialView = repository.Get(path);
if (partialView == null)
{
scope.Complete();
return true;
}
EventMessages eventMessages = EventMessagesFactory.Get();
var deletingNotification = new PartialViewDeletingNotification(partialView, eventMessages);
if (scope.Notifications.PublishCancelable(deletingNotification))
{
scope.Complete();
return false;
}
repository.Delete(partialView);
scope.Notifications.Publish(new PartialViewDeletedNotification(partialView, eventMessages).WithStateFrom(deletingNotification));
Audit(AuditType.Delete, userId, -1, partialViewType.ToString());
scope.Complete();
}
return true;
}
public Attempt<IPartialView> SavePartialView(IPartialView partialView, int userId = Constants.Security.SuperUserId) =>
SavePartialView(partialView, PartialViewType.PartialView, userId);
public Attempt<IPartialView> SavePartialViewMacro(IPartialView partialView, int userId = Constants.Security.SuperUserId) =>
SavePartialView(partialView, PartialViewType.PartialViewMacro, userId);
private Attempt<IPartialView> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int userId = Constants.Security.SuperUserId)
{
using (IScope scope = ScopeProvider.CreateScope())
{
EventMessages eventMessages = EventMessagesFactory.Get();
var savingNotification = new PartialViewSavingNotification(partialView, eventMessages);
if (scope.Notifications.PublishCancelable(savingNotification))
{
scope.Complete();
return Attempt<IPartialView>.Fail();
}
IPartialViewRepository repository = GetPartialViewRepository(partialViewType);
repository.Save(partialView);
Audit(AuditType.Save, userId, -1, partialViewType.ToString());
scope.Notifications.Publish(new PartialViewSavedNotification(partialView, eventMessages).WithStateFrom(savingNotification));
scope.Complete();
}
return Attempt.Succeed(partialView);
}
internal string StripPartialViewHeader(string contents)
{
var headerMatch = new Regex("^@inherits\\s+?.*$", RegexOptions.Multiline);
return headerMatch.Replace(contents, string.Empty);
}
internal Attempt<string> TryGetSnippetPath(string fileName)
{
if (fileName.EndsWith(".cshtml") == false)
{
fileName += ".cshtml";
}
var snippetPath = _hostingEnvironment.MapPathContentRoot($"{Constants.SystemDirectories.Umbraco}/PartialViewMacros/Templates/{fileName}");
return System.IO.File.Exists(snippetPath)
? Attempt<string>.Succeed(snippetPath)
: Attempt<string>.Fail();
}
public void CreatePartialViewFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_partialViewRepository.AddFolder(folderPath);
scope.Complete();
}
}
public void CreatePartialViewMacroFolder(string folderPath)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_partialViewMacroRepository.AddFolder(folderPath);
scope.Complete();
}
}
private IPartialViewRepository GetPartialViewRepository(PartialViewType partialViewType)
{
switch (partialViewType)
{
case PartialViewType.PartialView:
return _partialViewRepository;
case PartialViewType.PartialViewMacro:
return _partialViewMacroRepository;
default:
throw new ArgumentOutOfRangeException(nameof(partialViewType));
}
}
/// <inheritdoc />
public Stream GetPartialViewFileContentStream(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _partialViewRepository.GetFileContentStream(filepath);
}
}
/// <inheritdoc />
public void SetPartialViewFileContent(string filepath, Stream content)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_partialViewRepository.SetFileContent(filepath, content);
scope.Complete();
}
}
/// <inheritdoc />
public long GetPartialViewFileSize(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _partialViewRepository.GetFileSize(filepath);
}
}
/// <inheritdoc />
public Stream GetPartialViewMacroFileContentStream(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _partialViewMacroRepository.GetFileContentStream(filepath);
}
}
/// <inheritdoc />
public void SetPartialViewMacroFileContent(string filepath, Stream content)
{
using (IScope scope = ScopeProvider.CreateScope())
{
_partialViewMacroRepository.SetFileContent(filepath, content);
scope.Complete();
}
}
/// <inheritdoc />
public long GetPartialViewMacroFileSize(string filepath)
{
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
return _partialViewMacroRepository.GetFileSize(filepath);
}
}
#endregion
#region Snippets
public string GetPartialViewSnippetContent(string snippetName) => GetPartialViewMacroSnippetContent(snippetName, PartialViewType.PartialView);
public string GetPartialViewMacroSnippetContent(string snippetName) => GetPartialViewMacroSnippetContent(snippetName, PartialViewType.PartialViewMacro);
private string GetPartialViewMacroSnippetContent(string snippetName, PartialViewType partialViewType)
{
if (snippetName.IsNullOrWhiteSpace())
{
throw new ArgumentNullException(nameof(snippetName));
}
string partialViewHeader;
switch (partialViewType)
{
case PartialViewType.PartialView:
partialViewHeader = PartialViewHeader;
break;
case PartialViewType.PartialViewMacro:
partialViewHeader = PartialViewMacroHeader;
break;
default:
throw new ArgumentOutOfRangeException(nameof(partialViewType));
}
// Try and get the snippet path
Attempt<string> snippetPathAttempt = TryGetSnippetPath(snippetName);
if (snippetPathAttempt.Success == false)
{
throw new InvalidOperationException("Could not load snippet with name " + snippetName);
}
using (var snippetFile = new StreamReader(System.IO.File.OpenRead(snippetPathAttempt.Result)))
{
var snippetContent = snippetFile.ReadToEnd().Trim();
//strip the @inherits if it's there
snippetContent = StripPartialViewHeader(snippetContent);
//Update Model.Content to be Model when used as PartialView
if (partialViewType == PartialViewType.PartialView)
{
snippetContent = snippetContent
.Replace("Model.Content.", "Model.")
.Replace("(Model.Content)", "(Model)");
}
var content = $"{partialViewHeader}{Environment.NewLine}{snippetContent}";
return content;
}
}
#endregion
private void Audit(AuditType type, int userId, int objectId, string entityType) => _auditRepository.Save(new AuditItem(objectId, type, userId, entityType));
// TODO: Method to change name and/or alias of view template
}
}