MessageDialog crashes when called - Windows Phone Store app - c#

I am having a message dialog to prompt the user when there is no internet.
public async void validateInternet()
{
if (!isInternet())
{
Action cmdAction = null;
MessageDialog _connectAlert = new MessageDialog("We are currently experiencing difficulties with your conectivity. Connect to internet and refresh again.", "No internet");
_connectAlert.Commands.Add(new UICommand("Retry", (x) => { cmdAction = () => validateInternet(); }));
_connectAlert.DefaultCommandIndex = 0;
_connectAlert.CancelCommandIndex = 1;
await _connectAlert.ShowAsync();
cmdAction.Invoke();
}
}
public static bool isInternet()
{
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
return internet;
}
Now, I call this function validateInternet when MainPage has loaded. The app opens the message dialog, and crashes immediately. What's wrong with the code?
A A first chance exception of type 'System.UnauthorizedAccessException' occurred in BusTrack.exe Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
is thrown at
await _connectAlert.ShowAsync();

As #yasen rightly pointed out, the validateInternet() was called both in MainPage_loaded() and OnNavigatedTo().
Hence, System.UnauthorizedAccessException occurs since both of those methods will try to show a messageDialog. So, never try to call two message dialogs at the same time.

Related

Get Microsoft Store updates available for the UWP app

I want user to notify if the Microsoft store has updates for the app.After researching I found below code and implemented it.
public static async Task<bool> IsStoreUpdatesAvailable()
{
try
{
if (context == null)
context = StoreContext.GetDefault();
IReadOnlyList<StorePackageUpdate> updates = await context.GetAppAndOptionalStorePackageUpdatesAsync();
Logs.Write.Success("Store updates are available? :" + updates.Any().ToString());
return updates.Any();
}
catch (Exception ex)
{
return false;
}
}
When I run it in my machine in debug mode or release mode it works fine.But when I try a release build in another machine it logs the following error.
Message: Exception from HRESULT: 0x8024500C StackTrace: at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x21
at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) +
0x70 at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task)
0x38 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task) + 0x17
at
com.IronOne.BoardPACWinApp.Helpers.WindowsStoreServiceHelper.d__3.MoveNext()
0x105
Any suggestion on how to fix it?

How to fix NullReferenceException occurring only on some computers

I create a setup file of a winform app using VS 2017 installer. When I test this setup file on my PC, the login runs fine. So I run this setup file on other PCs.
However, when I login the app in these PCs, the app say "Object reference not set to an instance of an object", though I am sure that the username and password were correct in the db.
I have seen What is a NullReferenceException, and how do I fix it?, but I do not think it is the null exception, because the installed app did not throw above error in my PC. This error only happens when I install the app in other PCs.
I also try replacing the .exe and .config files in folder of the installed app in other PCs with the same files of the app in my PC (which work well), and the app runs ok. But then I restart those PCs, and try to login the app, the same error happens.
This is the code for login. I believe that I have checked for the null exception properly. Am I right?
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
var info = UsersBiz.Login(txtUserName.Text.Trim(), txtPassWord.Text);
if (info != null && info.user.Id > 0)
{
Constants.USERINFO = info;
this.Hide();
var frm = new frmMain();
frm.Show();
if (ckbRemember.Checked)
{
ManagementInventory.Properties.Settings.Default.User = txtUserName.Text;
ManagementInventory.Properties.Settings.Default.Pass = txtPassWord.Text;
ManagementInventory.Properties.Settings.Default.Save();
}
}
else
{
MessageBox.Show("UserName or Password not correct!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The most easy way would be to use visual studio debugger on the computer where the program runs. If there is no visual studio on that computer, consider using remote debugging. See how to start debugging on a remote computer
If for security reasons remote debugging is out of the question, consider to log the exception, especially the stack trace. If you know where it occurs, simply surround it with a try-catch
try
{
// Here are the statements that cause your ArgumentNullException
}
catch (ArgumentNullException exc)
{
// log the exception
}
If your program has no logging facility, consider adding something like NLOG. Another possibility is to append it to a text file.
void WriteExceptionToTextFile(Exception exc, string fileName)
{
using (var writer = File.AppendText(fileName))
{
writer.WriteLine("Exception {0}", exc.GetType());
write.WriteLine("Stack trace" + exc.StackTrace);
... // etc
}
}
If you don't know where the exception occurs, you can't try-catch it. In that case consider to catch the unhandled exception and log it:
See: catching unhandled exception
In your forms program is a file program.cs which contains the main:
public static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += OnUnhandledException;
...
}
static void OnUnhandledException(object sender, UnhandledExceptionEventArgs args)
{
Exception undhandledException = (Exception) args.ExceptionObject;
// TODO log the unhandled exception
}

Getting Access is denied exception when calling CompositionCapabilities.GetForCurrentView

I am getting the following exception when I call CompositionCapabilities.GetForCurrentView.
System.UnauthorizedAccessException: 'Access is denied. (Exception from
HRESULT: 0x80070005 (E_ACCESSDENIED))'
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
// Exception happens here.
var capabilities = CompositionCapabilities.GetForCurrentView();
}
The weird thing is the code compiles OK so I assume the API is available. Do I need to declare any capabilities in Package.appxmanifest?
You don't need to declare anything. The method is simply called too early.
So instead of calling it in the constructor, call it right after the Window is created -
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 4))
{
var capabilities = CompositionCapabilities.GetForCurrentView();
var areEffectsSupported = capabilities.AreEffectsSupported();
var areEffectsFast = capabilities.AreEffectsFast();
}
base.OnWindowCreated(args);
}
Note you will want to add a check to see if that API is supported too, like in the code above.

Is there a way to catch the "An unexpected network error occurred" exception specifically, or to manually throw it (for testing)?

Background:
I have a CSV file containing a list of filepaths. Each file needs to be copied from the filepath to a new location over the network. My program handles this fine, however there are occasional network blips, which throw an IOException with the message "An unexpected network error occurred.". When this happens, I want to retry a few times (with a short delay) before giving up (if a retry is successful, the program would continue as normal). At the minute, I am catching IOException and using the Message value to determine whether to retry or throw, however it doesn't appear to be retrying as expected. I assume this is because the message I'm comparing isn't quite the same, but I can't think of how I can verify as the problem is occasional.
Questions:
Is there a way to replicate this error (without just creating a new IOException with the relevant Message)?
Is there a better way of isolating this particular error?
Sample Code:
private static void CopyFile(FileInfo file, string destinationFilepath)
{
try
{
file.CopyTo(destinationFilepath);
}
catch (IOException e)
{
var saved = false;
if (e.Message == "An unexpected network error occurred.")
{
saved = RetryCopyFile(file, destinationFilepath);
}
if (!saved)
{
throw;
}
}
}
private static bool RetryCopyFile(FileInfo file, string destinationFilepath)
{
var saved = false;
var maxRetries = 20
var retries = 0;
while (!saved && (retries < maxRetries))
{
try
{
file.CopyTo(destinationFilepath, true);
saved = true;
}
catch (Exception)
{
Thread.Sleep(10000);
retries++;
}
}
return saved;
}

Exception Unhandled by User Code

I have a member of a library being declared on the main page of my app:
private OpticalReaderLib.OpticalReaderTask _task = new OpticalReaderLib.OpticalReaderTask();
It works fine until I want to navigate back to this page at a different time. It brings up the error "An exception of type 'System.Exception' occurred in OpticalReaderLib.DLL but was not handled in user code".
Does anyone know why this is happening?
Thanks.
System.Exception is the base class for all Exceptions, so this is a very generic error message.
You could try logging more detail (e.g. exception.Message or exception.InnerException) about the exception that is thrown as part of your investigation. (via a try-catch statement).
It looks like you're initialising a field, where is this code being executed?
Update due to comment
As a temporary solution to discover the exception error.
private OpticalReaderLib.OpticalReaderTask _tempTask;
private OpticalReaderLib.OpticalReaderTask _task
{
get
{
//code to debug the error that is occuring
try
{
if (_tempTask == null)
_tempTask = new OpticalReaderLib.OpticalReaderTask();
else
return _tempTask;
}
catch (Exception exception)
{
//Log the exception detail here
}
}
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (_task != null)
{
_task.Completed -= OpticalReaderTask_Completed;
_task.Dispose();
_task = null;
}
base.OnBackKeyPress(e);
}

Categories

Resources