Skip to content

Instantly share code, notes, and snippets.

@leekelleher
Last active December 10, 2015 12:38
Show Gist options
  • Save leekelleher/4435535 to your computer and use it in GitHub Desktop.
Save leekelleher/4435535 to your computer and use it in GitHub Desktop.
Umbraco console/scripting concept

Umbraco scripting, with console/CLI

Enabling a scripting mechanism for Umbraco, using a console (command line interface) to execute the scripts/queries.

So far, the examples are using C#, however a suitable scripting language should be used. Currently JavaScript is the favourite, followed by Lua and Python.

///
/// An example where you (the developer) are given a handful of email addresses to create Umbraco back-office users for.
/// This script would loop through the emails; make assumptions on the first/last name and create the user.
///
var log = new List<string>();
var emails = new[]{
"john.lennon@beatles.com",
"paul.mccartney@beatles.com",
"george.harrison@beatles.com",
"ringo.starr@beatles.com"
// consider a lot more emails - enough to make doing this via the back-office UI painful!
};
var password = "RaNdOmPaSsWoRd1234567890";
var userType = UserType.GetAllUserTypes().Where(x => x.Alias == "admin").FirstOrDefault();
if (userType == null)
log.Add("Error: UserType 'admin' does not exist.");
foreach (var email in emails)
{
if (User.getAllByEmail(email).Any())
log.Add(string.Format("User existing for '{0}'.", email));
var parts = email.Split('.', '@');
var firstName = string.Concat(char.ToUpper(parts[0][0]), parts[0].Substring(1));
var lastName = string.Concat(char.ToUpper(parts[1][0]), parts[1].Substring(1));
var user = User.MakeNew(firstName, lastName, password, email, userType);
user.Save();
// additional logic can be applied; e.g. email the new user their details.
log.Add(string.Format("User '{0} {1}' created.", firstName, lastName));
}
return log; // to be returned as JSON string/object array [LK]
///
/// console usage: exec CreateUsersFromEmails.cs
///
var output = new List<string>();
// `args` could be dynamic? [LK]
var reader = Log.GetLogReader(LogTypes.Error, DateTime.Now.AddMinutes(-args.minutes));
while (reader.Read())
{
output.Add(string.Format("<li><i>{1:HH:mm}</i> - {0}<br/><br/></li>", reader.GetString("logComment"), reader.GetDateTime("DateStamp")));
}
return output; // to be returned as JSON string/object array [LK]
///
/// console usage: exec GetErrorLogs.cs --minutes:30
///
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment