Last active
July 23, 2016 11:27
-
-
Save glcheetham/8e94616147e32927f8a6af01923e08c4 to your computer and use it in GitHub Desktop.
Umbraco LINQPad CSV Import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Helper method enumerates over and returns lines in a file | |
static IEnumerable<string> ReadFrom(string file) | |
{ | |
string line; | |
using(var reader = System.IO.File.OpenText(file)) | |
{ | |
while((line = reader.ReadLine()) != null) | |
{ | |
yield return line; | |
} | |
} | |
} | |
// Example struct, represents a sample schema that data from your CSV may fit into | |
struct Person { | |
public string Name; | |
public string Area; | |
} | |
void Main() | |
{ | |
// Instantiate an empty list of people for us to add to later. | |
var people = new List<Person>(); | |
// Iterate over every row in the CSV, cast it to a "Person", and save it to the list | |
var csvData = ReadFrom(@"C:\\Users\\glcheetham\\Desktop\\people.csv"); | |
foreach(var row in csvData) { | |
var columns = row.Split(','); | |
var person = new Person(); | |
person.Name = columns[0]; | |
person.Area = columns[1]; | |
people.Add(person); | |
} | |
// Get an instance of the Umbraco content service (from the LINQPad driver) | |
// The content service provides methods for creating, updating, and deleting content nodes | |
var contentService = ApplicationContext.Services.ContentService; | |
// We need a node to act as a parent to the content nodes we'll create | |
// Here, we get a node from the content service by node ID. | |
var parentNode = contentService.GetById(36259); | |
// Iterate over our list of "people" and save each one to Umbraco | |
foreach(var person in people) { | |
// The format of the arguments here is: Node name, Parent Node ID, Document type alias | |
var personContentNode = contentService.CreateContent(person.Name, parentNode.Id, "site"); | |
personContentNode.SetValue("area", dealer.Area); | |
try { | |
contentService.Save(personContentNode); | |
Debug.WriteLine(string.Format("Saved {0} to Umbraco", person.Name)); | |
} catch(Exception e) { | |
Debug.WriteLine(e); | |
} | |
} | |
} | |
// Define other methods and classes here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment