xorcery / TableEditor

11 stars 8 forks source link

Programmatic import / insert of data #4

Closed ConcatenatedNonsense closed 9 years ago

ConcatenatedNonsense commented 9 years ago

Hi,

Firstly thanks for creating this, you solved a need I didn't realise I had until the very last moment!

Secondly, I'm now hunting for a way to insert data into a table during an automated import procedure. After attempting to find the data in the database I notice it seems to be stored in the form:

"useFirstRowAsHeader": true, "useLastRowAsFooter": false, "tableStyle": null, "columnStylesSelected": [ null, null, null, null ], "rowStylesSelected": [ null, null, null ], "cells": [ [ { "value": "Column 1" }, { "value": "Column 2" }, { "value": "Column 3" }, { "value": "Column 4" } ], [ { "value": "Row 1" }, { "value": "Value 1" }, { "value": "Value 2" }, { "value": "Value 3" } ], [ { "value": "Row 2" }, { "value": "Value 1" }, { "value": "Value 2" }, { "value": "Value 3" } ], ]

Is it feasible to simply insert data in this format directly into the database (my experience of doing this with Umbraco 7 so far has been wobbly at best), or is there a cleaner way of achieving this?

Regards, Chris.

tomfulton commented 9 years ago

Hi Chris,

In general you don't want to access the Umbraco DB directly but should favor their APIs instead. You could do this pretty easily using the ContentService to get the desired node, and use SetValue to add your data, passing the property alias you want to update.

Ideally we might also provide a model you could use instead of building the JSON as a string, but we haven't started on that just yet.

Hope that helps -Tom

ConcatenatedNonsense commented 9 years ago

Hi Tom,

Thanks for getting back to me, funnily enough I gave that a bash last night. The following works great for inserting the data, but still requires a manual publish from within Umbraco afterwards:

    var cs = new ContentService(); 
    var importNode = cs.GetById(ImportNodeId);
    if (importNode.Properties.Contains("Table"))
    {
         try
         {
             var jsonObject = JObject.Parse(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "/xml/Table.json"));
             importNode.SetValue("Table", jsonObject.ToString());
             cs.SaveAndPublishWithStatus(importNode);
           }
           catch (Exception)
           {
                // Handle file read errors
                throw;
            }
        }

Using magic strings for references works at the moment but a model would be brilliant for future implementations :)

Regards, Chris.

tomfulton commented 9 years ago

Awesome! You shouldn't need the manual publish, something else might be going on ;)