Skip to content

Instantly share code, notes, and snippets.

@seesharper
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save seesharper/f0be224d10b8aec416c0 to your computer and use it in GitHub Desktop.

Select an option

Save seesharper/f0be224d10b8aec416c0 to your computer and use it in GitHub Desktop.
A C# script (ScriptCS) used to import users into a Ghost Blog database.
using System.Data.SQLite;
using System.Data;
using System.Text.RegularExpressions;
using Dapper;
// Used http://bcrypthashgenerator.apphb.com/ to generate the bcrypt hash for "Password123"
string passwordHash = @"$2a$10$gAq/R8gZFCimFbRO3DCUHOn9xecwJPeVCQt/NGIjASjSouMFEapXq";
string connectionString = @"Data Source = C:\inetpub\wwwroot\blog\content\data\ghost.db";
// Example : Andrew Fuller <[email protected]>, Janet Leverling <[email protected]>
// The file should probably be UTF8
string fileToImport = "people.csv";
// Default role set to "Editor"
int roleId = 2;
// The user that imports the new users.
int createdBy = 1;
string createUser = "INSERT INTO users(uuid, name, slug, password, email, created_at, created_by) ";
createUser = createUser + "SELECT @UserId, @Name, @Slug, @Password, @Email, @CreatedAt, @CreatedBy ";
createUser = createUser + "WHERE NOT EXISTS(SELECT 1 FROM Users where email = @Email)";
string createRoles = "INSERT INTO roles_users (role_id, user_id) SELECT @roleid, u.id FROM Users AS u WHERE NOT EXISTS(SELECT 1 FROM roles_users AS ru WHERE ru.user_id = u.id )";
using(var connection = CreateConnection())
{
var users = ReadUsers();
foreach (var user in users)
{
connection.Execute(createUser, user);
}
connection.Execute(createRoles, new { roleId });
}
public IDbConnection CreateConnection()
{
var connection = new SQLiteConnection(connectionString);
connection.Open();
return connection;
}
public class User
{
public string UserId {get;set;}
public string Name {get;set;}
public string Email {get;set;}
public string Slug {get;set;}
public string Password {get;set;}
public DateTime CreatedAt {get;set;}
public int CreatedBy {get;set;}
}
public IEnumerable<User> ReadUsers()
{
using(StreamReader reader = new StreamReader(fileToImport))
{
var content = reader.ReadToEnd();
var lines = content.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
var name = Regex.Match(line, @"(.+)\s").Groups[1].Value;
var mail = Regex.Match(line, @"<(.+)>").Groups[1].Value;
var slug = Regex.Match(line, @".+<(.+)@").Groups[1].Value.ToLower();
yield return new User {UserId = Guid.NewGuid().ToString(), Name = name, Email = mail, Slug = slug, Password = passwordHash, CreatedAt = DateTime.Now, CreatedBy = createdBy};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment