public ActionResult FeedPost(FeedPostModel model) { //check if user is logged in if (User.Identity.IsAuthenticated) { //check if the feed is okay if (String.IsNullOrEmpty(model.feedContent)) { return RedirectToCurrentUmbracoPage(); } //get the username of the poster int userId = _memberService.GetByUsername(User.Identity.Name).Id; //create a new content var feed = _contentService.CreateContent( "feed", 1084, "feed", userId); //store the value feed.SetValue("feedContent", model.feedContent); //published it and save with the content service _contentService.SaveAndPublishWithStatus(feed); //create a relationship between the posting user and the feed, and save it var relationType = _relationService.GetRelationTypeByAlias("feedToUser"); var nRelation = new Relation(feed.Id, userId, relationType); _relationService.Save(nRelation); } return RedirectToCurrentUmbracoPage(); }
public ActionResult CommentPost(CommentPostModel model) { if (User.Identity.IsAuthenticated) { if (String.IsNullOrEmpty(model.commentContent)) { return RedirectToCurrentUmbracoPage(); } if (model.feedToCommentOn == 0) { return RedirectToCurrentUmbracoPage(); } int userId = _memberService.GetByUsername(User.Identity.Name).Id; //add content var commentToStore = _contentService.CreateContent( "comment", model.feedToCommentOn, "comment", userId); commentToStore.SetValue("commentContent", model.commentContent); _contentService.SaveAndPublishWithStatus(commentToStore); //create the relation betwen the feed and the member var relationType = _relationService.GetRelationTypeByAlias("commentToMember"); var nRelation = new Relation(commentToStore.Id, userId, relationType); _relationService.Save(nRelation); } return RedirectToCurrentUmbracoPage(); }
/// <summary> /// Finds all published Content for this site and adds relations to Media /// </summary> private void AddMediaUsageForAllContent() { // RelationService IRelationService rs = ApplicationContext.Current.Services.RelationService; // RelationType IRelationType relationType = rs.GetRelationTypeByAlias(Constants.RelationTypeAlias); // Remove all existing relations if (rs.HasRelations(relationType)) { rs.DeleteRelationsOfType(relationType); } // Relate Media in all Published Documents foreach (var contentNodeId in FindAllContent()) { foreach (var mediaNodeId in FindMedia(contentNodeId)) { Relation relation = new Relation(mediaNodeId, contentNodeId, relationType); rs.Save(relation); LogHelper.Debug<MediaContentUsage>(String.Format("Saved relation: ParentId {0} ChildId {1}", relation.ParentId, relation.ChildId)); } } }
public static Relation MakeNew(int ParentId, int ChildId, RelationType RelType, string Comment) { var relation = new Umbraco.Core.Models.Relation(ParentId, ChildId, RelType.RelationTypeEntity) { Comment = Comment }; ApplicationContext.Current.Services.RelationService.Save(relation); return(new Relation(relation)); }
public void Can_Perform_Add_On_RelationRepository() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); var repositoryType = new RelationTypeRepository(unitOfWork); var repository = new RelationRepository(unitOfWork, NullCacheProvider.Current, repositoryType); // Act var relationType = repositoryType.Get(1); var relation = new Relation(1047, 1048, relationType); repository.AddOrUpdate(relation); unitOfWork.Commit(); // Assert Assert.That(relation, Is.Not.Null); Assert.That(relation.HasIdentity, Is.True); }
public void Can_Perform_Add_On_RelationRepository() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); RelationTypeRepository repositoryType; using (var repository = CreateRepository(unitOfWork, out repositoryType)) { // Act var relationType = repositoryType.Get(1); var relation = new Relation(NodeDto.NodeIdSeed + 2, NodeDto.NodeIdSeed + 3, relationType); repository.AddOrUpdate(relation); unitOfWork.Commit(); // Assert Assert.That(relation, Is.Not.Null); Assert.That(relation.HasIdentity, Is.True); } }
public void CreateTestData() { var relateContent = new RelationType(new Guid(Constants.ObjectTypes.Document), new Guid("C66BA18E-EAF3-4CFF-8A22-41B16D66A972"), "relateContentOnCopy") { IsBidirectional = true, Name = "Relate Content on Copy" }; var relateContentType = new RelationType(new Guid(Constants.ObjectTypes.DocumentType), new Guid("A2CB7800-F571-4787-9638-BC48539A0EFB"), "relateContentTypeOnCopy") { IsBidirectional = true, Name = "Relate ContentType on Copy" }; var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); var relationTypeRepository = new RelationTypeRepository(unitOfWork); var relationRepository = new RelationRepository(unitOfWork, NullCacheProvider.Current, relationTypeRepository); relationTypeRepository.AddOrUpdate(relateContent); relationTypeRepository.AddOrUpdate(relateContentType); unitOfWork.Commit(); //Create and Save ContentType "umbTextpage" -> 1045 ContentType contentType = MockedContentTypes.CreateSimpleContentType("umbTextpage", "Textpage"); ServiceContext.ContentTypeService.Save(contentType); //Create and Save Content "Homepage" based on "umbTextpage" -> 1046 Content textpage = MockedContent.CreateSimpleContent(contentType); ServiceContext.ContentService.Save(textpage, 0); //Create and Save Content "Text Page 1" based on "umbTextpage" -> 1047 Content subpage = MockedContent.CreateSimpleContent(contentType, "Text Page 1", textpage.Id); ServiceContext.ContentService.Save(subpage, 0); //Create and Save Content "Text Page 1" based on "umbTextpage" -> 1048 Content subpage2 = MockedContent.CreateSimpleContent(contentType, "Text Page 2", textpage.Id); ServiceContext.ContentService.Save(subpage2, 0); var relation = new Relation(textpage.Id, subpage.Id, relateContent) { Comment = string.Empty }; var relation2 = new Relation(textpage.Id, subpage2.Id, relateContent) { Comment = string.Empty }; relationRepository.AddOrUpdate(relation); relationRepository.AddOrUpdate(relation2); unitOfWork.Commit(); }
/// <summary> /// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current /// to the new copy which is returned. /// </summary> /// <param name="content">The <see cref="IContent"/> to copy</param> /// <param name="parentId">Id of the Content's new Parent</param> /// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param> /// <param name="userId">Optional Id of the User copying the Content</param> /// <returns>The newly created <see cref="IContent"/> object</returns> public IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0) { using (new WriteLock(Locker)) { var copy = ((Content)content).Clone(); copy.ParentId = parentId; // A copy should never be set to published automatically even if the original was. copy.ChangePublishedState(PublishedState.Unpublished); if (Copying.IsRaisedEventCancelled(new CopyEventArgs<IContent>(content, copy, parentId), this)) return null; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateContentRepository(uow)) { // Update the create author and last edit author copy.CreatorId = userId; copy.WriterId = userId; repository.AddOrUpdate(copy); uow.Commit(); //Special case for the Upload DataType var uploadDataTypeId = new Guid(Constants.PropertyEditors.UploadField); if (content.Properties.Any(x => x.PropertyType.DataTypeId == uploadDataTypeId)) { bool isUpdated = false; var fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>(); //Loop through properties to check if the content contains media that should be deleted foreach (var property in content.Properties.Where(x => x.PropertyType.DataTypeId == uploadDataTypeId && string.IsNullOrEmpty(x.Value.ToString()) == false)) { if (fs.FileExists(IOHelper.MapPath(property.Value.ToString()))) { var currentPath = fs.GetRelativePath(property.Value.ToString()); var propertyId = copy.Properties.First(x => x.Alias == property.Alias).Id; var newPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(currentPath)); fs.CopyFile(currentPath, newPath); copy.SetValue(property.Alias, fs.GetUrl(newPath)); //Copy thumbnails foreach (var thumbPath in fs.GetThumbnails(currentPath)) { var newThumbPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(thumbPath)); fs.CopyFile(thumbPath, newThumbPath); } isUpdated = true; } } if (isUpdated) { repository.AddOrUpdate(copy); uow.Commit(); } } //Special case for the Tags DataType var tagsDataTypeId = new Guid(Constants.PropertyEditors.Tags); if (content.Properties.Any(x => x.PropertyType.DataTypeId == tagsDataTypeId)) { var tags = uow.Database.Fetch<TagRelationshipDto>("WHERE nodeId = @Id", new { Id = content.Id }); foreach (var tag in tags) { uow.Database.Insert(new TagRelationshipDto { NodeId = copy.Id, TagId = tag.TagId }); } } } //NOTE This 'Relation' part should eventually be delegated to a RelationService if (relateToOriginal) { RelationType relationType = null; using (var relationTypeRepository = _repositoryFactory.CreateRelationTypeRepository(uow)) { relationType = relationTypeRepository.Get(1); } using (var relationRepository = _repositoryFactory.CreateRelationRepository(uow)) { var relation = new Relation(content.Id, copy.Id, relationType); relationRepository.AddOrUpdate(relation); uow.Commit(); } Audit.Add(AuditTypes.Copy, string.Format("Copied content with Id: '{0}' related to original content with Id: '{1}'", copy.Id, content.Id), copy.WriterId, copy.Id); } //Look for children and copy those as well var children = GetChildren(content.Id); foreach (var child in children) { Copy(child, copy.Id, relateToOriginal, userId); } Copied.RaiseEvent(new CopyEventArgs<IContent>(content, copy, false, parentId), this); Audit.Add(AuditTypes.Copy, "Copy Content performed by user", content.WriterId, content.Id); //TODO: Don't think we need this here because cache should be cleared by the event listeners // and the correct ICacheRefreshers!? RuntimeCacheProvider.Current.Clear(); return copy; } }
/// <summary> /// Deletes a <see cref="Relation"/> /// </summary> /// <param name="relation">Relation to Delete</param> public void Delete(Relation relation) { var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateRelationRepository(uow)) { repository.Delete(relation); uow.Commit(); } }
/// <summary> /// Relates two objects that are based on the <see cref="IUmbracoEntity"/> interface. /// </summary> /// <param name="parent">Parent entity</param> /// <param name="child">Child entity</param> /// <param name="relationTypeAlias">Alias of the type of relation to create</param> /// <returns>The created <see cref="Relation"/></returns> public Relation Relate(IUmbracoEntity parent, IUmbracoEntity child, string relationTypeAlias) { var relationType = GetRelationTypeByAlias(relationTypeAlias); if(relationType == null || string.IsNullOrEmpty(relationType.Alias)) throw new ArgumentNullException(string.Format("No RelationType with Alias '{0}' exists.", relationTypeAlias)); var relation = new Relation(parent.Id, child.Id, relationType); var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateRelationRepository(uow)) { repository.AddOrUpdate(relation); uow.Commit(); return relation; } }
/// <summary> /// Gets the Parent and Child objects from a Relation as a <see cref="Tuple"/>"/> with <see cref="IUmbracoEntity"/>. /// </summary> /// <param name="relation">Relation to retrieve parent and child object from</param> /// <param name="loadBaseType">Optional bool to load the complete object graph when set to <c>False</c></param> /// <returns>Returns a Tuple with Parent (item1) and Child (item2)</returns> public Tuple<IUmbracoEntity, IUmbracoEntity> GetEntitiesFromRelation(Relation relation, bool loadBaseType = false) { var childObjectType = UmbracoObjectTypesExtensions.GetUmbracoObjectType(relation.RelationType.ChildObjectType); var parentObjectType = UmbracoObjectTypesExtensions.GetUmbracoObjectType(relation.RelationType.ParentObjectType); var child = _entityService.Get(relation.ChildId, childObjectType, loadBaseType); var parent = _entityService.Get(relation.ParentId, parentObjectType, loadBaseType); return new Tuple<IUmbracoEntity, IUmbracoEntity>(parent, child); }
/// <summary> /// Gets the Parent object from a Relation as an <see cref="IUmbracoEntity"/> /// </summary> /// <param name="relation">Relation to retrieve parent object from</param> /// <param name="loadBaseType">Optional bool to load the complete object graph when set to <c>False</c></param> /// <returns>An <see cref="IUmbracoEntity"/></returns> public IUmbracoEntity GetParentEntityFromRelation(Relation relation, bool loadBaseType = false) { var objectType = UmbracoObjectTypesExtensions.GetUmbracoObjectType(relation.RelationType.ParentObjectType); return _entityService.Get(relation.ParentId, objectType, loadBaseType); }
/// <summary> /// /// </summary> /// <param name="contextId">the id of the content, media or member item</param> /// <param name="propertyAlias">the property alias of the picker using relation mapping</param> /// <param name="relationTypeAlias">the alias of the relation type to use</param> /// <param name="relationsOnly"></param> /// <param name="pickedIds">the ids of all picked items that are to be related to the contextId</param> internal static void UpdateRelationMapping(int contextId, string propertyAlias, string relationTypeAlias, bool relationsOnly, int[] pickedIds) { IRelationType relationType = ApplicationContext.Current.Services.RelationService.GetRelationTypeByAlias(relationTypeAlias); if (relationType != null) { // get all relations of this type List<IRelation> relations = ApplicationContext.Current.Services.RelationService.GetAllRelationsByRelationType(relationType.Id).ToList(); // construct object used to identify a relation (this is serialized into the relation comment field) RelationMappingComment relationMappingComment = new RelationMappingComment(contextId, propertyAlias); // filter down potential relations, by relation type direction if (relationType.IsBidirectional && relationsOnly) { relations = relations.Where(x => x.ChildId == contextId || x.ParentId == contextId).ToList(); relations = relations.Where(x => new RelationMappingComment(x.Comment).DataTypeDefinitionId == relationMappingComment.DataTypeDefinitionId).ToList(); } else { relations = relations.Where(x => x.ChildId == contextId).ToList(); relations = relations.Where(x => new RelationMappingComment(x.Comment).PropertyTypeId == relationMappingComment.PropertyTypeId).ToList(); if (relationMappingComment.IsInArchetype()) { relations = relations.Where(x => new RelationMappingComment(x.Comment).MatchesArchetypeProperty(relationMappingComment.PropertyAlias)).ToList(); } } // check current context is of the correct object type (as according to the relation type) if (ApplicationContext.Current.Services.EntityService.GetObjectType(contextId) == UmbracoObjectTypesExtensions.GetUmbracoObjectType(relationType.ChildObjectType)) { // for each picked item foreach (int pickedId in pickedIds) { // check picked item context if of the correct object type (as according to the relation type) if (ApplicationContext.Current.Services.EntityService.GetObjectType(pickedId) == UmbracoObjectTypesExtensions.GetUmbracoObjectType(relationType.ParentObjectType)) { // if relation doesn't already exist (new picked item) if (!relations.Exists(x => x.ParentId == pickedId)) { // create relation Relation relation = new Relation(pickedId, contextId, relationType); relation.Comment = relationMappingComment.GetComment(); ApplicationContext.Current.Services.RelationService.Save(relation); } // housekeeping - remove 'the' relation from the list being processed (there should be only one) relations.RemoveAll(x => x.ChildId == contextId && x.ParentId == pickedId && x.RelationTypeId == relationType.Id); } } } // delete relations for any items left on the list being processed if (relations.Any()) { foreach (IRelation relation in relations) { ApplicationContext.Current.Services.RelationService.Delete(relation); } } } }
/// <summary> /// Store the profilepicture has media and createa a relationship between the user and the picture /// </summary> /// <param name="userName">UserName of the user to store the profile picture to</param> /// <param name="file">HttpPostedFileBase of the profile picture</param> public void StoreProfilePicure(string userName, HttpPostedFileBase file) { //lets store the media var memberToStore = _memberService.GetByUsername(userName); //create the media item var profileImageMediaToSTore = _mediaService.CreateMedia(memberToStore.Name, 1132, "Image"); //save it to create a medi aId _mediaService.Save(profileImageMediaToSTore); //let umbraco take care of the file profileImageMediaToSTore.SetValue("umbracoFile", file); //save the whole thing _mediaService.Save(profileImageMediaToSTore); //meow we need to create the relation between the member and his profile picture var relationType = _relationService.GetRelationTypeByAlias("memberToProfileImage"); var nRelation = new Relation(memberToStore.Id, profileImageMediaToSTore.Id, relationType); _relationService.Save(nRelation); }
public ActionResult OptIn(int id) { try { var rs = Services.RelationService; //rs.Relate(Member.GetCurrentMember(), , "UMF_EmailNotification"); var relation = new Relation(Member.GetCurrentMember().Id, id, rs.GetRelationTypeByAlias("UMF_EmailNotification")); rs.Save(relation); return RedirectToCurrentUmbracoPage(); } catch { return RedirectToCurrentUmbracoPage(); } }
/// <summary> /// Adds relation between Content and Media when Content is published /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ContentService_Published(IPublishingStrategy sender, PublishEventArgs<IContent> e) { // RelationService IRelationService rs = ApplicationContext.Current.Services.RelationService; // ContentService IContentService cs = ApplicationContext.Current.Services.ContentService; // RelationType IRelationType relationType = rs.GetRelationTypeByAlias(Constants.RelationTypeAlias); // Published Documents foreach (var contentNode in e.PublishedEntities) { // Content is child, query by child and RelationType var relations = rs.GetByChild(cs.GetById(contentNode.Id), Constants.RelationTypeAlias); // Remove current relations if (relations.Count() > 0) { LogHelper.Info<MediaContentUsage>(String.Format("Removing all Media relations for published Content with id '{0}'", contentNode.Id)); foreach (var relation in relations) { rs.Delete(relation); LogHelper.Debug<MediaContentUsage>(String.Format("Deleted relation: ParentId {0} ChildId {1}", relation.ParentId, relation.ChildId)); } } // Relate found Media to this Content foreach (var mediaNodeId in FindMedia(contentNode.Id)) { Relation relation = new Relation(mediaNodeId, contentNode.Id, relationType); rs.Save(relation); LogHelper.Debug<MediaContentUsage>(String.Format("Saved relation: ParentId {0} ChildId {1}", relation.ParentId, relation.ChildId)); } } }
/// <summary> /// Relates two objects that are based on the <see cref="IUmbracoEntity"/> interface. /// </summary> /// <param name="parent">Parent entity</param> /// <param name="child">Child entity</param> /// <param name="relationType">The type of relation to create</param> /// <returns>The created <see cref="Relation"/></returns> public Relation Relate(IUmbracoEntity parent, IUmbracoEntity child, RelationType relationType) { //Ensure that the RelationType has an indentity before using it to relate two entities if(relationType.HasIdentity == false) Save(relationType); var relation = new Relation(parent.Id, child.Id, relationType); var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateRelationRepository(uow)) { repository.AddOrUpdate(relation); uow.Commit(); return relation; } }