/// <summary>
        ///  Deserialize the relations for a relation type.
        /// </summary>
        private IEnumerable <uSyncChange> DeserializeRelations(XElement node, IRelationType relationType, SyncSerializerOptions options)
        {
            var changes = new List <uSyncChange>();

            var existing = relationService
                           .GetAllRelationsByRelationType(relationType.Id)
                           .ToList();

            var relations = node.Element("Relations");

            // do we do this, or do we remove them all!
            if (relations == null)
            {
                return(Enumerable.Empty <uSyncChange>());
            }

            var newRelations = new List <string>();

            foreach (var relationNode in relations.Elements("Relation"))
            {
                var parentKey = relationNode.Element("Parent").ValueOrDefault(Guid.Empty);
                var childKey  = relationNode.Element("Child").ValueOrDefault(Guid.Empty);

                if (parentKey == Guid.Empty || childKey == Guid.Empty)
                {
                    continue;
                }

                var parentItem = entityService.Get(parentKey);
                var childItem  = entityService.Get(childKey);

                if (parentItem == null || childItem == null)
                {
                    continue;
                }

                if (!existing.Any(x => x.ParentId == parentItem.Id && x.ChildId == childItem.Id))
                {
                    // missing from the current list... add it.
                    relationService.Save(new Relation(parentItem.Id, childItem.Id, relationType));
                    changes.Add(uSyncChange.Create(relationType.Alias, parentItem.Name, childItem.Name));
                }

                newRelations.Add($"{parentItem.Id}_{childItem.Id}");
            }


            if (options.DeleteItems())
            {
                var obsolete = existing.Where(x => !newRelations.Contains($"{x.ParentId}_{x.ChildId}"));

                foreach (var obsoleteRelation in obsolete)
                {
                    changes.Add(uSyncChange.Delete(relationType.Alias, obsoleteRelation.ParentId.ToString(), obsoleteRelation.ChildId.ToString()));
                    relationService.Delete(obsoleteRelation);
                }
            }

            return(changes);
        }
        public void Handle(ContentCopiedNotification notification)
        {
            if (notification.RelateToOriginal == false)
            {
                return;
            }

            var relationType = _relationService.GetRelationTypeByAlias(Constants.Conventions.RelationTypes.RelateDocumentOnCopyAlias);

            if (relationType == null)
            {
                relationType = new RelationType(Constants.Conventions.RelationTypes.RelateDocumentOnCopyAlias,
                                                Constants.Conventions.RelationTypes.RelateDocumentOnCopyName,
                                                true,
                                                Constants.ObjectTypes.Document,
                                                Constants.ObjectTypes.Document,
                                                false);

                _relationService.Save(relationType);
            }

            var relation = new Relation(notification.Original.Id, notification.Copy.Id, relationType);

            _relationService.Save(relation);

            _auditService.Add(
                AuditType.Copy,
                notification.Copy.WriterId,
                notification.Copy.Id, ObjectTypes.GetName(UmbracoObjectTypes.Document),
                $"Copied content with Id: '{notification.Copy.Id}' related to original content with Id: '{notification.Original.Id}'");
        }
Exemple #3
0
        public ActionResult Create(RelationViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    service.Insert(model);
                    service.Save();
                    return(RedirectToAction("Index"));
                }
                var employees = employeeService.GetEmployeeSelectListItems().Select(x => new {
                    Id   = x.Id,
                    Name = x.LastName + " - " + x.FirstName
                }).ToList();
                ViewBag.Employees = new SelectList(employees, "Id", "Name");

                var employees1 = employeeService.GetEmployeeSelectListItems1().Select(x => new {
                    Id   = x.Id,
                    Name = x.LastName + " - " + x.FirstName
                }).ToList();
                ViewBag.Employees1 = new SelectList(employees, "Id", "Name");
                return(View(model));
            }
            catch
            {
                return(View());
            }
        }
        /// <summary>
        /// Creates a bunch of content/media items return relation objects for them (unsaved)
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private IEnumerable <IRelation> CreateRelations(int count)
        {
            IRelationService rs     = RelationService;
            string           rtName = Guid.NewGuid().ToString();
            var rt = new RelationType(rtName, rtName, false, null, null);

            rs.Save(rt);

            ContentType ct = ContentTypeBuilder.CreateBasicContentType();

            ContentTypeService.Save(ct);

            MediaType mt = MediaTypeBuilder.CreateImageMediaType("img");

            MediaTypeService.Save(mt);

            return(Enumerable.Range(1, count).Select(index =>
            {
                Content c1 = ContentBuilder.CreateBasicContent(ct);
                Media c2 = MediaBuilder.CreateMediaImage(mt, -1);
                ContentService.Save(c1);
                MediaService.Save(c2);

                return new Relation(c1.Id, c2.Id, rt);
            }).ToList());
        }
        private IRelation CreateAndSaveRelation(string name, string alias)
        {
            IRelationService rs = RelationService;
            var rt = new RelationType(name, alias, false, null, null);

            rs.Save(rt);

            ContentType ct = ContentTypeBuilder.CreateBasicContentType();

            ContentTypeService.Save(ct);

            MediaType mt = MediaTypeBuilder.CreateImageMediaType("img");

            MediaTypeService.Save(mt);

            Content c1 = ContentBuilder.CreateBasicContent(ct);
            Media   c2 = MediaBuilder.CreateMediaImage(mt, -1);

            ContentService.Save(c1);
            MediaService.Save(c2);

            var r = new Relation(c1.Id, c2.Id, rt);

            RelationService.Save(r);

            return(r);
        }
    public void Handle(ContentMovedToRecycleBinNotification notification)
    {
        using (IScope scope = _scopeProvider.CreateScope())
        {
            const string  relationTypeAlias = Constants.Conventions.RelationTypes.RelateParentDocumentOnDeleteAlias;
            IRelationType?relationType      = _relationService.GetRelationTypeByAlias(relationTypeAlias);

            // check that the relation-type exists, if not, then recreate it
            if (relationType == null)
            {
                Guid         documentObjectType = Constants.ObjectTypes.Document;
                const string relationTypeName   = Constants.Conventions.RelationTypes.RelateParentDocumentOnDeleteName;

                relationType = new RelationType(relationTypeName, relationTypeAlias, false, documentObjectType, documentObjectType, false);
                _relationService.Save(relationType);
            }

            foreach (MoveEventInfo <IContent> item in notification.MoveInfoCollection)
            {
                IList <string> originalPath     = item.OriginalPath.ToDelimitedList();
                var            originalParentId = originalPath.Count > 2
                    ? int.Parse(originalPath[originalPath.Count - 2], CultureInfo.InvariantCulture)
                    : Constants.System.Root;

                // before we can create this relation, we need to ensure that the original parent still exists which
                // may not be the case if the encompassing transaction also deleted it when this item was moved to the bin
                if (_entityService.Exists(originalParentId))
                {
                    // Add a relation for the item being deleted, so that we can know the original parent for if we need to restore later
                    IRelation relation =
                        _relationService.GetByParentAndChildId(originalParentId, item.Entity.Id, relationType) ??
                        new Relation(originalParentId, item.Entity.Id, relationType);
                    _relationService.Save(relation);

                    _auditService.Add(
                        AuditType.Delete,
                        item.Entity.WriterId,
                        item.Entity.Id,
                        UmbracoObjectTypes.Document.GetName(),
                        string.Format(_textService.Localize("recycleBin", "contentTrashed"), item.Entity.Id, originalParentId));
                }
            }

            scope.Complete();
        }
    }
        public void Lock(int pageId, string ownerUsername)
        {
            Unlock(pageId);

            var relation = new Relation(pageId, pageId, _contentGuardRelationType)
            {
                Comment = ownerUsername
            };

            _relationService.Save(relation);
        }
        /// <summary>
        /// Creates a new relation type.
        /// </summary>
        /// <param name="relationType">The relation type to create.</param>
        /// <returns>A <see cref="HttpResponseMessage"/> containing the persisted relation type's ID.</returns>
        public ActionResult <int> PostCreate(RelationTypeSave relationType)
        {
            var relationTypePersisted = new RelationType(
                relationType.Name,
                relationType.Name.ToSafeAlias(_shortStringHelper, true),
                relationType.IsBidirectional,
                relationType.ParentObjectType,
                relationType.ChildObjectType);

            try
            {
                _relationService.Save(relationTypePersisted);

                return(relationTypePersisted.Id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating relation type with {Name}", relationType.Name);
                return(ValidationProblem("Error creating relation type."));
            }
        }
        public void Create_Relation_Type_Without_Object_Types()
        {
            IRelationService rs = RelationService;
            IRelationType    rt = new RelationType("repeatedEventOccurence", "repeatedEventOccurence", false, null, null);

            Assert.DoesNotThrow(() => rs.Save(rt));

            // re-get
            rt = RelationService.GetRelationTypeById(rt.Id);

            Assert.IsNull(rt.ChildObjectType);
            Assert.IsNull(rt.ParentObjectType);
        }
        public void Can_Create_RelationType_Without_Name()
        {
            IRelationService rs = RelationService;
            IRelationType    rt = new RelationType("Test", "repeatedEventOccurence", false, Constants.ObjectTypes.Document, Constants.ObjectTypes.Media);

            Assert.DoesNotThrow(() => rs.Save(rt));

            // re-get
            rt = RelationService.GetRelationTypeById(rt.Id);

            Assert.AreEqual("Test", rt.Name);
            Assert.AreEqual("repeatedEventOccurence", rt.Alias);
            Assert.AreEqual(false, rt.IsBidirectional);
            Assert.AreEqual(Constants.ObjectTypes.Document, rt.ParentObjectType.Value);
            Assert.AreEqual(Constants.ObjectTypes.Media, rt.ChildObjectType.Value);
        }
        public override void Migrate()
        {
            Logger.Debug <AddContentGuardRelationType>("Running migration {MigrationStep}", "AddContentGuardRelationType");

            var contentGuardRelationType = _relationService.GetRelationTypeByAlias("contentguard");

            if (contentGuardRelationType != null)
            {
                return;
            }

            // Insert custom relation type to Umbraco DB
            contentGuardRelationType =
                new RelationType("Relate (Lock) the Document with the Owner", "contentguard", true, null, null);

            _relationService.Save(contentGuardRelationType);
        }
Exemple #12
0
 private void saveRelations(IRelation relation)
 {
     try
     {
         if (relation.ChildId != 0)
         {
             relationService.Save(relation);
         }
         else
         {
             Current.Logger.Info(this.GetType(), string.Format("Skipping creation of relation between parent: {0} and child: {1} because child ID is 0. Property in comment: {2} ", relation.ParentId, relation.ChildId, relation.Comment));
         }
     }
     catch (Exception msg)
     {
         Current.Logger.Error(this.GetType(), string.Format("Exception while creating relation between parent: {0} and child: {1}. Property in comment: {2} ", relation.ParentId, relation.ChildId, relation.Comment), msg);
     }
 }
        private static void ContentService_Saved(IContentService contentService, ContentSavedEventArgs e)
        {
            foreach (IContent content in e.SavedEntities)
            {
                List <string> editors = new List <string>
                {
                    Umbraco.Core.Constants.PropertyEditors.Aliases.Grid,
                    BentoItemDataEditor.EditorAlias,
                    BentoStackDataEditor.EditorAlias
                };

                foreach (Property contentProperty in content.Properties.Where(x => editors.Contains(x.PropertyType.PropertyEditorAlias)))
                {
                    IDataType editor = DataTypeService.GetDataType(contentProperty.PropertyType.DataTypeId);

                    IRelationType bentoBlocksRelationType = RelationService.GetRelationTypeByAlias(RelationTypes.BentoItemsAlias);

                    if (bentoBlocksRelationType == null)
                    {
                        RelationType relationType = new RelationType(
                            RelationTypes.BentoItemsAlias,
                            RelationTypes.BentoItemsName,
                            true,
                            UmbracoObjectTypes.Document.GetGuid(),
                            UmbracoObjectTypes.Document.GetGuid());

                        RelationService.Save(relationType);

                        bentoBlocksRelationType = RelationService.GetRelationTypeByAlias(RelationTypes.BentoItemsAlias);
                    }

                    //todo: this does work but it's a bit brute force...
                    //i guess we could store the current relationships and then store the ones we're creating and compare them and then
                    //delete the ones from the old list that arent in the new list? but that's a lot of db hits...
                    IEnumerable <IRelation> rels = RelationService.GetByParentId(content.Id);
                    foreach (IRelation currentRelation in rels.Where(x => x.RelationType.Id == bentoBlocksRelationType.Id))
                    {
                        RelationService.Delete(currentRelation);
                    }

                    if (contentProperty.PropertyType.PropertyEditorAlias == BentoItemDataEditor.EditorAlias)
                    {
                        foreach (Property.PropertyValue value in contentProperty.Values)
                        {
                            if (value.PublishedValue == null)
                            {
                                break;
                            }

                            var area = JsonConvert.DeserializeObject <Area>(value.PublishedValue.ToString());

                            if (area.Id <= 0)
                            {
                                continue;
                            }

                            var bentoContent = contentService.GetById(area.Id);

                            if (bentoContent == null)
                            {
                                continue;
                            }

                            BentoItemConfiguration config = (BentoItemConfiguration)editor.Configuration;

                            ProcessRelationship(contentService, bentoContent, content, bentoBlocksRelationType, config.ItemDoctypeCompositionAlias);
                        }
                    }
                    else
                    {
                        foreach (Property.PropertyValue value in contentProperty.Values)
                        {
                            if (value.PublishedValue == null)
                            {
                                break;
                            }

                            string valueString = value.PublishedValue?.ToString();

                            if (string.IsNullOrWhiteSpace(valueString))
                            {
                                continue;
                            }

                            IEnumerable <StackItem> items = JsonConvert.DeserializeObject <IEnumerable <StackItem> >(valueString, new StackItemConverter());

                            var itemList = items.Where(x => x.Areas != null && x.Areas.Any())
                                           .SelectMany(stackItem => stackItem.Areas.Where(x => x.Id > 0), (stackItem, x) => contentService.GetById(x.Id))
                                           .Where(bentoContent => bentoContent != null)
                                           .Distinct();

                            BentoStackConfiguration config = (BentoStackConfiguration)editor.Configuration;

                            foreach (IContent item in itemList)
                            {
                                ProcessRelationship(contentService, item, content, bentoBlocksRelationType, config.ItemDoctypeCompositionAlias);
                            }
                        }
                    }
                }
            }
        }