Skip to content

Instantly share code, notes, and snippets.

@warrenbuckley
Created April 3, 2012 19:19
Show Gist options
  • Save warrenbuckley/2294862 to your computer and use it in GitHub Desktop.
Save warrenbuckley/2294862 to your computer and use it in GitHub Desktop.
Umbraco V5.1 Relate Member to Node with Relation - MVC Controller
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Framework;
using Umbraco.Cms.Web;
using Umbraco.Cms.Web.Context;
using Umbraco.Framework.Persistence.Model.Associations;
using Umbraco.Hive;
using Umbraco.Hive.RepositoryTypes;
namespace TestSite.V5.Web.Controllers
{
using Umbraco.Framework.Security.Model.Entities;
using System.Web.SessionState;
public class MyController : Controller
{
private readonly IUmbracoApplicationContext context;
public MyController(IUmbracoApplicationContext context)
{
this.context = context;
}
[HttpPost]
[Authorize()]
public JsonResult RelateMemberToNode(HiveId nodeID, HiveId memberID, string someValue)
{
//Get the member from the member ID
Member memberToRelate = context.Security.Members.GetById(memberID);
//Relation Type
var myRelationType = new RelationType("myRelationTypeAlias");
//flag for JSON
bool hasUpdated = false;
//Open a hive writer - so we can create the relation
using (var uow = context.Hive.OpenWriter<ISecurityStore>())
{
//Try and see if the relation already exists
var rel = uow.Repositories.GetChildRelations(memberToRelate.ProfileId, myRelationType).SingleOrDefault(x => x.DestinationId.Value == nodeID.Value);
//Some additional meta data we want to store with the relation
RelationMetaDatum someMeta = new RelationMetaDatum("someMeta", someValue);
//Check relation already exists - update the meta value
if (rel != null)
{
//Update the meta value on the relation
uow.Repositories.ChangeOrCreateRelationMetadata(memberToRelate.ProfileId, nodeID, myRelationType, someMeta);
//Update flag
hasUpdated = true;
}
else
{
//The relation does NOT exist - create it
//Add meta data to the existing relation
//Add a relation (Relate the node to the member)
uow.Repositories.AddRelation(memberToRelate.ProfileId, nodeID, myRelationType, someMeta);
//Update flag
hasUpdated = true;
}
//Say we are finished with the UOW/writer
uow.Complete();
}
//Return JSON - with a success message
return Json(new { updated = hasUpdated });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment