-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
ContentTypeService.cs
1340 lines (1171 loc) · 58.2 KB
/
ContentTypeService.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
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;
using AutoMapper;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the ContentType Service, which is an easy access to operations involving <see cref="IContentType"/>
/// </summary>
public class ContentTypeService : ContentTypeServiceBase, IContentTypeService
{
private readonly IContentService _contentService;
private readonly IMediaService _mediaService;
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//for example, the Move method needs to be locked but this calls the Save method which also needs to be locked.
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public ContentTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory, IContentService contentService, IMediaService mediaService)
: base(provider, repositoryFactory, logger, eventMessagesFactory)
{
if (contentService == null) throw new ArgumentNullException("contentService");
if (mediaService == null) throw new ArgumentNullException("mediaService");
_contentService = contentService;
_mediaService = mediaService;
}
#region Containers
public Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateContentTypeContainer(int parentId, string name, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
try
{
var container = new EntityContainer(Constants.ObjectTypes.DocumentTypeGuid)
{
Name = name,
ParentId = parentId,
CreatorId = userId
};
if (SavingContentTypeContainer.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.AddOrUpdate(container);
uow.Commit();
SavedContentTypeContainer.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return Attempt.Succeed(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs));
}
catch (Exception ex)
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
}
public Attempt<OperationStatus<EntityContainer, OperationStatusType>> CreateMediaTypeContainer(int parentId, string name, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
try
{
var container = new EntityContainer(Constants.ObjectTypes.MediaTypeGuid)
{
Name = name,
ParentId = parentId,
CreatorId = userId
};
if (SavingMediaTypeContainer.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.AddOrUpdate(container);
uow.Commit();
SavedMediaTypeContainer.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return Attempt.Succeed(new OperationStatus<EntityContainer, OperationStatusType>(container, OperationStatusType.Success, evtMsgs));
}
catch (Exception ex)
{
return Attempt.Fail(new OperationStatus<EntityContainer, OperationStatusType>(null, OperationStatusType.FailedExceptionThrown, evtMsgs), ex);
}
}
}
public Attempt<OperationStatus> SaveContentTypeContainer(EntityContainer container, int userId = 0)
{
return SaveContainer(
SavingContentTypeContainer, SavedContentTypeContainer,
container, Constants.ObjectTypes.DocumentTypeContainerGuid, "document type", userId);
}
public Attempt<OperationStatus> SaveMediaTypeContainer(EntityContainer container, int userId = 0)
{
return SaveContainer(
SavingMediaTypeContainer, SavedMediaTypeContainer,
container, Constants.ObjectTypes.MediaTypeContainerGuid, "media type", userId);
}
private Attempt<OperationStatus> SaveContainer(
TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> savingEvent,
TypedEventHandler<IContentTypeService, SaveEventArgs<EntityContainer>> savedEvent,
EntityContainer container,
Guid containerObjectType,
string objectTypeName, int userId)
{
var evtMsgs = EventMessagesFactory.Get();
if (container.ContainedObjectType != containerObjectType)
{
var ex = new InvalidOperationException("Not a " + objectTypeName + " container.");
return OperationStatus.Exception(evtMsgs, ex);
}
if (container.HasIdentity && container.IsPropertyDirty("ParentId"))
{
var ex = new InvalidOperationException("Cannot save a container with a modified parent, move the container instead.");
return OperationStatus.Exception(evtMsgs, ex);
}
if (savingEvent.IsRaisedEventCancelled(
new SaveEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return OperationStatus.Cancelled(evtMsgs);
}
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
repo.AddOrUpdate(container);
uow.Commit();
}
savedEvent.RaiseEvent(new SaveEventArgs<EntityContainer>(container, evtMsgs), this);
//TODO: Audit trail ?
return OperationStatus.Success(evtMsgs);
}
public EntityContainer GetContentTypeContainer(int containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.DocumentTypeContainerGuid);
}
public EntityContainer GetMediaTypeContainer(int containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.MediaTypeContainerGuid);
}
private EntityContainer GetContainer(int containerId, Guid containerObjectType)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
var container = repo.Get(containerId);
return container;
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(int[] containerIds)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
return repo.GetAll(containerIds);
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(string name, int level)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
return repo.Get(name, level);
}
}
public IEnumerable<EntityContainer> GetMediaTypeContainers(IMediaType mediaType)
{
var ancestorIds = mediaType.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
if (asInt) return asInt.Result;
return int.MinValue;
})
.Where(x => x != int.MinValue && x != mediaType.Id)
.ToArray();
return GetMediaTypeContainers(ancestorIds);
}
public EntityContainer GetContentTypeContainer(Guid containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.DocumentTypeGuid);
}
public IEnumerable<EntityContainer> GetContentTypeContainers(int[] containerIds)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
return repo.GetAll(containerIds);
}
}
public IEnumerable<EntityContainer> GetContentTypeContainers(IContentType contentType)
{
var ancestorIds = contentType.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var asInt = x.TryConvertTo<int>();
if (asInt) return asInt.Result;
return int.MinValue;
})
.Where(x => x != int.MinValue && x != contentType.Id)
.ToArray();
return GetContentTypeContainers(ancestorIds);
}
public EntityContainer GetMediaTypeContainer(Guid containerId)
{
return GetContainer(containerId, Constants.ObjectTypes.MediaTypeGuid);
}
private EntityContainer GetContainer(Guid containerId, Guid containerObjectType)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, containerObjectType))
{
var container = repo.Get(containerId);
return container;
}
}
public IEnumerable<EntityContainer> GetContentTypeContainers(string name, int level)
{
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
return repo.Get(name, level);
}
}
public Attempt<OperationStatus> DeleteContentTypeContainer(int containerId, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.DocumentTypeContainerGuid))
{
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs);
if (DeletingContentTypeContainer.IsRaisedEventCancelled(
new DeleteEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus(OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.Delete(container);
uow.Commit();
DeletedContentTypeContainer.RaiseEvent(new DeleteEventArgs<EntityContainer>(container, evtMsgs), this);
return OperationStatus.Success(evtMsgs);
//TODO: Audit trail ?
}
}
public Attempt<OperationStatus> DeleteMediaTypeContainer(int containerId, int userId = 0)
{
var evtMsgs = EventMessagesFactory.Get();
var uow = UowProvider.GetUnitOfWork();
using (var repo = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
{
var container = repo.Get(containerId);
if (container == null) return OperationStatus.NoOperation(evtMsgs);
if (DeletingMediaTypeContainer.IsRaisedEventCancelled(
new DeleteEventArgs<EntityContainer>(container, evtMsgs),
this))
{
return Attempt.Fail(new OperationStatus(OperationStatusType.FailedCancelledByEvent, evtMsgs));
}
repo.Delete(container);
uow.Commit();
DeletedMediaTypeContainer.RaiseEvent(new DeleteEventArgs<EntityContainer>(container, evtMsgs), this);
return OperationStatus.Success(evtMsgs);
//TODO: Audit trail ?
}
}
#endregion
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAllPropertyTypeAliases()
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAllPropertyTypeAliases();
}
}
/// <summary>
/// Gets all content type aliases
/// </summary>
/// <param name="objectTypes">
/// If this list is empty, it will return all content type aliases for media, members and content, otherwise
/// it will only return content type aliases for the object types specified
/// </param>
/// <returns></returns>
public IEnumerable<string> GetAllContentTypeAliases(params Guid[] objectTypes)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAllContentTypeAliases(objectTypes);
}
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parentId">
/// The parent to copy the content type to, default is -1 (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, int parentId = -1)
{
IContentType parent = null;
if (parentId > 0)
{
parent = GetContentType(parentId);
if (parent == null)
{
throw new InvalidOperationException("Could not find content type with id " + parentId);
}
}
return Copy(original, alias, name, parent);
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parent">
/// The parent to copy the content type to, default is null (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, IContentType parent)
{
Mandate.ParameterNotNull(original, "original");
Mandate.ParameterNotNullOrEmpty(alias, "alias");
if (parent != null)
{
Mandate.That(parent.HasIdentity, () => new InvalidOperationException("The parent content type must have an identity"));
}
var clone = original.DeepCloneWithResetIdentities(alias);
clone.Name = name;
var compositionAliases = clone.CompositionAliases().Except(new[] { alias }).ToList();
//remove all composition that is not it's current alias
foreach (var a in compositionAliases)
{
clone.RemoveContentType(a);
}
//if a parent is specified set it's composition and parent
if (parent != null)
{
//add a new parent composition
clone.AddContentType(parent);
clone.ParentId = parent.Id;
}
else
{
//set to root
clone.ParentId = -1;
}
Save(clone);
return clone;
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(string alias)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Key
/// </summary>
/// <param name="id">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return Enumerable.Empty<IContentType>();
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetContentType(id);
if (found == null) return false;
var query = Query<IContentType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// This is called after an IContentType is saved and is used to update the content xml structures in the database
/// if they are required to be updated.
/// </summary>
/// <param name="contentTypes">A tuple of a content type and a boolean indicating if it is new (HasIdentity was false before committing)</param>
private void UpdateContentXmlStructure(params IContentTypeBase[] contentTypes)
{
var toUpdate = GetContentTypesForXmlUpdates(contentTypes).ToArray();
if (toUpdate.Any())
{
var firstType = toUpdate.First();
//if it is a content type then call the rebuilding methods or content
if (firstType is IContentType)
{
var typedContentService = _contentService as ContentService;
if (typedContentService != null)
{
typedContentService.RePublishAll(toUpdate.Select(x => x.Id).ToArray());
}
else
{
//this should never occur, the content service should always be typed but we'll check anyways.
_contentService.RePublishAll();
}
}
else if (firstType is IMediaType)
{
//if it is a media type then call the rebuilding methods for media
var typedContentService = _mediaService as MediaService;
if (typedContentService != null)
{
typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray());
}
}
}
}
public int CountContentTypes()
{
using (var repository = RepositoryFactory.CreateContentTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Count(Query<IContentType>.Builder);
}
}
public int CountMediaTypes()
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Count(Query<IMediaType>.Builder);
}
}
/// <summary>
/// Validates the composition, if its invalid a list of property type aliases that were duplicated is returned
/// </summary>
/// <param name="compo"></param>
/// <returns></returns>
public Attempt<string[]> ValidateComposition(IContentTypeComposition compo)
{
using (new WriteLock(Locker))
{
try
{
ValidateLocked(compo);
return Attempt<string[]>.Succeed();
}
catch (InvalidCompositionException ex)
{
return Attempt.Fail(ex.PropertyTypeAliases, ex);
}
}
}
protected void ValidateLocked(IContentTypeComposition compositionContentType)
{
// performs business-level validation of the composition
// should ensure that it is absolutely safe to save the composition
// eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
// but that cannot be used (conflict with descendants)
var contentType = compositionContentType as IContentType;
var mediaType = compositionContentType as IMediaType;
var memberType = compositionContentType as IMemberType; // should NOT do it here but... v8!
IContentTypeComposition[] allContentTypes;
if (contentType != null)
allContentTypes = GetAllContentTypes().Cast<IContentTypeComposition>().ToArray();
else if (mediaType != null)
allContentTypes = GetAllMediaTypes().Cast<IContentTypeComposition>().ToArray();
else if (memberType != null)
return; // no compositions on members, always validate
else
throw new Exception("Composition is neither IContentType nor IMediaType nor IMemberType?");
var compositionAliases = compositionContentType.CompositionAliases();
var compositions = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
var propertyTypeAliases = compositionContentType.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).ToArray();
var indirectReferences = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
var comparer = new DelegateEqualityComparer<IContentTypeComposition>((x, y) => x.Id == y.Id, x => x.Id);
var dependencies = new HashSet<IContentTypeComposition>(compositions, comparer);
var stack = new Stack<IContentTypeComposition>();
indirectReferences.ForEach(stack.Push);//Push indirect references to a stack, so we can add recursively
while (stack.Count > 0)
{
var indirectReference = stack.Pop();
dependencies.Add(indirectReference);
//Get all compositions for the current indirect reference
var directReferences = indirectReference.ContentTypeComposition;
foreach (var directReference in directReferences)
{
if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias)) continue;
dependencies.Add(directReference);
//A direct reference has compositions of its own - these also need to be taken into account
var directReferenceGraph = directReference.CompositionAliases();
allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))).ForEach(c => dependencies.Add(c));
}
//Recursive lookup of indirect references
allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)).ForEach(stack.Push);
}
foreach (var dependency in dependencies)
{
if (dependency.Id == compositionContentType.Id) continue;
var contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
if (contentTypeDependency == null) continue;
var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray();
if (intersect.Length == 0) continue;
throw new InvalidCompositionException(compositionContentType.Alias, intersect.ToArray());
}
}
/// <summary>
/// Saves a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IContentType contentType, int userId = 0)
{
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
ValidateLocked(contentType); // throws if invalid
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
uow.Commit();
}
UpdateContentXmlStructure(contentType);
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(contentType, false), this);
Audit(AuditType.Save, string.Format("Save ContentType performed by user"), userId, contentType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var contentType in asArray)
{
ValidateLocked(contentType); // throws if invalid
}
foreach (var contentType in asArray)
{
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(asArray, false), this);
Audit(AuditType.Save, string.Format("Save ContentTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
public void Delete(IContentType contentType, int userId = 0)
{
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
//TODO: This needs to change, if we are deleting a content type, we should just delete the data,
// this method will recursively go lookup every content item, check if any of it's descendants are
// of a different type, move them to the recycle bin, then permanently delete the content items.
// The main problem with this is that for every content item being deleted, events are raised...
// which we need for many things like keeping caches in sync, but we can surely do this MUCH better.
_contentService.DeleteContentOfType(contentType.Id);
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
repository.Delete(contentType);
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(contentType, false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentType performed by user"), userId, contentType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IContentType"/> objects.
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>
/// Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/>
/// </remarks>
public void Delete(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
foreach (var contentType in asArray)
{
_contentService.DeleteContentOfType(contentType.Id);
}
var uow = UowProvider.GetUnitOfWork();
using (var repository = RepositoryFactory.CreateContentTypeRepository(uow))
{
foreach (var contentType in asArray)
{
repository.Delete(contentType);
}
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(asArray, false), this);
}
Audit(AuditType.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(string alias)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(IEnumerable<Guid> ids)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids.ToArray());
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return Enumerable.Empty<IMediaType>();
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(int id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(Guid id)
{
using (var repository = RepositoryFactory.CreateMediaTypeRepository(UowProvider.GetUnitOfWork()))
{
var found = GetMediaType(id);
if (found == null) return false;
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == found.Id);
int count = repository.Count(query);
return count > 0;
}
}
public Attempt<OperationStatus<MoveOperationStatusType>> MoveMediaType(IMediaType toMove, int containerId)
{
var evtMsgs = EventMessagesFactory.Get();
if (MovingMediaType.IsRaisedEventCancelled(
new MoveEventArgs<IMediaType>(evtMsgs, new MoveEventInfo<IMediaType>(toMove, toMove.Path, containerId)),
this))
{
return Attempt.Fail(
new OperationStatus<MoveOperationStatusType>(
MoveOperationStatusType.FailedCancelledByEvent, evtMsgs));
}
var moveInfo = new List<MoveEventInfo<IMediaType>>();
var uow = UowProvider.GetUnitOfWork();
using (var containerRepository = RepositoryFactory.CreateEntityContainerRepository(uow, Constants.ObjectTypes.MediaTypeContainerGuid))
using (var repository = RepositoryFactory.CreateMediaTypeRepository(uow))