Umbraco 8 Cheat Sheet

 

Below you will find our scrappy, unchecked, random, but incredibly useful Umbraco 8 cheat sheet. I use this everyday I work on Umbraco. Some of the obscurities of Umbraco drive me nuts and time spent working those out is what I like to record below.

ADD SITE SEARCH IN 15 MNIUTES

New: I am excited to announce the launch of USiteSearch on github and as a nuget package. You can see how it works in this video.

CONTEXT

var helper = Umbraco.Web.Composing.Current.UmbracoHelper

QUERYING

var helper = Umbraco.Web.Composing.Current.UmbracoHelper;

Query By Route
public MyController(UmbracoContext context) : base() { _context = context; }
IPublishedContent content = _context.Content.GetByRoute("/products/big");


Query By Document Type
IPublishedContent allContentOfType = helper.ContentAtXPath("//menuItem")
.SingleOrDefault(c => c.Value<IPublishedContent>("page") != null && c.Value<IPublishedContent>("page").Id == currentId);

Search for a Property Values
//tag search
var newsListing1 = Umbraco.Content(1064).Children.Where(c => c.Value<IEnumerable<string>>("tags").Contains("Energy policy")).ToList();
//dropdownlist search
var vicNews = Umbraco.Content(1064).Children.Where(s => s.Value<string>("state") == "VIC").ToList();

 //IPublishedContent search in normal Content (won’t work in Members)
var invoices = Umbraco.Content(PURCHASES_PARENT)
.Children.Where(s => s.Value<IPublishedContent>("member").Id == userId).ToList();

//IPublishedContent search in Members where content is Content Picker
var memberService = Current.Services.MemberService;
var results = memberService.GetAllMembers().Where(m => m.GetValue("organisation") != null && m.GetValue("organisation").ToString() == udi.ToString());

//IPublishedContent search in Members where content is Multi Content Picker
var memberService = Current.Services.MemberService;
var results = memberService.GetAllMembers().Where(m => m.GetValue("organisation") != null && m.GetValue("organisation").ToString().Contains(udi.ToString()));

Tags DataType
var newsTags = Umbraco.TagQuery.GetAllContentTags("news");//get all tags by tag group name

IPublishedContent

IPublishedContent content = UmbracoHelper.Content(1123);
var image = content.Value<IPublishedContent>("image");
if(image != null){
  var url = image.Url;
}

Direct Content Access
var tag = Umbraco.Content(1357).Name;

Get Guid
IPublishedContent c = _Helper.Content(id);

string guid = c.Key.ToString();

 

MEMBERSHIP

MembershipHelper

In a view – Members

MemershipHelper Injection

public MyRenderMVCController(MembershipHelper membershipHelper)
{
  _MembershipHelper = membershipHelper;
}

Insert Member

bool success = false;
var member = Services.MemberService.CreateMemberWithIdentity(register.Email, register.Email, register.Name, "Member");
Services.MemberService.Save(member);
Services.MemberService.SavePassword(member, register.Password);
Services.MemberService.AssignRole(member.Id, "General");
member.SetValue("company", register.Company);
member.SetValue("address", register.Address);|
member.SetValue("phone", register.Phone);
Services.MemberService.Save(member);

Update Member

var member = _helper.GetCurrentMember(); //_helper is a MembershipHelper
var imember = Services.MemberService.GetById(member.Id);
string email = imember.Email;
imember.Name = model.Name;
imember.SetValue("company", model.Company);
imember.SetValue("address", model.Address);
imember.SetValue("phone", model.Phone);
Services.MemberService.Save(imember);

Member Insert Value For a Dropdownlist
private void SetDropDownListValue(IMember content, int dropDownListDataTypeId, string propertyName, string prevalue)
{
  var DataTypeService = Services.DataTypeService;
 
var dropdown = DataTypeService.GetAll().First(x => x.Id == dropDownListDataTypeId);
  IDataType dataType = DataTypeService.GetDataType(dropdown.Id);
  ValueListConfiguration valueList = (ValueListConfiguration)dataType.Configuration;
  ValueListItem item = valueList.Items.SingleOrDefault(i => i.Value == prevalue);

  if (item != null)
  {
    content.SetValue(propertyName, "['" + item.Value + "']");
  }
}

Get Role (Group) of Member
var id = Members.GetCurrentMemberId();
IPublishedContent content = Umbraco.MembershipHelper.GetById(id);
string email = content.Value<string>("email");
string [] roles = Roles.GetRolesForUser(email);

Try also [UmbracoAuthorize(Roles = "admin")]

Or

var rolesList = System.Web.Security.Roles.GetRolesForUser(member.Username);

foreach (var roles in rolesList)

{

  role.ToString()

}

 

Get a member property

IMember member;
member.Properties[5].GetValue(); //may be forced into this syntax which gets a Udi


Assign a Role (Group)

_ServiceContext.MemberService.AssignRole(member.Id, role);


EXAMINE

And/or search

var textFields = new[] { "header", "bodyText" };
var results = searcher.CreateQuery("content").ParentId(parentId).And().GroupedOr(textFields, searchQuery).Execute();

var results = searcher.CreateQuery().NativeQuery("+__IndexType:content +nodeName:" + searchTerm).Execute();

var results = searcher.CreateQuery().NativeQuery("+__IndexType:content +__NodeTypeAlias:sectionParagraph (+nodeName:pps* ) || (+items:pps* )").Execute();

 

INSERTING

IContentService contentService = Services.ContentService;

Dependency Injection

// works for IComponent
public MyClass(IContentService contentService)
{

  _contentService = contentService;
}

 

Insert Content
var content = _ContentService.Create(news.pageName, NEWS_PARENT, NEWS);
content.SetValue("heading", news.pageTitle);
content.SetValue("body", Clean(news.articleContent));
_ContentService.SaveAndPublish(content);

 

Insert Content with Content Picker

private void Insert(News news)
{
  var content = _ContentService.Create(“content name”, NEWS_PARENT, NEWS);
  content.SetValue("heading", “News Article Title”);
  _ContentService.SaveAndPublish(content);
 

  IContent author = AddAuthor(“author”);//create another IContent
  var locaUdi = Udi.Create(Constants.UdiEntityType.Document, author.Key);
  content.SetValue("author", locaUdi);
  _ContentService.SaveAndPublish(content);
}

 

Insert Media

private IMedia CreateMedia(string imagePathHardDrive, string contentName, int folderId)
{

  FileStream stream = new FileStream(imagePathHardDrive, FileMode.Open);
  string filename = Path.GetFileNameWithoutExtension(imagePathHardDrive);
  var media = _MediaService.CreateMediaWithIdentity(filename, folderId, MediaType(imagePathHardDrive));
  media.SetValue("umbracoFile", stream);
  media.SetValue(_ContentTypeBaseServiceProvider, "umbracoFile", Path.GetFileName(imagePathHardDrive), stream);
  _MediaService.Save(media);
  stream.Close();

  return media;
}

 

Insert Media Then Add To Content As Media Picker

protected void AddMedia(string image, IContent content, int mediaFolder, string propertyName)
{
  IMedia media = CreateMedia (imageFile, mediaFolder);
  content.SetValue(propertyName, media.GetUdi());
  _ContentService.SaveAndPublish(content);
}

 

Insert Value For a Dropdownlist
private void SetDropDownListValue(IContent content, int dropDownListDataTypeId, string propertyName, string prevalue)
{
  var DataTypeService = Services.DataTypeService;
 
var dropdown = DataTypeService.GetAll().First(x => x.Id == dropDownListDataTypeId);
  IDataType dataType = DataTypeService.GetDataType(dropdown.Id);
  ValueListConfiguration valueList = (ValueListConfiguration)dataType.Configuration;
  ValueListItem item = valueList.Items.SingleOrDefault(i => i.Value == prevalue);

  if (item != null)
  {
    content.SetValue(propertyName, "['" + item.Value + "']");
  }
}

 

Delete Content
IPublishedContent parent = _helper.Content(NEWS_PARENT);
foreach (IPublishedContent content in parent.Children)
{
  IContent icontent = _ContentService.GetById(content.Id);
  PublishResult result1 = _ContentService.Unpublish(icontent);
  result = _ContentService.Delete(icontent);
}

 

Insert Multi-Node TreePicker
private void SaveMemberGroups(ref IMember member)
{  
  //insert comma delimited list of content Guid without '-' in Guid
 
member.SetValue("groups", "umb://document/a0bcab4501494cc1a5ac2dc732ea1406,umb://document/015e5f77b1c946ec895b9d8a5885a0bb");

 

MEMBERSHIP

Current.Logger.Info(typeof(MemberSavedComponent), $"Saving role for {member.Id}");

 

  

MODELS BUILDER

Add this to web.config

 

<add key="Umbraco.ModelsBuilder.ModelsMode" value="LiveAppData" />

 

 

 

CUSTOM BACK OFFICE

Warning: When uploading modified manifests delete this folder
Client Dependency temp files in: \App_Data\TEMP\ClientDependency


Button that copies fields from one location to another

/App_Plugins/ MemberCopyAddress

See AEC.MemberCopyAddress

 

Saved Event – new used it as it may be incomplete.
Instead use this:

 

  public class CacheUpdateEvent : ComponentComposer<CacheComponent>

  { }

 

  public class CacheComponent : IComponent

  {

 

    public void Initialize()

    {

      CacheRefresherBase<MemberCacheRefresher>.CacheUpdated += CacheUpdated;

    }

 

    private void CacheUpdated(MemberCacheRefresher sender, CacheRefresherEventArgs e)

    {

      Umbraco.Web.Cache.MemberCacheRefresher.JsonPayload p =

        ((Umbraco.Web.Cache.MemberCacheRefresher.JsonPayload[])e.MessageObject)[0];

 

      int memberId = p.Id;

    }

}

 

 

 

Custom Dashboard

See AEC Export Members

 

Get Id of Current Document

var nodeId = $routeParams.id;

 

 

EVENTS

Warning – Use the undocumented CacheUpdated event

https://our.umbraco.com/forum/using-umbraco-and-getting-started/100726-umbraco-events-getting-newly-created-node-inside-the-contentservicesaved-event

https://our.umbraco.com/forum/extending-umbraco-and-using-the-api/94308-load-balanced-site-pagecacherefreshercacheupdated-does-not-seem-to-fire-on-slave-server

 

public void Initialize()

{

  CacheRefresherBase<ContentCacheRefresher>.CacheUpdated += CacheUpdated;

}

 

private void CacheUpdated(ContentCacheRefresher sender, CacheRefresherEventArgs e)

{

  UpdateCampaigns(e);

  UpdateMembershipType(e);

}

 

CUSTOM ROUTES

See Cromwell Umbraco build

 

Count all database rows

CREATE TABLE #counts

(

    table_name varchar(255),

    row_count int

)

 

EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'

SELECT sum(row_count) FROM #counts

SELECT table_name, row_count FROM #counts ORDER BY table_name, row_count DESC

DROP TABLE #counts

 

TROUBLESHOOTING

Keep the database size small

delete from umbracoLog

delete from umbracoCacheInstruction

delete from cmsTags where id not in (select tagId from cmsTagRelationship)

 

Umbraco Core cannot start

Check the database user has the dbo schema

 

Umbraco wants to reinstall on database upload

Check the database user has the dbo schema

 

How to delete a user

It is possible, though it does require running a sql script. Below is the script I use.

DECLARE @userId AS INT = 1
UPDATE umbracoNode SET nodeUser = -1 WHERE nodeUser = @userId
UPDATE umbracoContentVersion SET userId = -1 WHERE userId = @userId
DELETE FROM umbracoLog WHERE userId = @userId
DELETE FROM umbracoUserStartNode WHERE [userId] = @userId
DELETE FROM umbracoUser2NodeNotify WHERE [userId] = @userId
DELETE FROM umbracoUser2UserGroup WHERE [userId] = @userId
DELETE FROM umbracoUserLogin WHERE userID = @userId
DELETE FROM umbracoUser WHERE id = @userId

This script removes the user completely from the system by updating the resources that can't be deleted to point at the root user and then deleting all connected table entries. If the umbracoLog table needs to be preserved, it can be changed to

UPDATE umbracoLog SET userId = -1 WHERE userId = @userId

To get the id of the user, just visit the user in the backoffice. The user's id can be seen in the url (/umbraco/#/users/users/user/{user id}).

 

Can’t find Backoffice node

If there is a picker for those content types (Media, Content etc) give it a start node. It is likely the start node changed and doesn’t exist.

Share