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)
Related
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>();
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.
consider a grammar like this ; speech.Recognizer.Grammars.AddGrammarFromList("answer",new string[] { "Go.","no" });
When I say something else that are not in grammar, she says "sorry didnt catch" and then tries to start it again. Same goes for null input.
What I want is that it should only recognize the words in grammar and for everything else it should just pass the recognition. I don't want to see anything like "sorry didnt catch" and second time recognotion. Any idea ? thanks.
Edit : with try-catch I can avoid from second time recognotion if the word is unknown but now it's waiting too long on "sorry didnt catch" part.
try
{
SpeechRecognizerUI speech = new SpeechRecognizerUI();
speech.Settings.ReadoutEnabled = false;
speech.Settings.ShowConfirmation = false;
speech.Recognizer.Settings.InitialSilenceTimeout = System.TimeSpan.FromSeconds(0.8);
speech.Recognizer.Grammars.AddGrammarFromList("answer", new string[] { "Go.", "no" });
SpeechRecognitionUIResult result = await speech.RecognizeWithUIAsync();
if (result.RecognitionResult.Text == "Go.") { .... }
}
catch
{
..... }
In my opinion, you must build your own UI to avoid this. So you should use SpeechRecognizer and then you can handle the input as you want.
In my case I even created two SpeechRecognizer, on with own Wordlist, the other one with default dictionary. It works like a charm, but I couldn't get it to work with SpeechRecognizerUI.
I have used InternalProfileFormHandler to add an item InternalProfileRepository. It has successfully added the item(user:iuser310002) to the intended repository. Once added, I have accessed dyn/admin to open the repository and removed item I have just added by using <remove-item item-descriptor="user" id="iuser310002" />. Then I have used invoked InternalProfileFormHandler again to add one more item. However this time, I have got an atg.repository.RemovedItemException saying that Attempt to use an item which has been removed: user:iuser310002.
I'm not sure why it is trying to create a new user with same id as before and even if I did, why an item which is removed should cause this issue. I'm using default idGenerator /atg/dynamo/service/IdGenerator for InternalProfileRepository so I don't think I would be generating same id.
Here is the code that succesfully created item once and failing from second time...
FormHandlerInvoker invoker = new FormHandlerInvoker("/atg/userprofiling/InternalProfileFormHandler", Nucleus.getSystemNucleus());
try {
String paramName;
int paramCounter = 1;
while((paramName = (String) getCurrentTestParams().get("param" + paramCounter)) != null)
{
invoker.addInput(paramName, (String) getCurrentTestParams().get("value" + paramCounter));
paramCounter++;
}
} catch (ServletException e) {
e.printStackTrace();
}
FormHandlerInvocationResult result;
ProfileFormHandler formHandler = null;
try {
result = invoker.invoke();
formHandler =
(ProfileFormHandler)result.getDefaultFormHandler();
formHandler.handleCreate(result.getRequest(), result.getResponse());
}
Following is the exception log... which is caused by formHandler.handleCreate method invocation.
atg.repository.RemovedItemException: Attempt to use an item which has been removed: user:iuser310002
at atg.adapter.gsa.ItemTransactionState.<init>(ItemTransactionState.java:385)
at atg.adapter.gsa.GSAItem.getItemTransactionState(GSAItem.java:2421)
at atg.adapter.gsa.GSAItem.getItemTransactionState(GSAItem.java:2364)
at atg.adapter.gsa.GSAItem.getItemTransactionStateUnchecked(GSAItem.java:2600)
at atg.adapter.gsa.GSAItem.getPropertyValue(GSAItem.java:1511)
at atg.repository.RepositoryItemImpl.getPropertyValue(RepositoryItemImpl.java:151)
at atg.adapter.composite.CompositeItem.createPropertyQuery(CompositeItem.java:739)
at atg.adapter.composite.CompositeItem.getPropertyLinkedItem(CompositeItem.java:630)
at atg.adapter.composite.CompositeItem.getContributingItem(CompositeItem.java:577)
at atg.adapter.composite.CompositeItem.findContributingItem(CompositeItem.java:561)
at atg.adapter.composite.MutableCompositeItem.findContributingItem(MutableCompositeItem.java:971)
at atg.adapter.composite.MutableCompositeItem.getOrCreateContributingItem(MutableCompositeItem.java:985)
at atg.adapter.composite.MutableCompositeItem.setPropertyValue(MutableCompositeItem.java:210)
at atg.userprofiling.ProfileForm.updateProfileAttributes(ProfileForm.java:3761)
at atg.userprofiling.ProfileForm.updateProfileAttributes(ProfileForm.java:3528)
at atg.userprofiling.ProfileForm.createUser(ProfileForm.java:1507)
at atg.userprofiling.ProfileForm.handleCreate(ProfileForm.java:1214)
at atg.userprofiling.ProfileFormHandler.handleCreate(ProfileFormHandler.java:402)
at atg.scenario.userprofiling.ScenarioProfileFormHandler.handleCreate(ScenarioProfileFormHandler.java:599)
at atg.test.steps.CreateInternalUserStep.runTest(CreateInternalUserStep.java:45)
After some digging around, I figured out the reason. Along with creating user, a session is also being created for the same user automatically. The user could be found by going to this path in dyn/admin. /atg/dynamo/servlet/sessiontracking/GenericSessionManager/notdefined/atg/userprofiling/Profile/
Next time when I'm deleting the item in InternalProfileRepository, the item is being deleted successfully but the session object still exists.
When I call the formhandler.handleCreate again, it is checking if the profile object exists. When it found the user, it is trying to update the same user instead of creating a new one. Hence I'm getting the RemovedItemException.
However, I'm not quite sure if that is what is expected.