Trying to call async-Task for Multiple Files at a time
case Type1:
srcCopydir = Dir1
copyfilename = file1;
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;
case Type2:
srcCopydir = Dir2
copyfilename = file2;
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;
case Type3:
srcCopydir = Dir3;
copyfilename = file3
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;
case Type4:
srcCopydir = Dir3;
copyfilename = file3
copyFilesAsyncTask.execute(srcCopydir, copyfilename);
break;
Asysnc task for all these cases start one by one
"doInBackground" runs correctly and return the result correctly however sometimes while executing the asynctask before "onPostExecute" of one task is called "doInBackground" starts for another task
Hence onPostexecute returns the result of other task (e.g. Type2: Async task output is returned corresponding to Type 3 and Type3: Async task returns output expected for Type3)
Try to create new instance of your AsyncTask in every case. Something like this:
case Type1:
srcCopydir = Dir1
copyfilename = file1;
new YourAsyncTask().execute(srcCopydir, copyfilename);
break;
case Type2:
srcCopydir = Dir2
copyfilename = file2;
new YourAsyncTask().execute(srcCopydir, copyfilename);
break;
case Type3:
srcCopydir = Dir3;
copyfilename = file3
new YourAsyncTask().execute(srcCopydir, copyfilename);
break;
case Type4:
srcCopydir = Dir3;
copyfilename = file3
new YourAsyncTask().execute(srcCopydir, copyfilename);
break;
private class Task extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
//preExecute
}
#Override
protected Void doInBackground(Void... voids) {
//Execution Code
return null;
}
#Override
protected void onPostExecute(Void result) {
if(yes){
//Call new Task
new NewTask().execute();
}
}
}
Related
I'm a user for libarry Json.NET Schema, is there a function for generate json sample by given the json schema?
I finally tried another way to get the result, refer the function:
/// <summary>
/// Generate a random Json sample based on json schema
/// </summary>
/// <param name="schema"></param>
/// <returns>a random Json sample</returns>
public static JToken GenerateJsonSample(this JSchema schema)
{
JToken output;
switch (schema.Type)
{
case JSchemaType.Object:
var jObject = new JObject();
if (schema.Properties != null)
{
foreach (var prop in schema.Properties)
{
jObject.Add(LowerCaseFirstChar(prop.Key), GenerateJsonSample(prop.Value));
}
}
output = jObject;
break;
case JSchemaType.Object | JSchemaType.Null:
var jObject2 = new JObject();
if (schema.Properties != null)
{
foreach (var prop in schema.Properties)
{
jObject2.Add(LowerCaseFirstChar(prop.Key), GenerateJsonSample(prop.Value));
}
}
output = jObject2;
break;
case JSchemaType.Array:
var jArray = new JArray();
foreach (var item in schema.Items)
{
jArray.Add(GenerateJsonSample(item));
}
output = jArray;
break;
case JSchemaType.Array | JSchemaType.Null:
var jArray2 = new JArray();
foreach (var item in schema.Items)
{
jArray2.Add(GenerateJsonSample(item));
}
output = jArray2;
break;
case JSchemaType.String:
output = new JValue("string_sample");
break;
case JSchemaType.String | JSchemaType.Null:
output = new JValue("nullable_string_sample");
break;
case JSchemaType.Number:
output = new JValue(1.0);
break;
case JSchemaType.Integer:
output = new JValue(1);
break;
case JSchemaType.Boolean:
output = new JValue(false);
break;
case JSchemaType.Null:
output = JValue.CreateNull();
break;
default:
output = null;
break;
}
return output;
}
private static string LowerCaseFirstChar(string name)
{
return name.Substring(0, 1).ToLower() + name.Substring(1);
}
then, your calling code would be:
var sampleJsonContent = yourJSchema.GenerateJsonSample().ToString();
... that is after all its properties - including its value - are updated?
The use-case is a Task that
"collects" items into an ObservableList which is the result of the call method
the list should be set as value when the task is "finished", no matter if normally or cancelled
A snippet of the Task implementation (complete example at end):
#Override
protected ObservableList<Rectangle> call() throws Exception {
ObservableList<Rectangle> results = FXCollections.observableArrayList();
for (int i=0; i<=count; i++) {
// do fill list
//...
try {
Thread.sleep(200);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
// do update value on cancelled
updateValue(results);
break;
}
}
}
return results;
}
It's intended usage:
bind the itemsProperty of a tableView to the valueProperty
unbind on "finished"
My approach was to listen to its state property and unbind on state changes to SUCCEEDED or CANCELLED. The former works just fine, the latter doesn't because at the time of receiving the cancelled, the value is not yet updated and consequently the items not set.
// working ... but when to unbind?
table.itemsProperty().bind(task.valueProperty());
task.stateProperty().addListener((src, ov, nv) -> {
if (Worker.State.SUCCEEDED == nv ) {
// this is fine because implementation in TaskCallable first
// updates the value (with the result it got from T call())
// then updates state
LOG.info("succeeded" + task.getValue());
table.itemsProperty().unbind();
} else if (Worker.State.CANCELLED == nv) {
LOG.info("receiving cancelled " + task.getValue());
// can't unbind here, value not yet updated
// table.itemsProperty().unbind();
}
});
So in case of cancelled, this leaves me with either a property that's still bound or an empty table. Feels like I'm doing something wrong. Or core Task impl is not as useful as expected? It would mean that we simply can't bind to the value property (nor any of the others like progress) due to being unable to safely cleanup (using table items here is just an example, because it's easy to see, same for all types of properties).
Question is, how to do it correctly/overcome the limitation?
The complete example:
public class TaskValueBinding extends Application {
private Parent createListPane() {
Task<ObservableList<Rectangle>> task = createListTask();
Thread thread = new Thread(task);
thread.setDaemon(true);
TableView<Rectangle> table = new TableView<>();
TableColumn<Rectangle, Double> xCol = new TableColumn<>("X");
xCol.setCellValueFactory(new PropertyValueFactory<>("x"));
TableColumn<Rectangle, Double> yCol = new TableColumn<>("Y");
yCol.setCellValueFactory(new PropertyValueFactory<>("y"));
table.getColumns().addAll(xCol, yCol);
// working ... but when to unbind?
table.itemsProperty().bind(task.valueProperty());
task.stateProperty().addListener((src, ov, nv) -> {
if (Worker.State.SUCCEEDED == nv ) {
// this is fine because implementation in TaskCallable first
// updates the value (with the result it got from T call())
// then updates state
LOG.info("succeeded" + task.getValue());
table.itemsProperty().unbind();
} else if (Worker.State.CANCELLED == nv) {
LOG.info("receiving cancelled " + task.getValue());
// can't unbind here, value not yet updated
// table.itemsProperty().unbind();
}
});
Label messageLabel = new Label("Message: ");
Label message = new Label();
message.textProperty().bind(task.messageProperty());
Label progressAsText = new Label();
Label progressLabel = new Label("Progress: ");
progressAsText.textProperty().bind(task.progressProperty().asString());
ProgressBar progress = new ProgressBar();
progress.progressProperty().bind(task.progressProperty());
Button start = new Button("Start");
start.setOnAction(e -> {
start.setDisable(true);
thread.start();
});
Button cancel = new Button("Cancel");
cancel.setOnAction(e -> task.cancel());
cancel.disableProperty().bind(task.runningProperty().not());
int row = 0;
GridPane grid = new GridPane();
grid.add(table, 0, row++, 20, 1);
grid.add(messageLabel, 0, row);
grid.add(message, 1, row++);
grid.add(progressLabel, 0, row);
grid.add(progressAsText, 1, row++);
grid.add(progress, 0, row++, 2, 1);
grid.add(start, 0, row);
grid.add(cancel, 1, row++);
return grid;
}
private Task<ObservableList<Rectangle>> createListTask() {
Task<ObservableList<Rectangle>> task = new Task<ObservableList<Rectangle>>() {
#Override
protected ObservableList<Rectangle> call() throws Exception {
updateMessage("Creating Rectangles ...");
ObservableList<Rectangle> results = FXCollections.observableArrayList();
String message = "finished";
int count = 10;
for (int i=0; i<=count; i++) {
if (isCancelled()) {
updateValue(results);
// when do we get here?
message = "cancelled";
break;
}
Rectangle r = new Rectangle(10, 10);
r.setX(10 * i);
results.add(r);
updateProgress(i, count);
// Now block the thread for a short time, but be sure
// to check the interrupted exception for cancellation!
try {
Thread.sleep(200);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateValue(results);
message = "interrupted";
break;
}
}
}
updateMessage(message);
return results;
}
};
return task;
}
#Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createListPane()));
stage.setTitle(FXUtils.version());
stage.show();
}
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("unused")
private static final Logger LOG = Logger
.getLogger(TaskValueBinding.class.getName());
}
Cancelling the task immediately triggers an update of the state property. If canceled from the application thread Platfrom.runLater is not used for this purpose but the call of the cancel method updates the state immediately. This results in the state being changed before any updateValue call updates the value property using Platform.runLater.
Task is not designed to allow partial results so you need to implement custom logic to accommodate for this. Depending on your needs you could subclass Task to trigger a custom event when the task completes in any way.
public abstract class PartialResultTask<T> extends Task<T> {
// handler triggered after last change of value
private Runnable onDone;
public Runnable getOnDone() {
return onDone;
}
public void setOnDone(Runnable onDone) {
this.onDone = onDone;
}
protected abstract T calculateResult() throws Exception;
private void onDone() {
if (onDone != null) {
Platform.runLater(onDone);
}
}
#Override
protected final T call() throws Exception {
try {
T result = calculateResult();
updateValue(result); // update value to the final value
onDone();
return result;
} catch (Exception ex) {
onDone();
throw ex;
}
}
}
private PartialResultTask<ObservableList<Rectangle>> createListTask() {
PartialResultTask<ObservableList<Rectangle>> task = new PartialResultTask<ObservableList<Rectangle>>() {
#Override
protected ObservableList<Rectangle> calculateResult() throws Exception {updateMessage("Creating Rectangles ...");
ObservableList<Rectangle> results = FXCollections.observableArrayList();
int count = 10;
for (int i = 0; !isCancelled() && i <= count; i++) {
Rectangle r = new Rectangle(10, 10);
r.setX(10 * i);
results.add(r);
updateProgress(i, count);
// Now block the thread for a short time, but be sure
// to check the interrupted exception for cancellation!
try {
Thread.sleep(200);
} catch (InterruptedException interrupted) {
}
}
updateMessage(isCancelled() ? "canceled" : "finished");
return results;
}
};
return task;
}
task.setOnDone(() -> {
table.itemsProperty().unbind();
});
task.stateProperty().addListener((src, ov, nv) -> {
if (Worker.State.SUCCEEDED == nv) {
// this is fine because implementation in TaskCallable first
// updates the value (with the result it got from T call())
// then updates state
LOG.info("succeeded" + task.getValue());
} else if (Worker.State.CANCELLED == nv) {
LOG.info("receiving cancelled " + task.getValue());
}
});
I have this C# method is asp.net webapi :
public IHttpActionResult Definitions()
{
var words = db.Words
.Where(w => w.Name == "abandon")
.AsNoTracking()
.ToList();
foreach (var word in words)
{
HttpResponse<string> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/" + word.Name)
.header("X-Mashape-Key", "xxx")
.header("Accept", "application/json")
.asJson<string>();
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(response.Body);
var results = rootObject.results;
foreach (var result in results)
{
if (!(from d in db.WordDefinitions where d.Definition == result.definition select d).Any())
{
var pos = 0;
switch (result.partOfSpeech)
{
case "noun":
pos = 1;
break;
case "verb":
pos = 2;
break;
case "adjective":
pos = 3;
break;
case "Adverb":
pos = 4;
break;
default:
pos = 5;
break;
}
var definition = new WordDefinition()
{
WordId = word.WordId,
Definition = result.definition,
PosId = pos
};
db.WordDefinitions.Add(definition);
}
db.SaveChanges();
}
}
return Ok();
}
The code runs from start to finish. When I put a breakpoint on db.SaveChanges() I see it reaching that point multiple times and I see that definition is populated.
But when I check the database there's nothing added.
Is there a way that I can add some checks that might point me to what is going wrong? I suspected there was an exception but then I think not as the code keeps running right to the end of the method.
Try doing that db.SaveChanges after the complete lists gets added to WordDefinitions.. I mean after the scope of outer foreach.. Its better to have that line of code outside the scope because each time it will hit the db and save your data which will relatively take some more time when compared to doing like this...
Code:
public IHttpActionResult Definitions()
{
var words = db.Words
.Where(w => w.Name == "abandon")
.AsNoTracking()
.ToList();
foreach (var word in words)
{
HttpResponse<string> response = Unirest.get("https://wordsapiv1.p.mashape.com/words/" + word.Name)
.header("X-Mashape-Key", "xxx")
.header("Accept", "application/json")
.asJson<string>();
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(response.Body);
var results = rootObject.results;
foreach (var result in results)
{
if (!(from d in db.WordDefinitions where d.Definition == result.definition select d).Any())
{
var pos = 0;
switch (result.partOfSpeech)
{
case "noun":
pos = 1;
break;
case "verb":
pos = 2;
break;
case "adjective":
pos = 3;
break;
case "Adverb":
pos = 4;
break;
default:
pos = 5;
break;
}
var definition = new WordDefinition()
{
WordId = word.WordId,
Definition = result.definition,
PosId = pos
};
db.WordDefinitions.Add(definition);
}
}
}
db.SaveChanges();
return Ok();
}
I read large json file, change certain things and then write it back to disk:
using (var reader = new StreamReader(filePath))
{
var log = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
//log = UpdateOneLog(log);
using (var writer = new StreamWriter(updateFilePath))
{
log.WriteTo(new JsonTextWriter(writer));
writer.Close();
}
reader.Close();
}
or even
JObject o1 = JObject.Parse(File.ReadAllText(inputFile));
File.WriteAllText(outputFile, o1.ToString());
Weird things happen for certain files and I believe it has something to do with file size. The date time should be startedDateTime":"2013-01-17T11:00:40.000-06:00" but it gets written to the file as startedDateTime":"2013-01-17T11:00:40-06:00" (note that fractions of the second "000" is missing). I even commented out my update logic as shown above. All I am doing is reading file and writing it back but the date gets garbled..
Am I doing something wrong?
-Stan
For reason still not clear for me (this is probably a bug), Json.Net sometimes incorrectly parses the millisecond portion of the date/time. So, for example in the string "2013-01-17T11:00:40.230-06:00" the millisecond portion "230" gets droped and the string becomes "2013-01-17T11:00:40-06:00" which is invalid. The workaround that I found is to loop through all tokens when saving and replace millisecond to some value as shown below.
[TestMethod]
public void LoadAndSave()
{
var directory = #"..\..\Files";
var inputFile = Path.Combine(directory, "LargeFile.har");
var outputFile = Path.Combine(directory, "LargeFileResult.har");
if (File.Exists(outputFile))
File.Delete(outputFile);
StreamWriter sw = null;
JsonTextWriter jTextWriter = null;
StreamReader sr = null;
JsonTextReader jTextReader = null;
try
{
sw = new StreamWriter(outputFile);
jTextWriter = new JsonTextWriter(sw);
sr = new StreamReader(inputFile);
jTextReader = new JsonTextReader(sr);
while (jTextReader.Read())
{
var tokenType = jTextReader.TokenType;
var tokenValue = jTextReader.Value;
var tokenString = jTextReader.Value as string;
switch (tokenType)
{
case JsonToken.Boolean:
case JsonToken.Bytes:
case JsonToken.Float:
case JsonToken.Integer:
case JsonToken.String:
jTextWriter.WriteValue(tokenValue);
break;
case JsonToken.Comment:
jTextWriter.WriteComment(tokenString);
break;
case JsonToken.Date:
DateTime date = (DateTime)tokenValue;
DateTime dateWrite = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 100, date.Kind);
jTextWriter.WriteValue(dateWrite);
break;
case JsonToken.EndArray:
jTextWriter.WriteEndArray();
break;
case JsonToken.EndConstructor:
jTextWriter.WriteEndConstructor();
break;
case JsonToken.EndObject:
jTextWriter.WriteEndObject();
break;
case JsonToken.None:
break;
case JsonToken.Null:
jTextWriter.WriteNull();
break;
case JsonToken.PropertyName:
jTextWriter.WritePropertyName(tokenString);
break;
case JsonToken.Raw:
jTextWriter.WriteRaw(tokenString);
break;
case JsonToken.StartArray:
jTextWriter.WriteStartArray();
break;
case JsonToken.StartConstructor:
jTextWriter.WriteStartConstructor(tokenString);
break;
case JsonToken.StartObject:
jTextWriter.WriteStartObject();
break;
case JsonToken.Undefined:
jTextWriter.WriteUndefined();
break;
default:
break;
}
}
}
finally
{
jTextReader.Close();
sr.Close();
jTextWriter.Close();
sw.Close();
}
I've checked all the articles I could on this, and I can't figure out how to fix this.
I'm writing an app that will take the information from a picker (which has two columns) and populate that into a label after a button is pressed. There are no crashes or anything. The only thing in the log is a line that says:
Unknown class ***PickerView in Interface Builder file.
I've attempted clearing the build and 4 other suggestions I found searching around, and I can't get rid of that. PickerView is in the compile sources.
Here is the code for the label updating (just ignore what I commented out, the spacing on iPhone vs the xib were different):
-(IBAction)buttonPressed
{
NSInteger jobRow = [doublePicker selectedRowInComponent:kJobsList];
NSInteger hourRow = [doublePicker selectedRowInComponent:kHoursList];
NSString *job = [jobTypes objectAtIndex:jobRow];
NSString *hour = [hoursTypes objectAtIndex:hourRow];
NSString *message = [[NSString alloc] initWithFormat:#"%# %#", job, hour];
int /*one=0, two=0,*/ three=0, four=0, five=0, six=0;
bool done = YES;
while(!done)
{
/*if(one == 0)
{
label1.text = message;
one = 1;
done = NO;
break;
}
if(two == 0)
{
label2.text = message;
two = 1;
done = NO;
break;
}*/
if(three == 0)
{
self.label3.text = message;
[label3 setNeedsDisplay]; // This is a line of something I found online to try
three = 1;
done = NO;
break;
}
if(four == 0)
{
self.label4.text = message;
four = 1;
done = NO;
break;
}
if(five == 0)
{
self.label5.text = message;
five = 1;
done = NO;
break;
}
if(six == 0)
{
self.label6.text = message;
six = 1;
done = NO;
break;
}
}
}
Any suggestions?