I have an "Update" function in which the end isn't executed, then I use the function "Console.WriteLine" to know where the function is interrupted. Here is the Udate function:
async Task Update()
{
count++;
try
{
List<string> cmds = new List<string>();
if (Ev3Messaging.IsConnected())
{
Tuple<string, string> response = null;
Console.WriteLine("Test1"); // Displayed
try
{
response = await Ev3Messaging.ReceiveText(true);
}
catch(Exception ex)
{
Console.WriteLine(ex.Source + ": " + ex.Message); // Not displayed
}
Console.WriteLine("Test2"); // Not displayed
while (response != null)
{
Console.WriteLine("Test2: " + response.Item2);
string[] list = response.Item2.Split(';');
foreach (string cmd in list)
cmds.Add(cmd);
response = await Ev3Messaging.ReceiveText(false);
}
}
Canvas canvas = _screenSV.Holder.LockCanvas();
if (canvas != null)
{
foreach (string cmd in cmds)
ExecuteCommand(cmd, canvas);
_screenSV.Holder.UnlockCanvasAndPost(canvas);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Source + ": " + ex.Message);
}
}
The Update function is called each 100ms by the following code:
var timer = new System.Threading.Timer((e) =>
{
RunOnUiThread(async () => await Update());
}, null, 0, 100);
It displays "Test1", but it displays neither the exception (no problem in the "EV3Messaging.ReceiveText" function), nor "Test2" (function interrupted before reaching "ShowAlert("Test2");" )
How is it possible ?
If you want me to post the "Ev3Messaging.ReceiveText" function, please ask me. I didn't post it since it is big enough, and I just want to know how is it possible to get this problem...
Thanks in advance.
Related
Have a quote application, which we fill the data and send from source system to receiver system. That receiver system will be sending status of that quote(Success/Failed) as Acknowledgement to source system. We have an option to revise the same quote. whenever we revise the quote, the Status is inherited from previous quote. we need to clear the latest revision's status. which is not happening. but it clears previous revision's status. Could anyone help me.
if (plm == "PLM")
{
if (id.Revision != 0)
{
var javascriptSerializer = new JavaScriptSerializer();
var urn = line.CustomProperties?.FirstOrDefault(k => k.Key.ToLower() == "urn")?.Value;
oRecordLog.WriteToLogFile("Updating DBValue");
//initilizing document store object to query the documents from database.
IDocumentStore ravenDB = new DocumentStore { Url = "http://localhost:8072", DefaultDatabase = "Configit.Quote" }.Initialize();
try
{
List<Document> docs;
using (var session = ravenDB.OpenSession())
{
oRecordLog.WriteToLogFile("Opened RavenDB session");
//getting the URN value.
var javaScriptSerializer = new JavaScriptSerializer();
string urnString = urn;
ModelKeyValuePair urnKeyValue = new ModelKeyValuePair();
urnKeyValue.Key = "URN";
urnKeyValue.Value = javaScriptSerializer.Serialize(urnString);
//wait for 5 seconds before the next query
docs = session.Query<Document>().Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(5))).Where(x => x.Lines.Any(l => l.Properties.Any(ID => ID == urnKeyValue))).ToList();
try
{
oRecordLog.WriteToLogFile("docs " + docs.Count);
//processing one by one document from RavenDB.
foreach (var doc in docs)
{
string quoteGuid = null;
if (doc.LinesCount > 0)
{
int lineCnt = doc.LinesCount;
// processing each line in the docuement getting the quoteID
foreach (var quoteline in doc.Lines)
{
if ((quoteline.Properties.ContainsKey("Urn")) || (quoteline.Properties.ContainsKey("URN")) || (quoteline.Properties.ContainsKey("urn")))
{
Guid lGuid = quoteline.LineId;
var quote_ForID = _quoteStorage.GetQuote(new QuoteRevisionId(id.QuoteId, id.Revision));
var urn_ForQuoteId = quoteline.Properties?.FirstOrDefault(k => k.Key == "URN")?.Value;
if (GetUniqueRefnum(quote_ForID, quoteline) == urn_ForQuoteId)
{
quoteGuid = doc.DocumentId.ToString();
oRecordLog.WriteToLogFile("quoteGuid " + quoteGuid);
var TransferStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "TransferStatus");
var PLMDetailedStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "PLMDetailedStatus");
TransferStatus.Value = "";
PLMDetailedStatus.Value = "";
}
}
}
}
else
{
oRecordLog.WriteToLogFile("Quote ID not found");
}
}
session.SaveChanges();
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
}
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
else
{
oRecordLog.WriteToLogFile("This is new quote");
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
}
I am using Kendo grid and I have stopped the grid from saving duplicate values as follows in create method:
var results = new List<ProviderTypeMasterViewModel>();
try
{
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Start");
foreach (var ProviderTypeMaster in ProviderTypeMasterList)
{
TblProviderTypeMaster ptm = new ProviderTypeMasterViewModel().ToModel(ProviderTypeMaster);
var provd = _context.TblProviderTypeMasters.Where(p => p.ProviderTypeName == ProviderTypeMaster.ProviderTypeName).ToList();
if (provd != null && provd.Count() == 0)
{
if (ProviderTypeMasterList != null && ModelState.IsValid)
{
string userID = GetUserID();
providerTypeMasterService.SaveProviderTypeMaster(ProviderTypeMaster, userID);
}
}
else
{
duplicate = true;
//Session["ErrMsg"] = "Already Exists";
//return RedirectToAction("ProviderType_Read", "ProviderTypeMasters");
}
}
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Complete");
}
catch (Exception e)
{
_logger.LogError("ProviderTypeMastersController ProviderType_Create Failed - " + e.Message);
}
return Json(results.ToDataSourceResult(request, ModelState));
And in the read method I have displayed the error message to the user as follows
try
{
if (duplicate == true)
{
TempData["ErroMsg"] = "Already Exists";
}
_logger.LogInformation("In ProviderTypeMastersController ProviderType_Read");
return Json(providerTypeMasterService.ListProviderTypeMaster().ToDataSourceResult(request));
}
catch (Exception e)
{
_logger.LogError("ProviderTypeMastersController ProviderType_Read Failed - " + e.Message);
}
return View();
The duplication process has stopped. But I am unable to show the error message to the user. Can anyone let me know what I should do where I have gone wrong. I have tried using ViewBag,ViewData,TempData.
This is my View
<div>
if (TempData["ErroMsg"] != null)
{
<p>#TempData["ErroMsg"].ToString()</p>
}
you can use DataBinding() and DataBound() function of kendo grid...these functions call in client side after Read method on server side..for example you can set a field and decision with this field
I'm stuck with a problem. I need help...
In general, I have an ASP.NET MVC 5 project. When a user clicks on "Save" button, I run some code in a new created task. I need to know the result of operation, so I return the instance of my class ChangesMade. Then I serialze the object to JSON format and pass to a view. Then I check if result is true, I open an url in a new window.
So, in my controller I have the following:
public async Task<ActionResult> Save(here some parameters)
{
var changes = await _model.SaveAsync(some parameters);
return NewtownJson(changes);
}
The main saving logic is the following:
public async Task<ChangesMade> SaveAsync(some parameters here)
{
var data = (await _model.GetData(some parameter)).ToList();
// create a task of ChangesMade that contains public bool property MemoAdded
// that I need to pass to a view to know the result of operation
var task = Task<ChangesMade>.Factory.StartNew(() =>
{
ChangesMade changes = new ChangesMade();
try
{
using (var tr = new TransactionScope())
{
// some code here omitted for simplicity…
// if (someCondition == true) changes.MemoAdded = true;
tr.Complete();
}
return changes;
}
catch (Exception ex)
{
throw ex;
}
});
try
{
task.Wait();
}
catch (AggregateException ex)
{
string msg = "";
msg= ex.Flatten().InnerExceptions
.Where(e => e != null)
.Select(e => e.Message)
.Aggregate(msg, (current, message) => current + " " + message + ";")
.TrimEnd(';');
throw new Exception(msg);
}
return task.Result;
}
I publish the project on two sites on IIS. The first works fine. But the second doesn't - by some reason, it always returns changes.MemoAdded false to the view.
I can't find out a reason of that. I don't have a clue what to do ...
I have this code to load and count data from API server;
class TestNetWork
{
private Task taskFillPicker;
private List<CityItemDB> itemsCity;
private CustomPicker cpCity;
public async Task FillPicker()
{
try {
JObject res = await SuperFUNC.GET_CITY_ACTIVE_SENDER();
if(res == null){
//null
}else{
string message = res["message"].ToString();
if(message.Equals("Success")){
itemsCity.Clear();
cpCity.Items.Clear();
JArray data = (JArray)res["data"];
int count = data.Count;
for (int i = 0; i < count; i++) {
CityItemDB node = new CityItemDB();
node.cityId = Int32.Parse(data[i]["cityId"].ToString());
node.cityName = data[i]["cityName"].ToString();
itemsCity.Add(node);
cpCity.Items.Add(node.ToString());
}
}else{
//null
}
}
} catch (Exception ex) {
Debug.WriteLine (TAG + " : " + ex.StackTrace);
}
}
public TestNetWork()
{
this.itemsCity = new List<CityItemDB> ();
this.cpCity = new CustomPicker {
HeightRequest = 40,
TextColor = Color.FromHex("#5a5a5a"),
Title = "City Choose",
};
taskFillPicker = FillPicker ();
Debug.WriteLine (COUNT + " : " + itemsCity.Count);
}
}
But console print me COUNT : 0, I'm sure code get and parse json from internet is correct, picker show full data but List<CityItemDB> itemsCity count 0.
Thank for read, sorry my english not good!
You need to await the task, otherwise execution might continue before FillPicker has completed:
taskFillPicker = await FillPicker ();
As this code is in a constructor where await is not possible, I suggest moving it to a separate async method:
public async Task Init()
{
taskFillPicker = await FillPicker ();
Debug.WriteLine (COUNT + " : " + itemsCity.Count);
}
You have to write a little bit more code to construct the object now:
var n = new TestNetWork();
await n.Init();
So I am trying to add an async progress bar on a really slow and long query that inserts a bunch of rows to a database. My implementation is based off this example: http://blog.janjonas.net/2012-01-02/asp_net-mvc_3-async-jquery-progress-indicator-long-running-tasks
Here is the javascript code for the progress bar
function updateMonitor(taskId, status) {
$("#" + taskId).html("Task [" + taskId + "]: " + status);
}
//other code
if (doSend == true) {
$.post("/SendBatch/HandleBatchRequest", {
//other code
},
function (taskId) {
// Init monitors
//breakpoint here does not stop it, it never enters this somehow?
$("#monitors").append($("<p id='" + taskId + "'/>"));
updateMonitor(taskId, "Started");
// Periodically update monitors
var intervalId = setInterval(function () {
$.post("SendBatch/Progress", { id: taskId }, function (progress) {
if (progress >= 100) {
updateMonitor(taskId, "Completed");
clearInterval(intervalId);
} else {
updateMonitor(taskId, progress + "%");
}
});
}, 100);
}
,"html");
Then there is the DIV within the display part of the website
<div id="monitors"></div>
Here is how the controller looks
public SendBatchController
//some code
private static IDictionary<Guid, int> tasks = new Dictionary<Guid, int>();
public ActionResult HandleBatchRequest(
//some code
)
{
var taskId = Guid.NewGuid();
tasks.Add(taskId, 0);
var batchId = Guid.NewGuid().ToString("N");
var costd = cost.ToDecimal();
IEnumerable<BatchListModel> customers;
try
{
customers = new CustomerService(_customerRepository.Session).GetCustomers(
//some code
);
}
catch (Exception err)
{
return Json(err.Message);
}
if (doSend)
{
var sent = 0;
foreach (var c in customers)
{
try
{
var usr = _customerRepository.LoadByID(c.ID);
var message = new ComLog
{
//insertions to log
};
_comLogRepository.Save(message);
sent++;
//progress bar part inside here that is important comes here:
tasks[taskId] = sent;
}
catch (Exception e)
{
Log.WriteLine("ERR:" + e);
}
tasks.Remove(taskId);
}
return Json(taskId);
}
return Json(customers.Count() + " customers");
}
public ActionResult Progress(Guid id)
{
return Json(tasks.Keys.Contains(id) ? tasks[id] : 100);
}
This does not work. The process works in the background. It is only the div that never shows up and never gives any indication. I know this is a lot of code to read but I am really stuck and would love some input on how to fix this.
try change your updateMonitor function into this :
function updateMonitor(taskId, status) {
$("#monitors").html("Task [" + taskId + "]: " + status);
}