NetSuite - get csv values using suitescript - netsuite

I would like to do update a whole bunch of 'rev rec plan' records. Updating using mass update isn't available nor is an import possible.
So the only way I think I could do this is via script (probably scheduled), but I am not sure how to retrieve the 3 fields in my excel (internal id, start date and end date). I need the script to get the date fields from my file and using the internal id update the rec rec dates.
Thanks

You should be able to get started with the following code. Just get the internal id of the file you want to parse.
function parseCSVFromFile(fileId){
var csvFile = nlapiLoadFile(fileId);
var csv = csvFile.getValue();
var parsedCSV = CSVParser().parse(csv);
var data= parsedCSV.data;
return data;
}
function CSVParser(){function e(r,n){if(Array.isArray(r)){var i=[];return r.forEach(function(t){"object"==typeof t?i.push(e(t.file,t.config)):i.push(e(t,n))}),i}var i={data:[],errors:[]};if(!/(\.csv|\.txt)$/.test(r))return i.errors.push({type:"",code:"",message:"Unsupported file type.",row:""}),i;try{var a=fs.readFileSync(r).toString();return t(a,n)}catch(s){return i.errors.push(s),i}}function t(e,t){var r=a(t),i=new n(r),s=i.parse(e);return f(r.complete)&&r.complete(s),s}function r(e,t){function r(){"object"==typeof t&&("string"==typeof t.delimiter&&1==t.delimiter.length&&-1==l.BAD_DELIMITERS.indexOf(t.delimiter)&&(o=t.delimiter),("boolean"==typeof t.quotes||t.quotes instanceof Array)&&(f=t.quotes),"string"==typeof t.newline&&(d=t.newline))}function n(e){if("object"!=typeof e)return[];var t=[];for(var r in e)t.push(r);return t}function i(e,t){var r="";"string"==typeof e&&(e=JSON.parse(e)),"string"==typeof t&&(t=JSON.parse(t));var n=e instanceof Array&&e.length>0,i=!(t[0]instanceof Array);if(n){for(var s=0;s<e.length;s++)s>0&&(r+=o),r+=a(e[s],s);t.length>0&&(r+=d)}for(var f=0;f<t.length;f++){for(var l=n?e.length:t[f].length,u=0;l>u;u++){u>0&&(r+=o);var p=n&&i?e[u]:u;r+=a(t[f][p],u)}f<t.length-1&&(r+=d)}return r}function a(e,t){if("undefined"==typeof e||null===e)return"";e=e.toString().replace(/"/g,'""');var r="boolean"==typeof f&&f||f instanceof Array&&f[t]||s(e,l.BAD_DELIMITERS)||e.indexOf(o)>-1||" "==e.charAt(0)||" "==e.charAt(e.length-1);return r?'"'+e+'"':e}function s(e,t){for(var r=0;r<t.length;r++)if(e.indexOf(t[r])>-1)return!0;return!1}var f=!1,o=",",d="\r\n";if(r(),"string"==typeof e&&(e=JSON.parse(e)),e instanceof Array){if(!e.length||e[0]instanceof Array)return i(null,e);if("object"==typeof e[0])return i(n(e[0]),e)}else if("object"==typeof e)return"string"==typeof e.data&&(e.data=JSON.parse(e.data)),e.data instanceof Array&&(e.fields||(e.fields=e.data[0]instanceof Array?e.fields:n(e.data[0])),e.data[0]instanceof Array||"object"==typeof e.data[0]||(e.data=[e.data])),i(e.fields||[],e.data||[]);throw"exception: Unable to serialize unrecognized input"}function n(e){function t(){if(E&&m&&(p("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+l.DefaultDelimiter+"'"),m=!1),e.skipEmptyLines)for(var t=0;t<E.data.length;t++)1==E.data[t].length&&""==E.data[t][0]&&E.data.splice(t--,1);return r()&&n(),a()}function r(){return e.header&&0==w.length}function n(){if(E){for(var e=0;r()&&e<E.data.length;e++)for(var t=0;t<E.data[e].length;t++)w.push(E.data[e][t]);E.data.splice(0,1)}}function a(){if(!E||!e.header&&!e.dynamicTyping)return E;for(var t=0;t<E.data.length;t++){for(var r={},n=0;n<E.data[t].length;n++){if(e.dynamicTyping){var i=E.data[t][n];"true"==i||"TRUE"===i?E.data[t][n]=!0:"false"==i||"FALSE"===i?E.data[t][n]=!1:E.data[t][n]=u(i)}e.header&&(n>=w.length?(r.__parsed_extra||(r.__parsed_extra=[]),r.__parsed_extra.push(E.data[t][n])):r[w[n]]=E.data[t][n])}e.header&&(E.data[t]=r,n>w.length?p("FieldMismatch","TooManyFields","Too many fields: expected "+w.length+" fields but parsed "+n,t):n<w.length&&p("FieldMismatch","TooFewFields","Too few fields: expected "+w.length+" fields but parsed "+n,t))}return e.header&&E.meta&&(E.meta.fields=w),E}function o(t){for(var r,n,a,s=[","," ","|",";",l.RECORD_SEP,l.UNIT_SEP],f=0;f<s.length;f++){var o=s[f],d=0,u=0;a=void 0;for(var p=new i({delimiter:o,preview:10}).parse(t),c=0;c<p.data.length;c++){var h=p.data[c].length;u+=h,"undefined"!=typeof a?h>1&&(d+=Math.abs(h-a),a=h):a=h}u/=p.data.length,("undefined"==typeof n||n>d)&&u>1.99&&(n=d,r=o)}return e.delimiter=r,{successful:!!r,bestDelimiter:r}}function d(e){e=e.substr(0,1048576);var t=e.split("\r");if(1==t.length)return"\n";for(var r=0,n=0;n<t.length;n++)"\n"==t[n][0]&&r++;return r>=t.length/2?"\r\n":"\r"}function u(e){var t=g.test(e);return t?parseFloat(e):e}function p(e,t,r,n){E.errors.push({type:e,code:t,message:r,row:n})}var c,h,m,g=/^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i,y=this,v=0,b=!1,w=[],E={data:[],errors:[],meta:{}};if(f(e.step)){var x=e.step;e.step=function(n){if(E=n,r())t();else{if(t(),0==E.data.length)return;v+=n.data.length,e.preview&&v>e.preview?h.abort():x(E,y)}}}this.parse=function(r){if(e.newline||(e.newline=d(r)),m=!1,!e.delimiter){var n=o(r);n.successful?e.delimiter=n.bestDelimiter:(m=!0,e.delimiter=l.DefaultDelimiter),E.meta.delimiter=e.delimiter}var a=s(e);return e.preview&&e.header&&a.preview++,c=r,h=new i(a),E=h.parse(c),t(),!f(e.complete)||b||y.streamer&&!y.streamer.finished()||e.complete(E),b?{meta:{paused:!0}}:E||{meta:{paused:!1}}},this.pause=function(){b=!0,h.abort(),c=c.substr(h.getCharIndex())},this.resume=function(){b=!1,h=new i(e),h.parse(c),b||(y.streamer&&!y.streamer.finished()?y.streamer.resume():f(e.complete)&&e.complete(E))},this.abort=function(){h.abort(),f(e.complete)&&e.complete(E),c=""}}function i(e){e=e||{};var t=e.delimiter,r=e.newline,n=e.comments,i=e.step,a=e.preview,s=e.fastMode;if(("string"!=typeof t||1!=t.length||l.BAD_DELIMITERS.indexOf(t)>-1)&&(t=","),n===t)throw"Comment character same as delimiter";n===!0?n="#":("string"!=typeof n||l.BAD_DELIMITERS.indexOf(n)>-1)&&(n=!1),"\n"!=r&&"\r"!=r&&"\r\n"!=r&&(r="\n");var f=0,o=!1;this.parse=function(e){function l(){return w.push(e.substr(f)),v.push(w),f=c,y&&p(),u()}function d(t){v.push(w),w=[],f=t,O=e.indexOf(r,f)}function u(e){return{data:v,errors:b,meta:{delimiter:t,linebreak:r,aborted:o,truncated:!!e}}}function p(){i(u()),v=[],b=[]}if("string"!=typeof e)throw"Input must be a string";var c=e.length,h=t.length,m=r.length,g=n.length,y="function"==typeof i;f=0;var v=[],b=[],w=[];if(!e)return u();if(s){for(var E=e.split(r),x=0;x<E.length;x++)if(!n||E[x].substr(0,g)!=n){if(y){if(v=[E[x].split(t)],p(),o)return u()}else v.push(E[x].split(t));if(a&&x>=a)return v=v.slice(0,a),u(!0)}return u()}for(var D=e.indexOf(t,f),O=e.indexOf(r,f);;)if('"'!=e[f])if(n&&0===w.length&&e.substr(f,g)===n){if(-1==O)return u();f=O+m,O=e.indexOf(r,f),D=e.indexOf(t,f)}else if(-1!==D&&(O>D||-1===O))w.push(e.substring(f,D)),f=D+h,D=e.indexOf(t,f);else{if(-1===O)break;if(w.push(e.substring(f,O)),d(O+m),y&&(p(),o))return u();if(a&&v.length>=a)return u(!0)}else{var A=f;for(f++;;){var A=e.indexOf('"',A+1);if(-1===A)return b.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:v.length,index:f}),l();if(A===c-1)return w.push(e.substring(f,A).replace(/""/g,'"')),v.push(w),y&&p(),u();if('"'!=e[A+1]){if(e[A+1]==t){w.push(e.substring(f,A).replace(/""/g,'"')),f=A+1+h,D=e.indexOf(t,f),O=e.indexOf(r,f);break}if(e.substr(A+1,m)===r){if(w.push(e.substring(f,A).replace(/""/g,'"')),d(A+1+m),D=e.indexOf(t,f),y&&(p(),o))return u();if(a&&v.length>=a)return u(!0);break}}else A++}}return l()},this.abort=function(){o=!0},this.getCharIndex=function(){return f}}function a(e){"object"!=typeof e&&(e={});var t=s(e);return("string"!=typeof t.delimiter||1!=t.delimiter.length||l.BAD_DELIMITERS.indexOf(t.delimiter)>-1)&&(t.delimiter=o.delimiter),"\n"!=t.newline&&"\r"!=t.newline&&"\r\n"!=t.newline&&(t.newline=o.newline),"boolean"!=typeof t.header&&(t.header=o.header),"boolean"!=typeof t.dynamicTyping&&(t.dynamicTyping=o.dynamicTyping),"number"!=typeof t.preview&&(t.preview=o.preview),"function"!=typeof t.step&&(t.step=o.step),"function"!=typeof t.complete&&(t.complete=o.complete),"boolean"!=typeof t.skipEmptyLines&&(t.skipEmptyLines=o.skipEmptyLines),"boolean"!=typeof t.fastMode&&(t.fastMode=o.fastMode),t}function s(e){if("object"!=typeof e)return e;var t=e instanceof Array?[]:{};for(var r in e)t[r]=s(e[r]);return t}function f(e){return"function"==typeof e}var o={delimiter:"",newline:"",header:!1,dynamicTyping:!1,preview:0,step:void 0,comments:!1,complete:void 0,skipEmptyLines:!1,fastMode:!1},l={};return l.parse=t,l.parseFiles=e,l.unparse=r,l.RECORD_SEP=String.fromCharCode(30),l.UNIT_SEP=String.fromCharCode(31),l.BYTE_ORDER_MARK="\ufeff",l.BAD_DELIMITERS=["\r","\n",'"',l.BYTE_ORDER_MARK],l.DefaultDelimiter=",",l.Parser=i,l.ParserHandle=n,l}
Example:
var parsedCSV = parseCSVFromFile(123);
nlapiLogExecution('DEBUG', "parsedCSV ", JSON.stringify(parsedCSV));

Related

Python - Error querying Solarwinds N-Central via SOAP

I'm using python 3 to write a script that generates a customer report for Solarwinds N-Central. The script uses SOAP to query N-Central and I'm using zeep for this project. While not new to python I am new to SOAP.
When calling the CustomerList fuction I'm getting the TypeError: __init__() got an unexpected keyword argument 'listSOs'
import zeep
wsdl = 'http://' + <server url> + '/dms/services/ServerEI?wsdl'
client = zeep.CachingClient(wsdl=wsdl)
config = {'listSOs': 'true'}
customers = client.service.CustomerList(Username=nc_user, Password=nc_pass, Settings=config)
Per the perameters below 'listSOs' is not only a valid keyword, its the only one accepted.
CustomerList
public com.nable.nobj.ei.Customer[] CustomerList(String username, String password, com.nable.nobj.ei.T_KeyPair[] settings) throws RemoteException
Parameters:
username - MSP N-central username
password - Corresponding MSP N-central password
settings - A list of non default settings stored in a T_KeyPair[]. Below is a list of the acceptable Keys and Values. If not used leave null
(Key) listSOs - (Value) "true" or "false". If true only SOs with be shown, if false only customers and sites will be shown. Default value is false.
I've also tried passing the dictionary as part of a list:
config = []
key = {'listSOs': 'true'}
config += key
TypeError: Any element received object of type 'str', expected lxml.etree._Element or builtins.dict or zeep.objects.T_KeyPair
Omitting the Settings value entirely:
customers = client.service.CustomerList(Username=nc_user, Password=nc_pass)
zeep.exceptions.ValidationError: Missing element Settings (CustomerList.Settings)
And trying zeep's SkipValue:
customers = client.service.CustomerList(Username=nc_user, Password=nc_pass, Settings=zeep.xsd.SkipValue)
zeep.exceptions.Fault: java.lang.NullPointerException
I'm probably missing something simple but I've been banging my head against the wall off and on this for awhile I'm hoping someone can point me in the right direction.
Here's my source code from my getAssets.py script. I did it in Python2.7, easily upgradeable though. Hope it helps someone else, N-central's API documentation is really bad lol.
#pip2.7 install zeep
import zeep, sys, csv, copy
from zeep import helpers
api_username = 'your_ncentral_api_user'
api_password='your_ncentral_api_user_pw'
wsdl = 'https://(yourdomain|tenant)/dms2/services2/ServerEI2?wsdl'
client = zeep.CachingClient(wsdl=wsdl)
response = client.service.deviceList(
username=api_username,
password=api_password,
settings=
{
'key': 'customerId',
'value': 1
}
)
# If you can't tell yet, I code sloppy
devices_list = []
device_dict = {}
dev_inc = 0
max_dict_keys = 0
final_keys = []
for device in response:
# Iterate through all device nodes
for device_properties in device.items:
# Iterate through each device's properties and add it to a dict (keyed array)
device_dict[device_properties.first]=device_properties.second
# Dig further into device properties
device_properties = client.service.devicePropertyList(
username=api_username,
password=api_password,
deviceIDs=device_dict['device.deviceid'],
reverseOrder=False
)
prop_ind = 0 # This is a hacky thing I did to make my CSV writing work
for device_node in device_properties:
for prop_tree in device_node.properties:
for key, value in helpers.serialize_object(prop_tree).items():
prop_ind+=1
device_dict["prop" + str(prop_ind) + "_" + str(key)]=str(value)
# Append the dict to a list (array), giving us a multi dimensional array, you need to do deep copy, as .copy will act like a pointer
devices_list.append(copy.deepcopy(device_dict))
# check to see the amount of keys in the last item
if len(devices_list[-1].keys()) > max_dict_keys:
max_dict_keys = len(devices_list[-1].keys())
final_keys = devices_list[-1].keys()
print "Gathered all the datas of N-central devices count: ",len(devices_list)
# Write the data out to a CSV
with open('output.csv', 'w') as csvfile:
fieldnames = final_keys
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for csv_line in devices_list:
writer.writerow(csv_line)

Node-red output a message to CSV

For the past couple of days I have been trying and reading to get something very specific done in Node-Red: I want to send the (LoRa) message to a CSV.
This CSV should contain the following items:
topic
date
payload
I can insert the date using a function node:
var str1 = Date();
I have been playing around with CSV node, but I can't get it to output comma separated values. All this has probably to do with my lack of javascript programming skills, which is why I turn to you.
Can you help me out?
Edit:
I'm still looking for the answer, which has brought me the following:
Function node:
var res = Date() + "," + msg.topic + "," + msg.payload; return [ { payload: res } ];
Output:
[{"col1":"Mon Oct 17 2016 17:10:20 GMT+0200 (CEST)","col2":"1/test/1","col3":"string1"}]
All I want now is to lose the extra information such as column names and [{}]
The CSV node works only on the msg.payload field so you will have to copy the extra data into the payload object to get it to output what you want.
So to format the data correctly you need to place a function node with the following before the CSV node:
var originalPayload = msg.payload;
var newPayload = {};
newPayload.date = new Date().toString();
newPayload.topic = msg.topic;
newPayload.payload = originalPayload;
msg.payload = newPayload;
return msg;
And configure the CSV node to output columns "date,topic,payload"

Using Groovy Script, How to access the dynamic soap request which is stored in MessageExchange in a Data-Driven Approach?

I am trying a data driven approach in soap ui using groovy script and I wanted to export each of the dynamic request and response from MessageExchange to an Excel sheet. I am using the input data Excel file "dataFile.xls" for a simple "Login" operation. It consists of 2 fields Username and Password with 4 records. My script is doing a data driven approach and executing all the records from the excel file. But I wanted to export all the four dynamic request and response into an Excel file "Output.xls". My soap pack is having 2 groovy test request(one for data driver and the other for looping), one property test step to hold the input element properties and temporary variables, one soap test request "login". Below is the code snippet I am using in the "data driver" groovy test step.
// IMPORT THE LIBRARIES WE NEED
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*
import com.eviware.soapui.model.iface.MessageExchange
// DECLARE THE VARIABLES
def myTestCase = context.testCase //myTestCase contains the test case
log.info(myTestCase)
def counter,next,previous,size //Variables used to handle the loop and to move inside the file
Workbook workbook1 = Workbook.getWorkbook(new File("d:\\Groovy videos\\dataFile.xls")) //file containing the data
Sheet sheet1 = workbook1.getSheet(0) //save the first sheet in sheet1
size = sheet1.getRows().toInteger() //get the number of rows, each row is a data set
log.info(size)
propTestStep = myTestCase.getTestStepByName("Property - Looper") // get the Property TestStep object
log.info(propTestStep)
req = myTestCase.getTestStepByName("login").getProperty("Request").getValue()
//log.info(req)
propTestStep.setPropertyValue("Total", size.toString())
counter = propTestStep.getPropertyValue("Count").toString() //counter variable contains iteration number
counter = counter.toInteger() //
next = (counter > size-2? 0: counter+1) //set the next value
// OBTAINING THE DATA YOU NEED
Cell u = sheet1.getCell(0,counter) // getCell(column,row) //obtains user
Cell p = sheet1.getCell(1,counter) // obtains password
workbook1.close() //close the file
////////////////////////////////////
usr = u.getContents()
pass = p.getContents()
propTestStep.setPropertyValue("user", usr) //the value is saved in the property
propTestStep.setPropertyValue("pass", pass) //the value is saved in the property
propTestStep.setPropertyValue("Count", next.toString()) //increase Count value
next++ //increase next value
propTestStep.setPropertyValue("Next", next.toString()) //set Next value on the properties step
WritableWorkbook workbook2 = Workbook.createWorkbook(new File("d:\\output.xls"))
WritableSheet sheet2 = workbook2.createSheet("Request", 0)
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def temp=testRunner.testCase.testSteps["login"]
def testStepContext = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext(temp)
def reqq = testStepContext.getRequestContent()
log.info(reqq)
//def temp=testRunner.testCase.testSteps.testRequest.getRequestContent()
//holder = groovyUtils.getXmlHolder(messageExchange.requestContent)
log.info("request : "+temp)
Label label1 = new Label(0, 6, temp);
sheet2.addCell(label1);
workbook2.write()
workbook2.close()
//Decide if the test has to be run again or not
if (counter == size-1)
{
propTestStep.setPropertyValue("StopLoop", "T")
log.info "Setting the stoploop property now..."
}
else if (counter==0)
{
def runner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(testRunner.testCase, null)
propTestStep.setPropertyValue("StopLoop", "F")
}
else
{
propTestStep.setPropertyValue("StopLoop", "F")
}
I am getting the fault
"groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext.getRequestContent() is applicable for argument types: () values: [] error at line: 50"
Could some one please help me in this.
The main objective is to get all the dynamic request and response from the MessageExchange and export all the data into the excel sheet.
Your program throws the exception there:
def testStepContext = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext(temp)
def reqq = testStepContext.getRequestContent()
log.info(reqq)
The exception is pretty clear MissingMethodException so the problem is that com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext doesn't have getRequestContent() method.
Anyway in your code you only use reqq on log.info(reqq)... then without analyzing the whole code the easy solution to solve the problem is simply remove this lines due they are useless.
You better make use of project level event "TestRunListener.afterStep" to accomplish your task.
In this event you'll have access to testRunner, context & testStepResult Objects. The following code snippet can help you.
For Soap Services:
if (context.getCurrentStep() instanceof WsdlTestRequestStep) {
WsdlTestStepResult soapResult= (WsdlTestStepResult) testStepResult;
log.info "Request: "+soapResult.getRequestContent();
log.info "Response: "+soapResult.getResponseContent();
}
For Rest Services:
if (context.getCurrentStep() instanceof RestTestRequestStep) {
RestRequestStepResult restResult= (RestRequestStepResult) testStepResult;
log.info "Request: "+restResult.getRequestContent();
log.info "Response: "+restResult.getResponseContent();
}

SoapUI Load test groovy sequentially reading txt file

I am using free version of soapui. In my load test, I want to read request field value from a text file. The file looks like following
0401108937
0401109140
0401109505
0401110330
0401111204
0401111468
0401111589
0401111729
0401111768
In load test, for each request I want to read this file sequentially. I am using the code mentioned in Unique property per SoapUI request using groovy to read the file. How can I use the values from the file in a sequential manner?
I have following test setup script to read the file
def projectDir = context.expand('${projectDir}') + File.separator
def dataFile = "usernames.txt"
try
{
File file = new File(projectDir + dataFile)
context.data = file.readLines()
context.dataCount = context.data.size
log.info " data count" + context.dataCount
context.index = 0; //index to read data array in sequence
}
catch (Exception e)
{
testRunner.fail("Failed to load " + dataFile + " from project directory.")
return
}
In my test, I have following script as test step. I want to read the current index record from array and then increment the index value
def randUserAccount = context.data.get(context.index);
context.setProperty("randUserAccount", randUserAccount)
context.index = ((int)context.index) + 1;
But with this script, I always get 2nd record of the array. The index value is not incrementing.
You defined the variable context.index to 0 and just do +1
You maybe need a loop to read all values.
something like this :
for(int i=0; i <context.data.size; i++){
context.setProperty("randUserAccount", i);
//your code
}
You can add this setup script to the setup script section for load test and access the values in the groovy script test step using:
context.LoadTestContext.index =((int)context.LoadTestContext.index)+1
This might be a late reply but I was facing the same problem for my load testing for some time. Using index as global property solved the issue for me.
Index is set as -1 initially. The below code would increment the index by 1, set the incremented value as global property and then pick the context data for that index.
<confirmationNumber>${=com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( "index", (com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "index" ).toLong()+1 ).toString()); return (context.data.get( (com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "index" )).toInteger())) }</confirmationNumber>

Odd behaviour of insertNewObjectForEntityForName leading to NSInternalInconsistencyException

I have a rather odd case of getting a core data error whilst experimenting with Swift. I am not sure whether it comes from Swift (beta error?) or whether it is me. However, here is the setup for my test cases (in VTModelTests.swift).
var bundle = NSBundle(forClass: VTModelTests.self)
var url = bundle.URLForResource("VTDocument", withExtension:"momd")
appleModel = NSManagedObjectModel(contentsOfURL: url)
assert (appleModel != nil)
var coord = NSPersistentStoreCoordinator(managedObjectModel: appleModel);
var store = coord.addPersistentStoreWithType(NSInMemoryStoreType,configuration:nil,URL:nil,options:nil,error:nil);
assert (store != nil)
ctx = NSManagedObjectContext();
ctx!.persistentStoreCoordinator=coord
ctx!.retainsRegisteredObjects=true;
var drwName = "Drawing"
var descs = ctx!.persistentStoreCoordinator.managedObjectModel.entitiesByName
for e : AnyObject in descs.allKeys{
assert (descs.objectForKey(e).name == e as String )
if (e as String == drwName) {
NSLog("yeah")
}
}
model = NSEntityDescription.insertNewObjectForEntityForName(drwName,inManagedObjectContext: ctx) as Drawing
My error message looks like this:
2014-06-22 22:12:25.584 xctest[63792:303] yeah
<unknown>:0: error: -[_TtC12VTModelTests12BaseTypeTest testTreeStructure] : failed: caught "NSInternalInconsistencyException", "+entityForName: could not locate an entity named 'Drawing' in this model."
In short, I can "prove" that the entity name is there (the 'yeah' in the log), but core data is showing the issue that the name would not be in the model. Previous versions of the loop printed out the entities and that looked good. I don't have any second versions, and a new changed name ('Model' is now called 'Drawing') is correctly shown in the model data when all entities are printed. The compiled model is in the resulting bundle.
Can anybody explain? Or do I have to wait for the next beta release of Xcode 6? What else did I overlook? Many thanks in advance!
I can confirm the issue. Not an answer but the way around I use is to split insertNewObjectForEntityForName into:
let entity = NSEntityDescription.entityForName("Photo", inManagedObjectContext:context)
let photo = Photo(entity:entity, insertIntoManagedObjectContext:context)

Resources