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.
Related
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);
}
}
I am using aws_ai plugin and the response is in the form of
instance of Future<String>
I read the response as given below. I need to access specific value from json with key "confidence", how do I access it?
Future main1() async {
File sourceImagefile; //load source image in this File object
String accessKey = "",
secretKey = "",
region = "" ;
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
Future<String> labelsArray = rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
}else{
return "Enter Image";}
}
___________________________________
(later in widget build:)
___________________________________
onpressed(){
main1().then((labelsArray){
print("json value is: "+labelsArray);
});
}
the current result is :
json value is: Instance of 'Future<String>'
thanks for the help!
The reason you are getting the Instance of 'Future<String>' as a result is you are not waiting for the future to return and just getting the Future<String> object back refer this for more details:
The below code should solve your problem:
Future<String> futureFunction() async {
RekognitionHandler rekognition = new RekognitionHandler(accessKey, secretKey, region);
if(sourceImagefile !=null && targetImagefile !=null) {
var labelsArray = await rekognition.compareFaces(
sourceImagefile, targetImagefile);
print(labelsArray);
return labelsArray.toString();
} else {
return "enter image";
}
}
I want to get object companies from localStorage if exist and
return it
and go to server and update companies in localStorage
if localStorageCompanies is empty i need to subscribe the one who
called the
function to get the result from the server, hot i do it?
and how i exeute this code:
localStorage.setItem('companies',JSON.stringify(res.result));
After this code:
if(!localStorageCompanies){
return res;
}
getCompanies(): any {
const localStorageCompanies = localStorage.getItem('companies');
this.http.get(environment.apiUmbracoUrl+'home/GetCompanies').subscribe(
res => {
//this.sharedService.turnOnLoader();
if(res.rc == 0){
localStorage.setItem('companies',JSON.stringify(res.result));
if(!localStorageCompanies){
return res;
}
}
});
if(localStorageCompanies){
return {rc:1,result:JSON.stringify(localStorageCompanies)};
}
}
I am having trouble trying to retrieve large datasets from Azure TableStorage. After several attempts at trying to get it in one go I have given up and am now using the TableContinuation Token, which is now not getting Deserialized correctly.The object is getting created but all the Next... values (i.e. NextRowKey, NextPartitionKey, etc are NULL, when the in stringresponse that gets created you can see the values it should be populating with...
The class I am passing contains a list of objects and the token
public class FlorDataset
{
public List<FlorData> Flors { get; set; }
public TableContinuationToken Token { get; set; }
}
The controller code is not exactly rocket science either....
[HttpGet, Route("api/list/{token}")]
public IHttpActionResult FindAll(string token)
{
try
{
TableContinuationToken actualToken = token == "None"
? null
: new TableContinuationToken()
{
NextPartitionKey = NextPartition,
NextRowKey = token,
NextTableName = NextTableName
};
var x = Run(actualToken);
Flors = x.Flors;
actualToken = x.Token;
NextTableName = actualToken.NextTableName;
NextPartition = actualToken.NextPartitionKey;
return Flors != null
? (IHttpActionResult)new IsoncOkResult<FlorDataset>(x, this)
: NotFound();
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
return NotFound();
}
}
private FlorDataset Run(TableContinuationToken token)
{
return _repo.GetAllByYear("2016", token) as FlorDataset;
}
The calling code, which calls my fairly standard Web API 2 Controller is:
do
{
try
{
HttpResponseMessage response = null;
if (string.IsNullOrEmpty(token.NextRowKey))
{
response = await client.GetAsync("api/list/None");
}
else
{
response = await client.GetAsync($"api/list/{token.NextRowKey}");
}
if (response.IsSuccessStatusCode)
{
var stringresponse = await response.Content.ReadAsStringAsync();
var ds = JsonConvert.DeserializeObject<FlorDataset>(stringresponse);
token = ds.Token;
Flors.AddRange(ds.Flors);
}
else
{
token = null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
token = null;
}
} while (token != null);
Okay, this is not the greatest solution, but it's the only thing that works so far in case anyone else is trying the same and stumbling across my question....
In the calling code bit you do a horrible bit of string replacement before you do the deserialisation.... I actually feel dirty just posting this, so if anyone comes up with a better answer, please feel free to share.....
if (response.IsSuccessStatusCode)
{
var stringresponse = await response.Content.ReadAsStringAsync();
stringresponse = stringresponse.Replace(">k__BackingField", "");
stringresponse = stringresponse.Replace("<", "");
var ds = JsonConvert.DeserializeObject<FlorDataset>(stringresponse);
token = ds.Token;
Flors.AddRange(ds.Flors);
}
Not nice, not pretty, but does work!!!! :-D Going to wash my fingers with bleach now!!!
I am building a WP8 app that downloads images using HttpClient in a background task. My problem is that some images are not downloaded no matter how much time I wait for them to finish. The image sizes are a few megabytes at maximum.
The code I use to download images:
internal static async Task<bool> Download_Wallpaper(string image_url, string file_name, string destination_folder_name)
{
try
{
using (var client = new HttpClient())
{
// 12MB max images
client.Timeout = TimeSpan.FromSeconds(5);
client.MaxResponseContentBufferSize = DeviceStatus.ApplicationMemoryUsageLimit / 2;
//client.Timeout = TimeSpan.FromSeconds(5);
byte[] image_byte_arr;
try
{
/* var requestMessage = new HttpRequestMessage( HttpMethod.Get, image_url );
var responseMessage = await client.SendAsync((requestMessage));
// byte array of image
image_byte_arr = await responseMessage.Content.ReadAsByteArrayAsync();
*/
// byte array of image
image_byte_arr = await client.GetByteArrayAsync(image_url);
}
// Could not download
catch (OutOfMemoryException X)
{
GC.Collect();
return false;
}
var folder = await StorageFolder.GetFolderFromPathAsync(destination_folder_name);
// Create file
StorageFile file = await folder.CreateFileAsync(file_name, CreationCollisionOption.ReplaceExisting);
using (var write_stream = await file.OpenStreamForWriteAsync())
{
write_stream.Write(image_byte_arr, 0, image_byte_arr.Length);
}
Console.WriteLine(DeviceStatus.ApplicationCurrentMemoryUsage);
return true;
}
}
catch (HttpRequestException X)
{
Console.WriteLine(X);
return false;
}
catch (OutOfMemoryException X)
{
GC.Collect();
return false;
}
catch (Exception X)
{
Console.WriteLine(X);
return false;
}
}
This is an example image that fails to download: https://upload.wikimedia.org/wikipedia/commons/9/95/Tracy_Caldwell_Dyson_in_Cupola_ISS.jpg
In my experience all wikimedia images fail to download for some reason.
I see no way of tracking download progress using HttpClient. Is there a way to do so?
Edit: It seems that setting the timeout does not have any function. The HttpRequestException is not thrown after 5 seconds.
Edit2: I tried a different approach, the one that anonshankar suggested. With that method the code would get stuck at the line:
byte[] img = response.Content.ReadAsByteArrayAsync();
So the HttpResponse arrives, but somehow the bytes could not be read out, no matter how much time I gave it. How could this even happen? The hard part is getting the response, reading out the bytes should be simple.
Again, this only happens with some images, most of them downloads correctly. One example is mentioned above.
I have modified my image downloader code, so that it times out after a few seconds. Here is my final code:
internal static async Task<bool> Download_Wallpaper(string image_url, string file_name, string destination_folder_name)
{
try
{
using (var client = new HttpClient())
{
// prevent running out of memory
client.MaxResponseContentBufferSize = DeviceStatus.ApplicationMemoryUsageLimit / 3;
byte[] image_byte_arr = null;
using (CancellationTokenSource cts = new CancellationTokenSource())
{
var task = Task.Factory.StartNew(() =>
{
try
{
image_byte_arr = client.GetByteArrayAsync(image_url).Result;
}
catch (AggregateException X)// Handling read errors, usually image is too big
{
Console.WriteLine(X.Message);
foreach (var v in X.InnerExceptions)
Console.WriteLine(v.Message);
image_byte_arr = null;
}
}, cts.Token);
bool finished_in_time = task.Wait(TimeSpan.FromSeconds(5));
if (!finished_in_time)// Timeout
{
cts.Cancel();
task.Wait();
return false;
}
else if (image_byte_arr == null)// Read error
{
return false;
}
}
var folder = await StorageFolder.GetFolderFromPathAsync(destination_folder_name);
// Create file
StorageFile file = await folder.CreateFileAsync(file_name, CreationCollisionOption.ReplaceExisting);
using (var write_stream = await file.OpenStreamForWriteAsync())
{
write_stream.Write(image_byte_arr, 0, image_byte_arr.Length);
}
Console.WriteLine(DeviceStatus.ApplicationCurrentMemoryUsage);
return true;
}
}
catch (HttpRequestException X)
{
Console.WriteLine(X);
return false;
}
catch (OutOfMemoryException X)
{
GC.Collect();
return false;
}
catch (Exception X)
{
Console.WriteLine(X);
return false;
}
}
Any improvement suggestions are welcome, and I still don't understand why does the method HttpContent.ReadAsByteArrayAsync() gets stuck.
Just try out this snippet which worked for me.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("give the url");
byte[] img = response.Content.ReadAsByteArray();
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
writer.WriteBytes(img);
await writer.StoreAsync();
BitmapImage b = new BitmapImage();
b.SetSource(randomAccessStream);
pic.Source = b; //(pic is an `<Image>` defined in the `XAML`
Hope it helps!