Boolean Resets When App Loads Wp8 - c#

Hi I am still fairly new to C# & windows phone.
When the app Loads I wanted popup asking the user if they would like to do something
MessageBoxResult m = MessageBox.Show("Info.", "Question?", MessageBoxButton.OKCancel);
if (m == MessageBoxResult.Cancel)
{ }
else if (m == MessageBoxResult.OK)
{ //Do Something }
Now that works fine, if the user says no I wanted a popup that asked the user if they would like reminding next time so U used
MessageBoxResult m = MessageBox.Show("Info.", "Question?", MessageBoxButton.OKCancel);
if (m == MessageBoxResult.Cancel)
{
MessageBoxResult r = MessageBox.Show("", "Would You Like Reminding Next Time ?",MessageBoxButton.OKCancel);
if (r == MessageBoxResult.Cancel)
{ }
else if (r == MessageBoxResult.OK)
{ }
}
else if (m == MessageBoxResult.OK)
{ //Do Something }
I need some kind of a switch, so when the app starts for the first time
app checks switch which is on,
they get asked a question
if they answer cancel,
they get asked if they want reminding
if they answer no,
set switch to off
I've tried to use a boolean but it just resets to true when the app closes, if i use a string it says a string cant be used as a bool
Any Advice ?

Use IsolatedStorageSettings.ApplicationSettings to quickly save small values for example
// this will save my "your_key" to false;
IsolatedStorageSettings.ApplicationSettings.Add("your_key", false);
IsolatedStorageSettings.ApplicationSettings.Save(); // make sure you call save
// so the next time the app runs I can get it back doing this
bool your_key = (bool) IsolatedStorageSettings.ApplicationSettings["your_key"];
But, should always enclose it in a try catch because the key might not exist
bool your_key = false; // or default value
try
{
your_key = (bool) IsolatedStorageSettings.ApplicationSettings["your_key"];
}
catch(Exception ex)
{
}
More Information can be found here:
How to: Store and Retrieve Application Settings Using Isolated Storage

if(!IsolatedStorageSettings.ApplicationSettings.Contains("first"))
{
// Do your stuff
IsolatedStorageSettings.ApplicationSettings["first"] = true;
IsolatedStorageSettings.ApplicationSettings.Save();
}
This is all the code you need.
Place everything you want to do only on first launch into this if statement. Then execute this code either in main page Loaded event or OnNavigatedTo.

Related

Back button on keyboard is acting like phone back key, how to distinguish them?

So I'm writing my first small app on Xamarin Android. I noticed that my app sometimes is suddenly closing, I found that it's closing when I'm holding back button on keyboard to delete text in text field.
I have this code that is supposed to make press back button twice to exit app:
bool doubleBackToExitPressedOnce = false;
public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
{
if (myWebView != null)
{
if (keyCode == Keycode.Back && myWebView.CanGoBack())
{
myWebView.GoBack();
return true;
}
else
{
if (doubleBackToExitPressedOnce)
{
base.OnBackPressed();
Java.Lang.JavaSystem.Exit(0);
return false;
}
doubleBackToExitPressedOnce = true;
Toast.MakeText(this, "Press back again to exit app", ToastLength.Short).Show();
new Handler().PostDelayed(() => {
doubleBackToExitPressedOnce = false;
}, 1000);
}
}
return false;
}
But apperently it's not reacting to phone's 'back' button, but also to 'back' on keyboard.
Any ideas how to fix this?
For now I solved it with adding next code into first if statement
if (myWebView != null && e.Flags != (Android.Views.KeyEventFlags.KeepTouchMode | Android.Views.KeyEventFlags.SoftKeyboard))
I still wonder if this is right way to fix my problem.

Strange behaviour when communicating over serial from VS WPF to Arduino

A basic overview. I am sending serial data from an Arduino Due to WPF application. Up until now this has all been working perfectly. Today I implemented a loop into the Arduino code that looks for a "Y" (ascii 89) in the serial port, if received it leaves the loop and returns back into what I am calling offline mode and stops sending over data, via online = false.
Now what is strange about this is that...
It was working fine before this loop so it must be something to do with trying to resend new data once it has left the 'online loop'.
It works perfectly from the Arduino serial monitor, which suggests it's a WPF problem, although the code hasn't changed on the upload section.
The code for both of these programmes is pretty big so I will try and keep it concise whilst providing all the information necessary.
void loop() {
// Check to see if the testbench is in offline mode and run the respective code.
if (Online == false) {
OfflineMode();
}
// Check to see if the testbench is in online mode and run the respective code.
if (Online == true) {
OnlineMode();
}
}
void OfflineMode() {
while (Serial.available())
processlncomingByte(Serial.read());
}
I then have switch cases to handle incoming settings - I know this works fine as it will also upload after the Arduino is reset.
void processlncomingByte (const byte c) {
if (isdigit (c)) {
currentValue *= 10;
currentValue += c - '0';
} else {
// end of digit
// The end of the number signals a state change
handlePreviousState ();
// set the new state, if we recognize it
switch (c) {
case 'A':
state = GOT_A;
break;
etc...
Online Mode
void OnlineMode() {
CheckForStop();
SendSerialData();
}
void CheckForStop() {
//Serial.println("...");
if (Serial.available() > 0) {
//Serial.println("getting something");
ch = (char)Serial.read();
inputString = ch;
if (ch == 89) {
//Serial.end();
Online = false;
//Serial.begin(9600);
exit;
//return;
}
} else
delay(5);
}
SendSerialData() consists of just a range of serial.print, outputting into one large string for WPF to handle.
Here is a screenshot of the serial monitor working
As you will see from the link above the monitor spits out a load of data, stops when I send a Y and finally I send a Q to 'question' whether the Arduino is ready to receive settings and S signifies a Yes. Great stuff it works!
However as you can see from the link below this isn't the case in WPF. Sorry, I can only upload 2 images at the moment so had to combine them.
Combo of screenshots
Here is the loop it is currently getting stuck in
private bool checkArduinoisReady() {
Stopwatch Uploadtimer = new Stopwatch();
if (!myPort.IsOpen)
return false;
// Debug.Print("port is ready to be opened");
string tempdata;
Uploadtimer.Start();
myPort.DiscardInBuffer();
Start:
myPort.WriteLine("Q" + Environment.NewLine);
Debug.Print("sent Q");
tempdata = myPort.ReadExisting();
Debug.Print("tempdata_" + tempdata.ToString());
if (Uploadtimer.ElapsedMilliseconds > 5000)
return false;
if (tempdata.Contains("S"))
return true;
else
goto Start;
}
And on a separate page this is how I am stopping the incoming data.
private void StopTest(object sender, RoutedEventArgs e) {
MessageBoxResult StopConfirm = MessageBox.Show("Are you sure you want to stop the test?", "Stop the test", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (StopConfirm == MessageBoxResult.Yes) {
Timer.Stop();
Debug.Print("Timer Stopped");
myPort.DiscardInBuffer();
Start:
for (int i = 0; i < 100; i++) {
myPort.WriteLine("Y");
}
string tempData = myPort.ReadExisting();
Debug.Print("Checking...");
Debug.Print("tempData_" + tempData);
if (string.IsNullOrWhiteSpace(tempData)) {
Debug.Print("Its null!!");
comments_textbox.Text = comments_textbox.Text + "Test Aborted";
MessageBoxResult SaveCurrentData = MessageBox.Show("Would you like to save the data collected up until this point?", "Save", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (SaveCurrentData == MessageBoxResult.Yes) {
SaveFile();
}
if (SaveCurrentData == MessageBoxResult.No) {
myPort.Close();
NavigationService.Navigate(new Uri("testSettings.xaml", UriKind.RelativeOrAbsolute));
}
} else {
Debug.Print("Still going...");
goto Start;
}
}
}
The biggest stumbling block for me is why this works over the serial monitor but not within the application. And it also works as soon as I reset the Arduino. I have also tried the resetFunc() in Arduino but this didn't help either.
Thanks in advance.
It turns out i still had a resetFunc() in my switch case which was preventing the serial monitor from continuing to send data!

Validation Logic

I am trying to create some validation for a form I have. There are two text boxes and two radio buttons on the form. My logic for this validation I know is a little rusty at the moment so any suggestions would be great.
Here is the code for what I have so far:
Keep in mind that the int errors is a public variable in the class
Start Button code:
private void btnStart_Click(object sender, EventArgs e)
{
errors = validateForm();
//Here I want the user to be able to fix any errors where I am little
stuck on that logic at the moment
//validate the form
while (errors > 0)
{
validateForm();
errors = validateForm();
}
}
ValidateForm Method:
private int validateForm()
{
errors = 0;
//check the form if there are any unentered values
if (txtDest.Text == "")
{
errors++;
}
if (txtExt.Text == "")
{
errors++;
}
if (validateRadioBtns() == true)
{
errors++;
}
return errors;
}
ValidateRadioBtns Method:
private Boolean validateRadioBtns()
{
//flag - false: selected, true: none selected
Boolean blnFlag = false;
//both of the radio buttons are unchecked
if (radAll.Checked == false && radOther.Checked == false)
{
blnFlag = true;
}
//check if there is a value entered in the text box if other is checked
else if(radOther.Checked == true && txtExt.Text == "")
{
blnFlag = true;
}
return blnFlag;
}
Overall I feel like this can somehow be more stream lined which I am fairly stuck on.
Any suggestions would be greatly appreciated since I know this is such a nooby question.
Well first since you have said that you want to validate for non-entered values, did you consider white spaces as an entry? since someone can just press space and then your validation would pass.
Aside from that, you might want to indicate which textbox they did not fill out or which group they did not click, it seems like you are using web forms so here is a walkthrough http://msdn.microsoft.com/en-us/library/vstudio/a0z2h4sw(v=vs.100).aspx.
If you are using windows forms you can use this walkthrough http://msdn.microsoft.com/en-us/library/ms229603(v=vs.110).aspx.
If you need to keep the existing logic, I would suggest extracting the repeating logic into separate functions and temporary btnFlag is not necessary also as you can return true and return false at the end.
private Boolean validateRadioBtns()
{
if (radAll.Checked == false && radOther.Checked == false)
return true;
else if(radOther.Checked == true && txtExt.Text.Trim().Length == 0 ) //just a quick sample of how you can trim the spaces and check for length
return true;
return false;
}
See the documentation for the validation patterns. You have chosen the explicit validation strategy, for which you would use the ContainerControl.ValidateChildren method and either perform your "Start" action or not.
Windows Forms has dedicated events for validation that allow you to react accordingly for each of your controls. You'll use Control.Validating and Control.Validated events.
So, unless ValidateChildren returns true, you don't need to initiate your "Start" action, i.e. the logic would become trivial.
P.S. you also probably don't need the errors variable as a class member since you return it from your validation function. For showing the error, prefer the "Tell, Don't Ask" idea by separating the error visualization in a separate component.

ConfirmationBox from codebehind, wait for answer

From my code behind, in my update method, I have to ask the user if he wants to overide some particular value. If so, overide, if not, continue with the saving without saving this value.
In my aspx I have this javascript function:
function ConfirmationBox(msg) {
var ovd = document.getElementById("hdnOveride"); //gets a HiddenField
if (confirm(msg) == true) {
ovd.value = "1";
return true;
}
else {
ovd.value = "0";
return false;
}
}
From codebehind, I call this function. And then I check the value of my HiddenField "hdnoveride". If its 1 I save, otherwise I don't.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", "javascript:ConfirmationBox('overide?');", true);
if (hdnOveride.Value == "1"){
//Save the value
}
The problem is that my code doesn't wait for the user to answer the confirm box before it continues. I have tried using Thread.Sleep() while hdnOveride is not set like this:
while (hdnOveride.Value == "notset") {
System.Threading.Thread.Sleep(500);
}
But it just stops everything, so the popup box never shows when I do this.
How can I tell the system to wait for an answer before continuing with the code?
Thanks!
Ok then, I used Panel instead to ask the question to my users as suggested here: https://stackoverflow.com/a/7677000/454157

Alert user about the running process during installation

protected override void OnBeforeInstall(IDictionary savedState)
{
base.OnBeforeInstall(savedState);
DialogResult result = DialogResult.None;
if (isExcelIsRunning())
{
result = MessageBox.Show("Excel is still running. Please save your work and close Excel, and then click \"Retry\" button to continue with installation.", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
}
while (result == DialogResult.Retry)
{
if (!isExcelIsRunning())
{
break;
}
}
}
//check if excel is currently running
private bool isExcelIsRunning()
{
bool flag = false;
Process[] xlProc = Process.GetProcessesByName("excel");
if (xlProc != null)
flag = true;
return flag;
}
The above is the code I am about to use for my Installer Class.
What I want to achieve here is that I need the installer to check whether or not Excel is currently running during the installation. And if it is running, then there should be a pop-up message at the start of installation to alert user to close off Excel and the installer should pause until there's no Excel instance found in the process list any more.
Back to the code, I don't think that while block is quite right, as it could cause an endless loop after user clicks "Retry" button if in the mean time Excel is still running.
So what'd be the better approach? Would anyone here take a look at the above code and see where I can improve?
I think your code would be something like this:
while(isExcelRunning())
{
var result = MessageBox.Show("Excel is still running. Please save your work and close Excel, and then click \"Retry\" button to continue with installation.", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
if (result != DialogResult.Retry)
{
//Handle Cancel
break;
}
}
This will keep displaying the alert in a loop, either until Excel exits, or they press cancel, at which you can do whatever you need to do; then we exit the loop (or you could return entirely out of the method).
The key here is display the alert repetitively, either until Excel is gone or they choose to cancel. If you need to do some code after the loop based on the response; perhaps something like this:
var userHasCancelled = false;
while(!userHasCancelled && isExcelRunning())
{
var result = MessageBox.Show("Excel is still running. Please save your work and close Excel, and then click \"Retry\" button to continue with installation.", "", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
if (result != DialogResult.Retry)
{
userHasCancelled = true;
}
}
if (userHasCancelled)
{
//User cancelled...
}
else
{
//Continue.
}

Categories