hello, those values cannot ever be null from the way im setting them app and also from the crash reports they are not null, they have a value, the crash comes later. some times this code doesnt crash. some times it does. even in the devices that crash it doesnt crash always. From what i understand my biggest problem is that i dont try catch inside the task and i loose exceptions because of that. I have added a try catch inside the task and now i see that even in my device thaat never crash sometimes i get an error about ssl. The correct way is to check all those values if they are null in the beggining of the function even if by the way are initialized always have value?
Exoskeletor
Posts
-
Can't catch NullReferenceException while explicitly defined for that -
Can't catch NullReferenceException while explicitly defined for thatoh i though it had a deeper meaning i didn't get :)
-
Can't catch NullReferenceException while explicitly defined for thatwhat means to be a Richard? :) i didnt get the joke
-
Can't catch NullReferenceException while explicitly defined for thatoh yes you are right, sorry i have used the wrong part of the code. i edit the question again. I cant reproduce the bug in my device, it is happening in around 2% of the devices that is being used, this code is from an app that is available from google play already
-
Can't catch NullReferenceException while explicitly defined for thatHello fellow members. Im trying to understand why my code is not catching NullReferenceException and i cant figure it out. I'm using this code to run async function
private async Task SearchMostLessViewsAsync(DateTime dateFrom, DateTime dateTo, int amountOfNumbersSelected, int frequencyOption, int fromDrawNumber, int toDrawNumber)
{
Microsoft.AppCenter.Analytics.Analytics.TrackEvent($"{typeof(FragmentDrawsNumbersFrequency).Name}.{nameof(SearchMostLessViewsAsync)}",
new Dictionary()
{
{nameof(dateFrom), dateFrom.ToString()},
{nameof(dateTo), dateTo.ToString()},
{nameof(amountOfNumbersSelected), amountOfNumbersSelected.ToString()},
{nameof(frequencyOption), frequencyOption.ToString()},
{nameof(fromDrawNumber), fromDrawNumber.ToString()},
{nameof(toDrawNumber), toDrawNumber.ToString()},
}
);
((MainActivity)Activity).DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle),
GetString(Resource.String.Common_SearchMessage));//ApplicationState.ChangeCancellationTokenSource(new CancellationTokenSource()); var task = Task.Run(async () => { var textResult = await SearchLeast(dateFrom, dateTo, amountOfNumbersSelected, frequencyOption, fromDrawNumber, toDrawNumber).ConfigureAwait(false); if (!string.IsNullOrEmpty(textResult)) { UpdateHistoryList(textResult); DatabaseFunctions.SaveHistoryList(HistoryList, Settings.DrawsNumbersFrequencyHistoryListViewKey); ((MainActivity)Activity).ShowSearchResults(textResult); } }, ApplicationState.GetCancellationToken()); // Pass same token to Task.Run. try { await task.ConfigureAwait(false); } catch (TaskCanceledException tce) { Console.WriteLine($"{nameof(TaskCanceledException)} thrown with message: {tce.Message}"); } catch (System.ObjectDisposedException ode) { Console.WriteLine($"{nameof(System.ObjectDisposedException)} thrown with message: {ode.Message}"); } catch (System.OperationCanceledException e)
-
Running Function from Task.Run with Cancellation Token gives infinite loopa general sample might not be the best solution for every situation. my code in the first post also is based on MS samples
-
Running Function from Task.Run with Cancellation Token gives infinite loopI was reading this today but it looks to me like a worst idea of having a task that can take a cancellation token so i will try to find more approaches on how to cancel task and its childrends
-
Running Function from Task.Run with Cancellation Token gives infinite loopthanks, this helped, i found the reason of that but now i see that if i cancel the task, all the already running functions will keep running. im not sure if the best approach is to add some if (token.iscancellationrequested) or to make all the functions to tasks that can take a token
-
Running Function from Task.Run with Cancellation Token gives infinite loopI have this function
private async Task SearchForAllNumbers(int num = -1)
{
if (num == -1)
DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle), GetString(Resource.String.Common_SearchMessage));
dates = DateFunctions.GetSelectedDates(DateFrom, DateTo);var list = string.Empty; var klirwseis = ", Κληρωσεις: "; if (num == -1) list = ListTextView.Text; else list = num.ToString(); var nums = list.Split(',').Select(Int32.Parse).ToList(); if (seperateCheckBox.Checked) { DisplayLoadingMessage(false); seperateCheckBox.Checked = false; for (int k = 0; k < nums.Count; k++) { await SearchForAllNumbers(nums\[k\]); } return -1; } var totalCoutner = 0; for (int datesPos = 0; datesPos <= dates.Count; datesPos++) { ... Do some calculations } HistoryTextView.Text = "Ημερομηνία: " + dates\[datesPos\] + ", Λίστα: " + list + ", Κληρώθηκε: " + totalCoutner + " φορές" + HistoryTextView.Text; if (showListsCheckBox.Checked) HistoryTextView.Text = klirwseis + HistoryTextView.Text; } DisplayLoadingMessage(false); HistoryTextView.Text = ".\\n" + HistoryTextView.Text; return totalCoutner; return 0; }
And i want to be able to cancel it when its running so i have created this function
private async Task SearchFoNumbersAsync()
{
ActiveCancellationTokenSource = new CancellationTokenSource();
DrawResultsTypeEnum searchType = (DrawResultsTypeEnum)ShowResultsSpinnerPosition;var task = Task.Run(async () => { if (searchType == DrawResultsTypeEnum.AllNumbers) await SearchForAllNumbers(); else if (searchType == DrawResultsTypeEnum.AnyWinningCombination) await SearchAnyWinningCombination(); SaveHistory(); }, ActiveCancellationTokenSource.Token); // Pass same token to Task.Run. try { await task; } catch (System.OperationCanceledException e) {
-
Proper Error handlingOh thank you. Any improvement is highly welcome, i have refactor it to:
public static string StoredDatesList
{
get => Preferences.Get(nameof(StoredDatesList), string.Empty);
set => Preferences.Set(nameof(StoredDatesList), value);
}
public static async Task GetDraws(Uri url, string date)
{
var StoredDates = JsonConvert.DeserializeObject>(StoredDatesList);
var contents = string.Empty;
var current = Connectivity.NetworkAccess;
var client = new HttpClient();if (StoredDates != null) if (StoredDates.ContainsKey(date)) { contents = StoredDates\[date\]; } else { if (current != NetworkAccess.Internet) return Helpers.Settings.Common\_Error\_NoInternetConnection; contents = await DownloadResults(url, date, StoredDates, contents, client); } else { if (current != NetworkAccess.Internet) return Helpers.Settings.Common\_Error\_NoInternetConnection; StoredDates = new Dictionary(); contents = await DownloadResults(url, date, StoredDates, contents, client); } return contents; } private static async Task DownloadResults(Uri url, string date, Dictionary StoredDates, string contents, HttpClient client) { contents = await client.GetStringAsync(url); var res2 = JsonConvert.DeserializeObject(contents.ToString()); if (180 == res2.content.Count) { StoredDates.Add(date, contents); StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented); } return contents; }
...
public const string Common_Error_NoInternetConnection = "Error_NoInternetConnection";So i would check every time if the return sting is equal to Common_Error_NoInternetConnection, Does this sounds like a solid idea?
-
Proper Error handlingNo, i meant that not all the times data is needed. When it does, it will throw an error if you dont have
-
Proper Error handlinggreetings guys. im building an android application and i have some second thoughts on some error handling case. I have a method that gets data from the internet by calling this method:
public static string StoredDatesList
{
get => Preferences.Get(nameof(StoredDatesList), string.Empty);
set => Preferences.Set(nameof(StoredDatesList), value);
}
public static async Task GetDraws(Uri url, string date)
{
Dictionary StoredDates = new Dictionary();
StoredDates = JsonConvert.DeserializeObject>(StoredDatesList);
var contents = string.Empty;
HttpClient client = new HttpClient();if (StoredDates != null) if (StoredDates.ContainsKey(date)) { contents = StoredDates\[date\]; } else { var current = Connectivity.NetworkAccess; if (current != NetworkAccess.Internet) return null; client = new HttpClient(); contents = await client.GetStringAsync(url); var res2 = JsonConvert.DeserializeObject(contents.ToString()); if (180 == res2.content.Count) { StoredDates.Add(date, contents); StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented); } } else { StoredDates = new Dictionary(); contents = await client.GetStringAsync(url); var res2 = JsonConvert.DeserializeObject(contents.ToString()); if (180 == res2.content.Count) { StoredDates.Add(date, contents); StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented); } } return contents; }
the if statement
current != NetworkAccess.Internet)
checks if internet is available, when internet is not available i return null and i check if the data is null and im displaying a message(error, internet is not available etc). I find this approach very bad and im trying to think how is the proper way to handle this. i cannot show a message t
-
C#Nice topic :) How are you expecting an answer without giving a specification on what you are using and how? there are almost unlimited ways to build what you are building, as a programmer you should be able to understand that and help the others help you
-
How to display an ImageSpan from Vector in Xamarin.AndroidIm trying to create a spannable text that contains an ImageSpan, but the vector drawables has infinite size so we have to scale it some how, i have try this code with no luck, in some forums they say it should work:
var icon = AppCompatResources.GetDrawable(Activity, Resource.Drawable.ic_info);
icon.SetBounds(0, 0, 20, 20);
DrawableCompat.SetTint(icon, Color.White);
var textView = layout.FindViewById(Resource.Id.FeaturesContentTextView);
var imageSpan = new ImageSpan(icon, SpanAlign.Baseline); //Find your drawable.var spannableString = new SpannableString(textView.Text); //Set text of SpannableString from TextView spannableString.SetSpan(imageSpan, textView.Text.Length - 1, textView.Text.Length, SpanTypes.InclusiveInclusive); textView.TextFormatted = spannableString;
Now this code display the icon with the maximum width and height allowed from the parent layout I also try to convert the vector drawable to bitmap with this code with no luck (i dont get any icon)
public static Bitmap GetBitmapFromVectorDrawable(Context context, int drawableId)
{
Drawable drawable = AppCompatResources.GetDrawable(context, drawableId);Bitmap bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(bitmap); drawable.SetBounds(0, 0, canvas.Width, canvas.Height); drawable.Draw(canvas); return bitmap; }
Bitmap bitmap = GetBitmapFromVectorDrawable(Activity, Resource.Drawable.ic_info);
Drawable d = new BitmapDrawable(Resources, Bitmap.CreateScaledBitmap(bitmap, 80, 80, true)); -
How to calculate in c# the possibility of this gameOverflow could cause positive + positive to be negative and the other way around from what i have read.
-
How to calculate in c# the possibility of this gameThere was a time i new all those things in university but years have passed since, ok i have look them up
-
How to calculate in c# the possibility of this gameWow it really works as the counters we have in cars that counts kilometers? They start all over again from the beginning, only for integers we also have negative ones
-
How to calculate in c# the possibility of this gameim 99,99 percent sure that on overflow int will return 0 or -1 :P so this should be the issue
-
How to calculate in c# the possibility of this gamecan you say it 10 more times :P i think it will help
-
How to calculate in c# the possibility of this gamethat wasnt a hint!!! it appears to be the solution cause now this works
using System.IO;
using System;class Program
{
static void Main()
{
Console.WriteLine(CalculateProbabilityOfDrawNumbersFromAllNumbers(1,1));
}
private static double CalculateProbabilityOfDrawNumbersFromAllNumbers(double drawNumbers, double allNumbers)
{
return Factorial(allNumbers) / (Factorial(drawNumbers) * Factorial(allNumbers - drawNumbers)) * (Factorial(80 - allNumbers) / (Factorial(20 - drawNumbers) * Factorial(80 - allNumbers - (20 - drawNumbers)))) / (Factorial(80) / (Factorial(20) * Factorial(80 - 20)));
}private static double Factorial(double x) { double f = 1; while (x > 1) { f \*= x--; } return f; }
}
im not sure why i was getting division by zero error. the int has surpass its largest number and return 0? i will use this crazy code to display it as a percentage without any unnecessary zeros in the end
Console.WriteLine((CalculateProbabilityOfDrawNumbersFromAllNumbers(12,12) \* 100).ToString("F7").TrimEnd(new Char\[\] { '0' } ).TrimEnd(new Char\[\] { '.' } )+"%");