We have an JQuery Ajax call that will execute when a user is about to leave a page on a DNN module.
This error is being logged the whole time in the DNN logs.
How can I improve the error handling so that it doesn't log the whole time?
Here is the DNN log:
Here is the Front End Code on the Module :
$(window).on("beforeunload", function () {
ClearTempUserSessionWhenLeavePage();
});
function ClearTempUserSessionWhenLeavePage() {
if ($fromButtonEvent == false) {
var Url = $.fn.GetBaseURL() + 'DesktopModules/DNNCommon/API/Store/ClearTempUserSessionWhenLeavePage';
$.ajax({
url: Url,
type: 'GET',
async: true,
dataType: 'json',
success: function () {
},
error: function (x, y, z) {
}
}).promise().done(function () {
});
}
$fromButtonEvent = false;
}
We are inheriting the DNNApiController class on our DNNCommon class.
This is the C# method being called:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{
if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
{
System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
SessionManager.SetSessionObject("NewCreatedWebUser", null);
SessionManager.SetSessionObject("UserInfo", null);
SessionManager.SetSessionObject("NewCustomerCode", null);
}
}
I have attempted to add two different types of Try Catch clauses, but when I debug the code it won't hit the breakpoints and somehow it still logs the error in the DNN Admin logs. Is there perhaps a Try Catch in the DNNController class that is writing this error?
First attempt with Try Catch Clause with TaskCanceledException and TimeoutException:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{
try
{
if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
{
System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
SessionManager.SetSessionObject("NewCreatedWebUser", null);
SessionManager.SetSessionObject("UserInfo", null);
SessionManager.SetSessionObject("NewCustomerCode", null);
}
}
catch (Exception ex)
{
EventLogController logController = new EventLogController();
if (ex.InnerException is TimeoutException)
{
ex = ex.InnerException;
}
else if (ex is TaskCanceledException)
{
if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
{
ex = new TimeoutException("Timeout occurred");
logController.AddLog("Timout Occured - Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
}
}
logController.AddLog("Problem Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
}
}
Second attempt with a TaskCanceledException:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{
try
{
if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
{
System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
SessionManager.SetSessionObject("NewCreatedWebUser", null);
SessionManager.SetSessionObject("UserInfo", null);
SessionManager.SetSessionObject("NewCustomerCode", null);
}
}
catch (TaskCanceledException ex)
{
EventLogController logController = new EventLogController();
logController.AddLog("Task Cancelled Exception - Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
}
}
Related
I'm not quite understanding the exception handling in await-able tasks. I have a primary task that needs to complete and yield its result to dependent tasks. So, the primary task must complete first, then, the subsequent tasks can run asynchronously. If the initial/primary task fails and throws an exception, I need to handle the exception properly and exit the program. If the 2 dependent tasks hit any exceptions, I just need to report them properly. Two things are happening in the code below... 1) Task 2 and 3 are running synchronously (I want them to run asynchronously)... AND 2) if I uncomment the exception throw inside DoStringStuff, I will get the "Exception User-Unhandled" message and the program stops (and I want this exception to bubble up to the top like normal and simply be printed to the console). I'm missing some important semantics here. Any help in the right direction is much appreciated!
UPDATE:
I found the issue, if this will help anyone... I needed to declare all my tasks at the outset of the function (not dynamically). Below is the working code. The Exceptions (if any) will propagate up as expected.
await parent();
Console.ReadKey();
static async Task parent()
{
Console.WriteLine("start of parent");
string sResult;
try
{
sResult = MyTask1("1111");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return;
}
try
{
string result = await DoRemainingTasks(sResult);
Console.WriteLine();
Console.WriteLine(result);
}
catch(Exception ex)
{
Console.Write(ex.ToString());
}
Console.WriteLine("end of parent");
}
static async Task<string> DoRemainingTasks(string sResult)
{
Task<string> task2 = MyTask2(sResult);
Task<string> task3 = MyTask3("3333");
string t2Result = string.Empty;
string t3Result = string.Empty;
try
{
t2Result = await task2;
}
catch(Exception ex)
{
Console.WriteLine("Task 2 issue. Error = " + ex.Message);
}
try
{
t3Result = await task3;
}
catch (Exception ex)
{
Console.WriteLine("Task 3 issue. Error = " + ex.Message);
}
return "Remaining tasks done: " + t2Result + "... " + t3Result;
}
static Task<string> DoStringStuff(string s)
{
foreach (char c in s)
{
Console.Write(c);
Thread.Sleep(500);
}
Console.WriteLine();
return Task.FromResult(s);
}
static async Task<string> DoStringStuffAsync(string s)
{
return await Task.Run(() =>
{
foreach (char c in s)
{
Console.Write(c);
Thread.Sleep(500);
}
Console.WriteLine();
return s;
});
//throw new Exception($"task {s} failure");
}
static string MyTask1(string svar)
{
try
{
DoStringStuff(svar);
Console.WriteLine();
Console.WriteLine("task 1 done");
}
catch
{
throw;
}
return "2222";
}
static async Task<string> MyTask2(string svar)
{
return await Task.Run(async () =>
{
string s = await DoStringStuffAsync(svar);
return "task done for " + s;
});
}
static async Task<string> MyTask3(string svar)
{
return await Task.Run(async () =>
{
string s = await DoStringStuffAsync(svar);
return "task done for " + s;
});
}
I have a login page where the user credentials checks against a status response from a api. I've written a function that returns a future boolean from the check but my problem is that if the user puts the wrong info the first time all the times they try to log in after the function still comes back as false.
I've print the user input to the console and it shows that the old info was updated but still comes back as false.
Future boolean function:
bool loginCheck;
Future<bool>check() async{
try{
await fetchResponse().then((response){
if(response.status == "ok"){
return loginCheck = true;
}else {
return loginCheck = false;
}
});
}
catch (e){
print(e);
}
return loginCheck;
}
API response function:
Future <SubsonicResponse>fetchResponse() async{
try{
userClear();
loginUser();
var authresponse = await http.get(authURL);
if (authresponse.statusCode == 200){
var jsondata = jsonDecode(authresponse.body);
var data = apicallFromJson(jsondata);
var response = data.subsonicResponse;
return response;
} else{
}
}
catch (e){
print(e);
}
}
other functions:
void loginUser() {
serveraddress = _serveraddressController.text;
password = _passwordController.text;
username = _usernameController.text;
print(username);
print(password);
print(serveraddress);
}
void loginclear(){
_serveraddressController.clear();
_passwordController.clear();
_usernameController.clear();
}
void userClear(){
loginCheck = null;
serveraddress = null;
password = null;
username = null;
}
as you can see above I've tried clearing the user input vars before the request and it updates to the newest user input but still comes back false
Login button:
onPressed: () {
check().then((loginCheck){
print(loginCheck);
if(loginCheck == true){
loginclear();
return Get.toNamed('/home');
} else {
return showAlertDialog(context);
}
});
},
If the user puts the right info in the first time it works no problem.
You need to update the state of your variables using some sort of state management, i.e. Use setState() (or streams or what ever based on your use case) to update your variable.
Simply calling user clear will not work.
I am getting the following compilation error:
cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'
code
public class PondController : ApiController
{
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json(new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
You are trying to use code snippet from ASP.NET MVC in ASP.NET WebAPI controller. In WebAPI the results and methods have different signatures. Try following:
public JsonResult<object> Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json((object)new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } });
}
}
catch (Exception Ex)
{
}
return Json((object)new { success = false });
}
I am Trying to create a Windows Universal App with a Background Task.
I am trying to Write a Background task that Triggers Upon an Incoming bluetooth connection.
To prevent both the foreground and background from creating a connection. I am trying to implement the Same Mutex in Both the Foreground and Background.
When I read the Data from the Bluetooth Device I am getting the Following Error.
Object Synchronization method was called from unsynchronized block
To my Surprise this Error comes Occasionally . Am I missing Something ?
Here's My Code :
public sealed class RFBackgroundTask : IBackgroundTask
{
.... Variable declarations
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
Debug.WriteLine("RFComm Task Running");
hotwatchConnection = taskInstance.TriggerDetails as RfcommConnectionTriggerDetails;
socket = hotwatchConnection.Socket;
reader = new DataReader(socket.InputStream);
// n = new Notification(hotwatchConnection.RemoteDevice.HostName);
await Read();
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
if (ismutexReleased == false)
{
Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message);
connectionMutex.ReleaseMutex();
ismutexReleased = true;
}
}
finally
{
if (ismutexReleased == false)
{
Debug.WriteLine("Releasing Mutex 2");
connectionMutex.ReleaseMutex();
}
ismutexReleased = true;
}
deferral.Complete();
}
public IAsyncAction Read()
{
return Task.Run(async () =>
{
try
{
connectionMutex = new Mutex(false, CONNECTION_MUTEX_NAME);
// Attempt to wait for the mutex
var waitResult = connectionMutex.WaitOne();
if (waitResult)
{
Debug.WriteLine("Aquired Mutex Successfully");
}
// If the wait was not successful, fail the connect operation
if (!waitResult) { throw new TimeoutException(); }
if (reader != null)
{
uint length = 500;
reader.InputStreamOptions = InputStreamOptions.Partial;
uint len = await reader.LoadAsync(length);
String message = reader.ReadString(len);
Debug.WriteLine("Read " + message + " In the First Attemnpt");
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["COMMAND"] = message;
//if(!message.StartsWith("01"))
//{
// await ProcessCommand(message);
//}
}
reader.Dispose();
socket.Dispose();
socket = null;
if (waitResult == true)
connectionMutex.ReleaseMutex();
ismutexReleased = true;
Debug.WriteLine("Released Mutex successfully after reading data");
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
if (ismutexReleased == false)
{
Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message);
connectionMutex.ReleaseMutex();
ismutexReleased = true;
}
throw;
}
finally
{
if (ismutexReleased == false)
{
connectionMutex.ReleaseMutex();
Debug.WriteLine("Releasing Mutex");
}
ismutexReleased = true;
}
}).AsAsyncAction();
}
}
The Mutex must be released on the same thread that it was acquired.
When you await an async method you are returned to the same context, you are not guaranteed to be returned to the same thread.
Use a Semaphore instead.
i want to return JSON from my controller and get it in my view .this is my code, when i debug it . goes to my controller and get value but in my j query code nothing happen .when i debug my j query code by firebug it dos not run the function(data). what is wrong in my code ?i want get object of part-booklet from server. its a row of data and add this row to my Telerik mvc grid .thanks in advance
its my contoroller code:
#region dynamic_add_row_to_grid
private PartBooklet GetPartBooklet( int sparepart ) {
return _PartBookletService.GetList().Where(m => m.SparePartCode == sparepart).FirstOrDefault();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetItems( int sparepart ) {
var PartbookletList = this.GetPartBooklet(sparepart);
return Json(PartbookletList, JsonRequestBehavior.AllowGet);
}
#endregion
and its jquery code:
$("#btnadd").button().click( function () {
alert("button");
var sparepartcode = $("#SparePartCode").val();
alert( sparepartcode );
$.getJSON("../Shared/GetItems", { sparepart: sparepartcode }, function( data ) {
alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
}).error( function () {
alert("JSON call failed");
});
$( function () {
$.ajaxSetup({
error: function (jqXHR, exception) {
if ( jqXHR.status === 0 ) {
alert('Not connect.\n Verify Network.');
} else if ( jqXHR.status == 404 ) {
alert('Requested page not found. [404]');
} else if ( jqXHR.status == 500 ) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror' ) {
alert('Requested JSON parse failed.');
} else if ( exception === 'timeout' ) {
alert('Time out error.');
} else if ( exception === 'abort' ) {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});
$("#btnadd").button().click( function () {
//alert("button");
var sparepartcode = $("#SparePartCode").val();
$.ajax({
url: "/Shared/GetItem?sparepart=" + sparepartcode,
type: 'GET',
success: function(a, b, data) {
//alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
},
error: function(jqXHR, textStatus, errorThrown) {
alert("JSON call failed");
},
// other options and setup ...
});
});
Note that in a successful ajax request, it's the 3rd parameter that contains the actual data you need.