private IContentItemDriver GetDriver(ContentItem contentItem) {
     return
         _contentItemDrivers
         .Where(cid => cid.GetContentTypes().Any(ct => string.Compare(ct.Name, contentItem.ContentType, true) == 0))
         //TODO: (erikpo) SingleOrDefault should be called here, but for some reason, the amount of drivers registered is doubled sometimes.
         .FirstOrDefault();
 }
Example #2
0
 public static string tryGetBodyText(ContentItem item)
 {
     BodyPart bodyPart = item.Parts.FirstOrDefault(x => x.PartDefinition.Name == "BodyPart") as BodyPart;
     if (bodyPart != null)
         return bodyPart.Text;
     return null;
 }
Example #3
0
 public bool CompareContent(ContentItem preContentItem, ContentItem newContentItem)
 {
     _defferences.Clear();
     var part = newContentItem.Parts.FirstOrDefault(p => p.PartDefinition.Name.Contains(preContentItem.ContentType));
     if (part == null) return false;
     var fieldContext = new PropertyContext
     {
         State = FormParametersHelper.ToDynamic(string.Empty)
     };
     string category = newContentItem.ContentType + "ContentFields";
     var allFielDescriptors = _projectionManager.DescribeProperties().Where(p => p.Category == category).SelectMany(x => x.Descriptors).ToList();
     foreach (var field in part.Fields) {
         if (!field.PartFieldDefinition.Settings.ContainsKey(isAuditKey)) continue;
         bool isAudit = bool.Parse(field.PartFieldDefinition.Settings[isAuditKey]);
         if (!isAudit) continue;
         if (_defferences.Keys.Contains(field.Name)) continue;
         var descriptor = allFielDescriptors.FirstOrDefault(d => d.Name.Text == field.Name + ":Value");
         if (descriptor == null) continue;
         var preValue = descriptor.Property(fieldContext, preContentItem);
         var newValue = descriptor.Property(fieldContext, newContentItem);
         if (preValue != null && !string.IsNullOrEmpty(preValue.ToString())
             && (newValue == null || string.IsNullOrEmpty(newValue.ToString())))
         {
             _defferences.Add(field.Name, string.Format("Deleted {1} in {0}.", field.Name, preValue));
         }
         else if (preValue != null && newValue.ToString() != preValue.ToString() ||
             preValue == null && newValue != null && !string.IsNullOrEmpty(newValue.ToString()))
         {
             _defferences.Add(field.Name, string.Format("Changed {0} from {1} to {2}.", field.Name, preValue, newValue));
         }
     }
     return _defferences.Count == 1;
 }
Example #4
0
        public void UpdateBundleProducts(ContentItem item, IEnumerable<ProductEntry> products) {
            var record = item.As<BundlePart>().Record;
            var oldProducts = _bundleProductsRepository.Fetch(
                r => r.BundlePartRecord == record);
            var lookupNew = products
                .Where(e => e.Quantity > 0)
                .ToDictionary(r => r.ProductId, r => r.Quantity);
            // Delete the products that are no longer there
            // and updtes the ones that should stay
            foreach (var bundleProductRecord in oldProducts) {
                var key = bundleProductRecord.ContentItemRecord.Id;
                if (lookupNew.ContainsKey(key)) {
                    bundleProductRecord.Quantity = lookupNew[key];
                    _bundleProductsRepository.Update(bundleProductRecord);
                    lookupNew.Remove(key);
                }
                else {
                    _bundleProductsRepository.Delete(bundleProductRecord);
                }
            }
            // Add the new products
            foreach (var productQuantity in lookupNew
                .Where(kvp => kvp.Value > 0)
                .Select(kvp => new ProductQuantity {ProductId = kvp.Key, Quantity = kvp.Value})) {

                AddProduct(productQuantity.Quantity, productQuantity.ProductId, record);
            }
        }
        private bool IsValid(int itemId, out ContentItem item, out ActionResult invalidResult)
        {
            if (_orchardServices.WorkContext.CurrentUser == null || !_orchardServices.Authorizer.Authorize(Permissions.WatchItems))
            {
                invalidResult = new HttpUnauthorizedResult();
                item = null;
                return false;
            }

            item = _orchardServices.ContentManager.Get(itemId);

            if (item == null)
            {
                invalidResult = HttpNotFound();
                return false;
            }

            if (!_orchardServices.Authorizer.Authorize(Orchard.Core.Contents.Permissions.ViewContent))
            {
                invalidResult = new HttpUnauthorizedResult();
                return false;
            }

            if (!item.Has<WatchablePart>())
            {
                invalidResult = HttpNotFound();
                return false;
            }

            invalidResult = null;
            return true;
        }
        //Finds localized route part for the specified content and culture
        //Returns true if localized url for content and culture exists; otherwise - false
        public bool TryFindLocalizedRoute(ContentItem routableContent, string cultureName, out AutoroutePart localizedRoute) {
            if (!routableContent.Parts.Any(p => p.Is<ILocalizableAspect>())) {
                localizedRoute = null;
                return false;
            }

            //var siteCulture = _cultureManager.GetCultureByName(_cultureManager.GetSiteCulture());
            IEnumerable<LocalizationPart> localizations = _localizationService.GetLocalizations(routableContent, VersionOptions.Published);

            ILocalizableAspect localizationPart = null, siteCultureLocalizationPart = null;
            foreach (LocalizationPart l in localizations) {
                if (l.Culture.Culture == cultureName) {
                    localizationPart = l;
                    break;
                }
                if (l.Culture == null && siteCultureLocalizationPart == null) {
                    siteCultureLocalizationPart = l;
                }
            }

            //try get localization part for default site culture
            if (localizationPart == null) {
                localizationPart = siteCultureLocalizationPart;
            }

            if (localizationPart == null) {
                localizedRoute = null;
                return false;
            }

            ContentItem localizedContentItem = localizationPart.ContentItem;
            localizedRoute = localizedContentItem.Parts.Single(p => p is AutoroutePart).As<AutoroutePart>();
            return true;
        }
 public void Store(string id, ContentItem item) {
     var contentIdentity = new ContentIdentity(id);
     if (_dictionary.ContainsKey(contentIdentity)) {
         _dictionary.Remove(contentIdentity);
     }
     _dictionary.Add(contentIdentity, item);
 }
Example #8
0
 private void Vote(ContentItem content, IUser currentUser, int rating, VoteRecord currentVote) {
     if (currentVote != null)
         _votingService.ChangeVote(currentVote, rating);
     else {
         _votingService.Vote(content, currentUser.UserName, HttpContext.Request.UserHostAddress, rating);
     }
 }
        void IArchiveLaterService.ArchiveLater(ContentItem contentItem, DateTime scheduledArchiveUtc) {
            if (!Services.Authorizer.Authorize(Permissions.PublishContent, contentItem, T("Couldn't archive selected content.")))
                return;

            RemoveArchiveLaterTasks(contentItem);
            _scheduledTaskManager.CreateTask(UnpublishTaskType, scheduledArchiveUtc, contentItem);
        }
Example #10
0
 public static void EmailAsync(this IScheduledTaskManager _taskManager, ContentItem contentItem)
 {
    
     var tasks = _taskManager.GetTasks(Services.EmailScheduledTaskHandler.TASK_TYPE_EMAIL);
     if (tasks == null || tasks.Count() < 100)
         _taskManager.CreateTask(Services.EmailScheduledTaskHandler.TASK_TYPE_EMAIL, DateTime.UtcNow, contentItem);
 }
Example #11
0
        public dynamic Render(PropertyContext context, ContentItem contentItem, IFieldTypeEditor fieldTypeEditor, string storageName, Type storageType, ContentPartDefinition part, ContentPartFieldDefinition field) {
            var p = contentItem.Parts.FirstOrDefault( x => x.PartDefinition.Name == part.Name);

            if(p == null) {
                return String.Empty;
            }

            var f = p.Fields.FirstOrDefault(x => x.Name == field.Name);

            if(f == null) {
                return String.Empty;
            }

            object value = null;

            _contentFieldValueProviders.Invoke(provider => {
                var result = provider.GetValue(contentItem, f);
                if (result != null) {
                    value = result;
                }
            }, Logger);

            if (value == null) {
                value = f.Storage.Get<object>(storageName);
            }

            if (value == null) {
                return null;
            }

            // call specific formatter rendering
            return _propertyFormater.Format(storageType, value, context.State);
        }
        //Finds localized route part for the specified content and culture
        //Returns true if localized url for content and culture exists; otherwise - false
        public bool TryFindLocalizedRoute(ContentItem routableContent, string cultureName, out RoutePart localizedRoute)
        {
            if (!routableContent.Parts.Any(p => p.Is<LocalizationPart>())) {
                localizedRoute = null;
                return false;
            }

            var siteCulture = _cultureManager.GetCultureByName(_cultureManager.GetSiteCulture());
            var localizations = _localizationService.GetAvailableLocalizations(routableContent, VersionOptions.Published, siteCulture);
            var localizationPart = localizations.FirstOrDefault(l => l.Culture.Culture == cultureName);

            //try get localization part for default site culture
            if (localizationPart == null) {
                localizationPart = localizations.FirstOrDefault(l => l.Culture.Equals(siteCulture));
            }

            if (localizationPart == null) {
                localizedRoute = null;
                return false;
            }

            var localizedContentItem = localizationPart.ContentItem;
            localizedRoute = localizedContentItem.Parts.Single(p => p is RoutePart).As<RoutePart>();
            return true;
        }
Example #13
0
        public void sendEmail(int idMenu, ContentItem item)
        {
            var slug = item.As<RoutePart>().Slug;
            var request = httpContextAccessor.Current().Request;
            var containerUrl = new UriBuilder(request.ToRootUrlString()) { Path = (request.ApplicationPath ?? "").TrimEnd('/') + "/" + (item.As<RoutePart>().GetContainerPath() ?? "") };
            var link = containerUrl.Uri.ToString().TrimEnd('/');

            var menu = menuService.Get(idMenu);
            var course = courseService.Get(menu.Course.Id);
            var year = yearService.Get(course.Year.Id);
            var props = new Dictionary<string, string> {
                { "ContentTypeName", item.ContentType },
                { "Title", ContentHelper.tryGetRouteTitle(item) },
                { "Link", link + slug},
                { "Year", year.Name},
                { "Course", course.Name},
                { "CourseMenu", menu.Name}
            };

            var users = mailRepo.Fetch(x => x.Menu.Id == idMenu).Select(x => membershipService.GetUser(x.UserName));

            foreach (var user in users)
            {
                messageManager.Send(user.ContentItem.Record, MessageTypes.MailNotification, "email", props);
            }
        }
        private void SetupRoutePart(PackagePart packagePartToMapTo) {
            var contentItem = new ContentItem { ContentType = "Package" };
            var routePart = new AutoroutePart {Record = new AutoroutePartRecord()};
            contentItem.Weld(routePart);
            contentItem.Weld(packagePartToMapTo);

        }
        public void NullCheckingCanBeDoneOnProperties() {
            var contentItem = new ContentItem();
            var contentPart = new ContentPart { TypePartDefinition = new ContentTypePartDefinition(new ContentPartDefinition("FooPart"), new SettingsDictionary()) };
            var contentField = new ContentField { PartFieldDefinition = new ContentPartFieldDefinition(new ContentFieldDefinition("FooType"), "FooField", new SettingsDictionary()) };

            dynamic item = contentItem;
            dynamic part = contentPart;

            Assert.That(item.FooPart == null, Is.True);
            Assert.That(item.FooPart != null, Is.False);

            contentItem.Weld(contentPart);

            Assert.That(item.FooPart == null, Is.False);
            Assert.That(item.FooPart != null, Is.True);
            Assert.That(item.FooPart, Is.SameAs(contentPart));

            Assert.That(part.FooField == null, Is.True);
            Assert.That(part.FooField != null, Is.False);
            Assert.That(item.FooPart.FooField == null, Is.True);
            Assert.That(item.FooPart.FooField != null, Is.False);

            contentPart.Weld(contentField);

            Assert.That(part.FooField == null, Is.False);
            Assert.That(part.FooField != null, Is.True);
            Assert.That(item.FooPart.FooField == null, Is.False);
            Assert.That(item.FooPart.FooField != null, Is.True);
            Assert.That(part.FooField, Is.SameAs(contentField));
            Assert.That(item.FooPart.FooField, Is.SameAs(contentField));
        }
        public void TestInit() {
            _testItemIdentity1 = new ContentIdentity("/ItemId=1");
            _testItemIdentity2 = new ContentIdentity("/ItemId=2");
            _testItemIdentity3 = new ContentIdentity("/ItemId=3");
            _testItemIdentity4 = new ContentIdentity("/ItemId=4");
            _testItemIdentity5 = new ContentIdentity("/ItemId=5");
            var draftItem = new ContentItem { VersionRecord = new ContentItemVersionRecord { Id = 1234, Published = false, Latest = true, ContentItemRecord = new ContentItemRecord { Id = 1 } } };
            var publishedItem = new ContentItem { VersionRecord = new ContentItemVersionRecord { Id = 1234, Published = true, Latest = true, ContentItemRecord = new ContentItemRecord { Id = 1 } } };

            var draftItem5 = new ContentItem { VersionRecord = new ContentItemVersionRecord { Id = 1234, Published = false, Latest = true, ContentItemRecord = new ContentItemRecord { Id = 5 } } };
            var publishedItem5 = new ContentItem { VersionRecord = new ContentItemVersionRecord { Id = 1234, Published = true, Latest = true, ContentItemRecord = new ContentItemRecord { Id = 5 } } };

            _contentManager = new Mock<IContentManager>();
            _contentManager.Setup(m => m.Get(It.Is<int>(v => v == 1), It.Is<VersionOptions>(v => v.IsDraftRequired))).Returns(draftItem);
            _contentManager.Setup(m => m.Get(It.Is<int>(v => v == 1), It.Is<VersionOptions>(v => !v.IsDraftRequired))).Returns(publishedItem);

            _contentManager.Setup(m => m.Get(It.Is<int>(v => v == 5), It.Is<VersionOptions>(v => v.IsDraftRequired))).Returns(draftItem5);
            _contentManager.Setup(m => m.Get(It.Is<int>(v => v == 5), It.Is<VersionOptions>(v => !v.IsDraftRequired))).Returns(publishedItem5);

            _contentManager.Setup(m => m.GetItemMetadata(It.Is<IContent>(c => c.Id == 1))).Returns(new ContentItemMetadata { Identity = _testItemIdentity1 });
            _contentManager.Setup(m => m.GetItemMetadata(It.Is<IContent>(c => c.Id == 5))).Returns(new ContentItemMetadata { Identity = _testItemIdentity5 });

            _contentManager.Setup(m => m.New(It.IsAny<string>())).Returns(draftItem5);

            _contentManager.Setup(m => m.ResolveIdentity(It.Is<ContentIdentity>(id => id.Get("ItemId") == "1"))).Returns(publishedItem);
        }
 public IEnumerable<IScheduledTask> GetTasks(ContentItem contentItem) {
     return _repository
         .Fetch(x => x.ContentItemVersionRecord.ContentItemRecord == contentItem.Record)
         .Select(x => new Task(_contentManager, x))
         .Cast<IScheduledTask>()
         .ToReadOnlyCollection();
 }
        private static bool AreEqual(ContentItem item1, ContentItem item2, XElement item1Export, XElement item2Export)
        {
            //todo: this is a little too generous
            if (!item1.SharesIdentifierWith(item2))
                return false;

            if (item1.Has<TitlePart>() && item2.Has<TitlePart>())
            {
                if (!item1.As<TitlePart>().Title.Equals(item2.As<TitlePart>().Title, StringComparison.CurrentCulture))
                {
                    return false;
                }
            }

            if (item1.Has<BodyPart>() && item2.Has<BodyPart>())
            {
                var text1 = item1.As<BodyPart>().Text;
                var text2 = item2.As<BodyPart>().Text;

                if (text1 == null || text2 == null)
                    return false;

                if (!item1.As<BodyPart>().Text.Equals(item2.As<BodyPart>().Text, StringComparison.CurrentCulture))
                {
                    return false;
                }
            }

            // compare xml elements
            return Differences(item1Export, item2Export) == 0;
        }
        public override IDisplayResult Display(ContentItem contentItem, IUpdateModel updater)
        {
            var testContentPart = contentItem.As<TestContentPartA>();

            if (testContentPart == null)
            {
                return null;
            }

            return Combine(
                // A new shape is created and the properties of the object are bound to it when rendered
                Shape("TestContentPartA", testContentPart).Location("Detail", "Content"),
                // New shape, no initialization, custom location
                Shape("LowerDoll").Location("Detail", "Footer"),
                // New shape 
                Shape("TestContentPartA",
                    ctx => ctx.New.TestContentPartA().Creating(_creating++),
                    shape =>
                    {
                        shape.Processing = _processing++;
                        return Task.CompletedTask;
                    })
                    .Location("Detail", "Content")
                    .Cache("lowerdoll2", cache => cache.During(TimeSpan.FromSeconds(5))),
                // A strongly typed shape model is used and initialized when rendered
                Shape<TestContentPartAShape>(shape => { shape.Line = "Strongly typed shape"; return Task.CompletedTask; })
                    .Location("Detail", "Content:2"),
                // Cached shape
                Shape("LowerDoll")
                    .Location("Detail", "/Footer")
                    .Cache("lowerdoll", cache => cache.During(TimeSpan.FromSeconds(5)))
                );
        }
        public static void CreateTaskIfNew(this IScheduledTaskManager taskManager, string taskType, DateTime scheduledUtc, ContentItem contentItem)
        {
            var outdatedTaskCount = taskManager.GetTasks(taskType, DateTime.UtcNow).Count();
            var taskCount = taskManager.GetTasks(taskType).Count();
            if (taskCount != 0 && taskCount - outdatedTaskCount > 0) return;

            taskManager.CreateTask(taskType, scheduledUtc, contentItem); 
        }
        public void RegisterAnonVote(ContentItem contentItem, int rating) {
            var currentContext = _httpContextAccessor.Current();
            var anonHostname = currentContext.Request.UserHostAddress;
            if (!string.IsNullOrWhiteSpace(currentContext.Request.Headers["X-Forwarded-For"]))
                anonHostname += "-" + currentContext.Request.Headers["X-Forwarded-For"];

            _votingService.Vote(contentItem, "Anonymous", anonHostname, rating, Constants.Voting.RatingConstant);
        }
        public void Store(ContentItem item) {
            _itemByVersionRecordId.Add(item.VersionRecord.Id, item);

            // is it the Published version ?
            if (item.VersionRecord.Latest && item.VersionRecord.Published) {
                _publishedItemsByContentRecordId[item.Id] = item;
            }
        }
Example #23
0
 public GraphNode MakeNode(ContentItem item)
 {
     var node = new GraphNode()
     {
         Item = item
     };
     return node;
 }
Example #24
0
 public void RemoveAliases(ContentItem content)
 {
     var rvd = content.ContentManager.GetItemMetadata(content).DisplayRouteValues;
     foreach (var alias in _aliasService.Lookup(rvd))
     {
         _aliasService.Delete(alias);
     }
 }
 private string GetContentType(int id, ContentItem item, VersionOptions options)
 {
     if (item != null)
     {
         return item.ContentType;
     }
     return (options.VersionRecordId == 0) ? String.Format("Content item: {0} is not published.", id) : "Unknown content type.";
 }
Example #26
0
 public static string tryGetRouteTitle(ContentItem item)
 {
     if (item == null)
         return null;
     RoutePart routePart = item.Parts.FirstOrDefault(x => x.PartDefinition.Name == "RoutePart") as RoutePart;
     if (routePart != null)
         return routePart.Title;
     return null;
 }
 public void MediaUrl(dynamic Shape, dynamic Display, TextWriter Output, string Profile, string Path, ContentItem ContentItem, FilterRecord CustomFilter) {
     try {
         Shape.IgnoreShapeTracer = true;
         Output.Write(_imageProfileManager.Value.GetImageProfileUrl(Path, Profile, CustomFilter, ContentItem));
     }
     catch (Exception ex) {
         Logger.Error(ex, "An error occured while rendering shape {0} for image {1}", Profile, Path);
     }
 }
 public static bool SharesIdentifierWith(this ContentItem item1, ContentItem item2)
 {
     if (item1.Has<IdentityPart>() && item2.Has<IdentityPart>())
     {
         return item1.As<IdentityPart>().Identifier.Equals(item2.As<IdentityPart>().Identifier,
                                                        StringComparison.InvariantCultureIgnoreCase);
     }
     return false;
 }
 public void DeleteTasks(ContentItem item, Func<IScheduledTask, bool> predicate = null)
 {
     if (predicate != null) {
         _scheduledTaskManager.DeleteTasks(item, task => task.TaskType == PublishTaskType && predicate(task));
     }
     else {
         _scheduledTaskManager.DeleteTasks(item, task => task.TaskType == PublishTaskType);
     }
 }
Example #30
0
 public void UpdatePresentationForContentItem(
     ContentItem item, EditPresentationViewModel model)
 {
     var presentationPart = item.As<PresentationPart>();
     presentationPart.Abstract = model.Abstract;
     presentationPart.Name = model.Name;
     presentationPart.Speaker = _speakerRepository.Get(
         s => s.Id == model.SpeakerId);
 }
Example #31
0
 public bool RecallVersionNumber(int id, int version, out ContentItem item)
 {
     return(_itemByVersionNumber.TryGetValue(Tuple.Create(id, version), out item));
 }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var contentItem = new ContentItem();
            var skip        = false;

            while (skip || reader.Read())
            {
                skip = false;

                if (reader.TokenType == JsonToken.EndObject)
                {
                    break;
                }

                if (reader.TokenType != JsonToken.PropertyName)
                {
                    continue;
                }

                var propertyName = (string)reader.Value;

                switch (propertyName)
                {
                case nameof(ContentItem.Id):
                    contentItem.Id = reader.ReadAsInt32() ?? 0;
                    break;

                case nameof(ContentItem.ContentItemId):
                    contentItem.ContentItemId = reader.ReadAsString();
                    break;

                case nameof(ContentItem.ContentItemVersionId):
                    contentItem.ContentItemVersionId = reader.ReadAsString();
                    break;

                case nameof(ContentItem.ContentType):
                    contentItem.ContentType = reader.ReadAsString();
                    break;

                case nameof(ContentItem.Latest):
                    contentItem.Latest = reader.ReadAsBoolean() ?? false;
                    break;

                case nameof(ContentItem.Number):
                    contentItem.Number = reader.ReadAsInt32() ?? 0;
                    break;

                case nameof(ContentItem.Published):
                    contentItem.Published = reader.ReadAsBoolean() ?? false;
                    break;

                case nameof(ContentItem.PublishedUtc):
                    contentItem.PublishedUtc = reader.ReadAsDateTime();
                    break;

                case nameof(ContentItem.ModifiedUtc):
                    contentItem.ModifiedUtc = reader.ReadAsDateTime();
                    break;

                case nameof(ContentItem.CreatedUtc):
                    contentItem.CreatedUtc = reader.ReadAsDateTime();
                    break;

                case nameof(ContentItem.Author):
                    contentItem.Author = reader.ReadAsString();
                    break;

                case nameof(ContentItem.Owner):
                    contentItem.Owner = reader.ReadAsString();
                    break;

                default:
                    var customProperty = JProperty.Load(reader);
                    contentItem.Data.Add(customProperty);

                    // Skip reading a token as JPproperty.Load already did the next one
                    skip = true;
                    break;
                }
            }

            return(contentItem);
        }
Example #33
0
        public async Task <ContentItem> GetAsync(int contentItemId, VersionOptions options)
        {
            ContentItem contentItem = null;

            // obtain the root records based on version options
            if (options.VersionRecordId != 0)
            {
                if (_contentManagerSession.RecallVersionId(options.VersionRecordId, out contentItem))
                {
                    return(contentItem);
                }

                contentItem = await _session.GetAsync <ContentItem>(options.VersionRecordId);
            }
            else if (options.VersionNumber != 0)
            {
                if (_contentManagerSession.RecallContentItemId(contentItemId, options.VersionNumber, out contentItem))
                {
                    return(contentItem);
                }

                contentItem = await _session
                              .QueryAsync <ContentItem, ContentItemIndex>()
                              .Where(x =>
                                     x.ContentItemId == contentItemId &&
                                     x.Number == options.VersionNumber
                                     )
                              .FirstOrDefault();
            }
            else if (options.IsLatest)
            {
                contentItem = await _session
                              .QueryAsync <ContentItem, ContentItemIndex>()
                              .Where(x => x.ContentItemId == contentItemId && x.Latest == true)
                              .FirstOrDefault();
            }
            else if (options.IsDraft && !options.IsDraftRequired)
            {
                contentItem = await _session
                              .QueryAsync <ContentItem, ContentItemIndex>()
                              .Where(x =>
                                     x.ContentItemId == contentItemId &&
                                     x.Published == false &&
                                     x.Latest == true)
                              .FirstOrDefault();
            }
            else if (options.IsDraft || options.IsDraftRequired)
            {
                // Loaded whatever is the latest as it will be cloned
                contentItem = await _session
                              .QueryAsync <ContentItem, ContentItemIndex>()
                              .Where(x =>
                                     x.ContentItemId == contentItemId &&
                                     x.Latest == true)
                              .FirstOrDefault();
            }
            else if (options.IsPublished)
            {
                // If the published version is requested and is already loaded, we can
                // return it right away
                if (_contentManagerSession.RecallPublishedItemId(contentItemId, out contentItem))
                {
                    return(contentItem);
                }

                contentItem = await _session
                              .QueryAsync <ContentItem, ContentItemIndex>()
                              .Where(x => x.ContentItemId == contentItemId && x.Published == true)
                              .FirstOrDefault();
            }

            if (contentItem == null)
            {
                if (!options.IsDraftRequired)
                {
                    return(null);
                }
            }

            // Return item if obtained earlier in session
            // If IsPublished is required then the test has already been checked before
            ContentItem recalled = null;

            if (!_contentManagerSession.RecallVersionId(contentItem.Id, out recalled))
            {
                // store in session prior to loading to avoid some problems with simple circular dependencies
                _contentManagerSession.Store(contentItem);

                // create a context with a new instance to load
                var context = new LoadContentContext(contentItem);

                // invoke handlers to acquire state, or at least establish lazy loading callbacks
                Handlers.Invoke(handler => handler.Loading(context), _logger);
                Handlers.Reverse().Invoke(handler => handler.Loaded(context), _logger);

                contentItem = context.ContentItem;
            }
            else
            {
                contentItem = recalled;
            }

            if (options.IsDraftRequired)
            {
                // When draft is required and latest is published a new version is added
                if (contentItem.Published)
                {
                    // Save the previous version
                    _session.Save(contentItem);

                    contentItem = await BuildNewVersionAsync(contentItem);
                }

                // Save the new version
                _session.Save(contentItem);
            }

            return(contentItem);
        }
 public bool RecallVersionRecordId(int id, out ContentItem item)
 {
     return(_itemByVersionRecordId.TryGetValue(id, out item));
 }
 public bool RecallContentRecordId(int id, out ContentItem item)
 {
     return(_publishedItemsByContentRecordId.TryGetValue(id, out item));
 }
Example #36
0
 public virtual void Create(ContentItem contentItem)
 {
     Create(contentItem, VersionOptions.Published);
 }
 private bool InvalidForm(Orchard.ContentManagement.ContentItem form)
 {
     return(form == null || !form.Has(typeof(ContactFormPart)));
 }