I'm using CsvHelper, but my parsing is crashing if the first line of the file is like sep=,
I'm doing it like this:
using var reader = new StreamReader(fileStream);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
return csv.GetRecords<ClassToReadInto>()
.Select(t => new ClassToMapTo
{
// map goes here
})
.ToList();
What happens is:
CsvHelper.HeaderValidationException: Header with name 'Type'[0] was not found. // and a bunch of other names
So CsvHelper is just trying to treat the first row as a header row. I doubt it even sets the separator from this row. To work this around I only came up with something like this:
while (csv.Read())
{
csv.ReadHeader();
try
{
csv.ValidateHeader(typeof(CsvOrder));
break;
}
catch { }
}
Is there "the right way" to do so?
If it's always there, you can just read a row first.
csv.Read();
var records = csv.GetRecords<ClassToReadInto>();
If it's not always there, you'll need to do a check.
csv.Read();
if (!csv[0].StartsWith("sep="))
{
// The first row is the header, so we need to read it.
csv.ReadHeader();
}
var records = csv.GetRecords<ClassToReadInto>();
Related
I'm using the monaco editor for validating JSON in accordance with a custom schema, such as is described in this Playground example.
Next, I'd like to customize a hover event whose behavior depends on which part of the schema is being hovered over. I can easily add a hover event that knows what word I'm hovering over, by just adding some code like this:
monaco.languages.registerHoverProvider('json', {
provideHover: function(model, position) {
// get the word that the cursor is currently hovering over
var word = model.getWordAtPosition(position);
var wordRange = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
return {
contents: [{ value: 'This word is: ' + word.word }],
range: wordRange
};
}
});
But what I also need to know is the schema path-- something like this, but with a properly functioning getSchemaPart():
function getSchemaPart(model, position) {
return ['http://myserver/bar-schema.json#', 'p1'].join('/'); // How do I do this properly?
}
monaco.languages.registerHoverProvider('json', {
provideHover: function(model, position) {
// get the word that the cursor is currently hovering over
var word = model.getWordAtPosition(position);
var wordRange = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);
var schemaPart = getSchemaPart(model, position);
return {
contents: [{ value: 'This word is: ' + word.word + ' and its schema part is ' + schemaPart }],
range: wordRange
};
}
});
Clearly, Monaco already knows this information since it's needed for validation. Is there any way to fetch it in my hover event?
Alternatively, is there a clean way to use some other library and feed it the entire JSON value, and then figure out what schema part applies to the particular position that is being hovered over? This latter approach seems feasible in theory but challenging when considering that there may be whitespace in the input which the parser ignores, and therefore it requires mapping positions to tokens to schema parts.
I am trying to write data into a file. Want I want to do is to have each function open a file if it exists, write to it and then close it before the next function. Below is the code I got so far which does write to a file but not how I want it as mentioned.
For example, I want GetInitialRoomData() to first open, write and close the file. Then the next function GetInitialTargetData() open, write and close the file. Any ideas / code would be appreciated? Thanks!
void WriteInitialDataToFile()
{
string path = Application.persistentDataPath + fileName;
if (!File.Exists(path))
{
File.WriteAllText(path, "");
}
GetInitialRoomData();
GetInitialTargetData();
string json = JsonConvert.SerializeObject(saveDataList);
Debug.Log(json);
File.AppendAllText(path, json);
}
void GetInitialRoomData()
{
foreach (GameObject roomObject in GameObject.FindGameObjectsWithTag("Cell"))
{
saveRoomObject = new SaveRoomData(roomObject.name, roomObject.transform.position);
saveDataList.Add(saveRoomObject);
}
}
void GetInitialTargetData()
{
foreach (GameObject targetObject in GameObject.FindGameObjectsWithTag("Target"))
{
saveTargetObject = new SaveRoomData(targetObject.name, targetObject.transform.position, targetObject.transform.eulerAngles);
saveDataList.Add(saveTargetObject);
}
}
I think your problem is not how to open and write a file, you already did it by using File.AppendAllText function.
You can not serialize a List directly when using SerializeObject function. And finally in your case, JsonConvert.SerializeObject(saveDataList); will return empty string and so your file will be empty too.
Use a Class or an Array instead (Read More)
I have django-tables2 set up and working well. I have set my table to be able to update checkbox columns directly from the displayed list. However when my displayed table paginates and I update a value it refreshes the entire page thus sending me back to the first page and I then have to click 'next' to get back to where I was. So I thought it might be a good idea to throw knockout.js into the mix to bind my individual columns to the corresponding data in my postgres database. According to the blurb this would allow me to simply refresh the item clicked on without having to refresh the entire page. I read the tutorial for knockout.js and all seems great and exactly what I am looking for. I've modified my views and written my js file etc and I am almost there. I have the JSONResponse from my views.py returning the correct number of rows, however, my django-tables2 tables are rendering each record as a header (ie th) in my table instead of the data as a row (ie td). Feeling like I've fallen at the last hurdle, I was wondering if anyone can shed any light on how I can fix this last bit of the puzzle please.
view.py
def mydatalist(request):
data = []
user = get_current_user()
query = Q(user_fkey=user.id)
query.add(Q(deleted__isnull=True), Q.AND)
query.add(Q(master=True), Q.AND)
tasks = Task.objects.filter(query)
for task in tasks:
data.append({"code":task.code, "name":task.name, etc})
return JsonResponse(data, safe=False)
my .js file
function Task(data) {
this.code = ko.observable(data.code);
this.name = ko.observable(data.name);
etc
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
$.getJSON('http://myweb.org/tasks/mydatalist/', function (data) {
if(data){
var mappedTasks = $.map(data, function (item) {
return new Task(item);
});
} else {
alert('data empty!');
}
self.tasks(mappedTasks);
});
}
ko.applyBindings(new TaskListViewModel());
my django-tables2 tables.py file
class MasterTable(ColumnShiftTable):
code = tables.Column(attrs={'th':{'class':'centered nodec'}})
name = tables.LinkColumn(attrs={'th':{'class':'centered nodec'}})
etc
class Meta:
model = Task
fields = ('code','name', etc)
template_name = 'django_tables2_column_shifter/bootstrap3.html'
attrs={'id':'masterlist', 'class': 'table table-noborder', 'data-bind': 'foreach: tasks, visible: task().length > 0'}
row_attrs={'id': lambda record: record.pk}
So basically everything is kind of working except that when rendered, my django-tables2 table is rendering 11 headers and no data rows instead of 1 header and 10 data rows.
If anyone can shed any light I really would appreciate it or alternatively if someone can suggest another way to achieve not having to refresh the entire page each time, that would be great also.
I have a code like this:
List<Models.MyModel> myobjects = new List<Models.MyModel>();
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
if(await reader.ReadAsync())
{
myobjects.AddRange(((IObjectContextAdapter)this)
.ObjectContext
.Translate<Models.MyModel>(reader,
GetEntitySetName<DbModels.MyModel>(),
MergeOption.NoTracking);
}
}
However, this skips the first row in the resultset. If I change this to
List<Models.MyModel> myobjects = new List<Models.MyModel>();
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
//if(await reader.ReadAsync())
{
myobjects.AddRange(((IObjectContextAdapter)this)
.ObjectContext
.Translate<Models.MyModel>(reader,
GetEntitySetName<DbModels.MyModel>(),
MergeOption.NoTracking);
}
}
I get back all the rows. Has anyone encountered this? If so, is there a workaround or a different way to call? The corresponding synchronous calls cmd.ExecuteReader() and reader.Read() run without any problems and always return all rows.
After calling await reader.ReadAsync() in your if condition you moved the reader to the next row. Then you passed the reader to the Translate method so it continues to read from it. Since you have already consumed some rows Translate is not able to read them anymore (i.e. it can't reset the reader to start reading from the first row)
I'm using a kendo UI tree with a remote data source from a JSON file.
I have a button on the tree page which gets the current data of the tree,sends it through a POST to a server and the server saves the current data to the JSON file so as the next time I reload the page,the changes I made will be kept.That's what I want to happen.
So I know the current data of the tree is in:
$("#treeview").data("kendoTreeView").dataSource.data()
Which means the data changes real time in there for example when someone drag and drops a node of the tree.
My problem starts when this data doesn't seem to change when I drag and drop nodes inside the tree,and only changes when I drag and drop a node on the root level of the tree and even then it doesn't do it correcly as the node should be moved in there as well but instead the node gets copied,leaving the past node in the tree as well...
For Example I have this tree:
If I make a drag and drop change like this:
And I send the data,save it and reload the change isn't made at all!
PS:Even when I view the current data after the change before sending it,I see that there is no change on the data at all even though I did a change visualy with a drag and drop.So it doesn't have to do with the sending,saving and the server.
On the other hand,if I make a change like this:
I can see in the current data that the moved node is added in the end of the data indeed but it is not deleted from it's initial position within the data!So if i send the current data to the server,save it and then refresh I get the result:
The code for viewing and sending the data is:
function sendData() {
var req = createRequest();
var putUrl = "rest/hello/treeData";
req.open("post", putUrl, true);
req.setRequestHeader("Content-type","application/json");
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
alert(JSON.stringify(dsdata));
req.send(JSON.stringify(dsdata));
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
Is this a Bug or am I doing something wrong?Has anyone been able to see the current data changing correctly on every drag and drop?
First and most important you have to use the latest version of KendoUI (Kendo UI Beta v2012.3.1024) still in beta but is where they have solved many problems.
Then, when you create the kendoTreeView you have to say something like:
tree = $("#treeview").kendoTreeView({
dataSource :kendo.observableHierarchy(data),
dragAndDrop:true
}).data("kendoTreeView");
Here the important is not using directly data array but wrapping it with kendo.observableHierarchy.
Then you will have the data updated with the result of drag & drops.
For me in addition to OnaBai answer I had to use the sync function on the save method. I am using Type Script.
this.treeData = new kendo.data.HierarchicalDataSource({
data: kendo.observableHierarchy([]),//Thanks OnaBai
schema: {
model: {
id: "MenuItemId",
children: "MenuItemChildren",
hasChildren: (e) => {
//this removes arrow next to items that do not have children.
return e.MenuItemChildren && e.MenuItemChildren.length > 0;
}
}
}
});
public save() {
this.treeData.sync().done(() => {
console.log("sync data");
var myType = this.treeData.view();
this.$http.post("/api/TreeViewPicker", myType)
.then((response) => {
});
});
}