Lock app with password - windows-phone-7

In WP application we need to provide user option to lock app with password.
As I understand WP app lifecycle, I need to put navigation to LockPage in App.Application_Activated, App.Application_Deactivated and start page, but I can not use NavigationService in App class...
I do not want to put navigation code to lock page in each other pages, or there is no other options?

I writed own solution, but may be it is not so elegant as it could be.
App locking logic: User enable app locking with password, we handling Application_Deactivated and Application_Closing events in App class and marking app as locked if user enabled this option. Then, on each page we should put check: is app currently locked and if it is, we should navigate to AppLockedWithPasswordPage. On AppLockedWithPasswordPage we need to check user`s password, if it is correct call NavigationService.GoBack().
So we need to do 6 steps:
You should choose where to save IsAppCurrentlyLocked (bool flag), AppLockPassword (string) and IsUserEnabledAppLockWithPassword (bool flag). I had chosen IsolatedStorageSettings
Create AppLockedWithPassword page, where you need to show TextBox and Button, do not forget to provide option for user to reset AppLock of course with deleting app data
AppLockedWithPasswordPage should prevent BackButton navigation, so preventing it:
// AppLockedWithPasswordPage
protected override void OnBackKeyPress(CancelEventArgs e)
{
// Preventing back key navigation
e.Cancel = true;
}
Check password on button click
// AppLockedWithPasswordPage
private void UnlockAppButton_Click(object sender, RoutedEventArgs e)
{
if (PasswordBox.Password.Equals(IsolatedStorageSettings["AppLockPassword"]))
{
NavigationService.GoBack();
}
else
{
// Say user, that password incorrect, etc...
}
}
In App class find Application_Deactivated (to handle app minimizing (windows button)) and Application_Closing (to handle when user closing app) methods, we should mark app as locked if user enabled this option when this events happens
private void SetIsAppCurrentlyLockedFlagIfUserEnabledAppLocking()
{
if ((bool)IsolatedStorageSettings["IsUserEnabledAppLockWithPassword"])
{
IsolatedStorageSettings["IsAppCurrentlyLocked"] = true;
}
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
SetIsAppCurrentlyLockedFlagIfUserEnabledAppLocking();
}
private void Application_Closing(object sender, ClosingEventArgs e)
{
SetIsAppCurrentlyLockedFlagIfUserEnabledAppLocking();
}
And final step, on all pages you want to lock you should add check in OnNavigatedTo method which will navigate to AppLockedWithPasswordPage if app is currently locked
// Create some class, like PagesUtils or so on with check method
private static Uri uriToAppLockedWithPasswordPage = new Uri("pathToAppLockedWithPasswordPage", UriKind.Relative);
public static void NavigateToAppLockedWithPasswordPageIfAppLocked(PhoneApplicationPage page)
{
if ((bool)IsolatedStorageSettings["IsAppCurrentlyLocked"])
{
page.NavigationService.Navigate(uriToAppLockedWithPasswordPage);
}
}
// In each page you want to lock add
protected override void OnNavigatedTo(NavigationEventArgs e)
{
PagesUtils.NavigateToAppLockedWithPasswordPageIfAppLocked();
base.OnNavigatedTo();
}
P.S. of course real code is much better, this is just simple example, I hope it will help you

You should add the check in the Application_Launching and Application_Activated events.
The launching event for when the app is first opened and the activated one for when the user returns to the app after having left to do something else.
Have these events both set a flag and have the base page that all your pages inherit from check for this flag when navigated to. The check should be for if the flag is set, if it is, show the login prompt and then clear the flag after successful password entry.
This approach will handle FAS, FAR & deep linking, in addition to starting the app normally.
Beware Some choosers will trigger the activated event when they return to the app. Add extra handling for these as appropriate / if necessary.

Why not create a start page where the passwords is entered?
For instances you have your MainPage.xaml, create a InsertPasswordPage.xaml reference it on WMAppManifest as the start page:
<DefaultTask Name="_default" NavigationPage="InsertPasswordPage.xaml" />
And insert all the password logic on the InsertPasswordPage.xaml, when the user successfully logins just navigate to your main page ;)
EDIT: As Gambit said if the user pressed the back button he will return to the insert password page, but you can solve this by removing from the backstack the page after the user logged in.

Related

How to notify user caps lock is turned on within a password field in C#?

I'm not a pro, but What i want in my Login panel (a windows form) which hass a pasword Text field,
I want to apply the same idea here, 'window Xp password text field had', in which if Caps lock is on, a small String gets to Popup saying CAPSLOCK is On, `
private void txtPass_TextChanged(object sender, EventArgs e)
{
txtPass.PasswordChar= '*' ;
}
`
this is my Password button.
The magic happens in this line
Application.EnableVisualStyles();
If this line is missing then you loose that functionality together with the flat appearance of many controls and so on.
The line should go before any attempt to create user interface objects and usually is present in the Main static method that starts your application
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new yourStartupForm());
}

Windows phone 7: facing issue for passing parameters

Right now i am developing a Windows phone app, yes this is my first windows app. Right now i am facing an issue, don't know what's the silly mistake i made. Yes of course i have done debugging.
Now, what exactly i am doing?
Passing data from 1st page to 2nd page,
On the page, catching data inside onNavigateTo() method, yes i am receiving it correctly.
Based on the parameter/data (i.e. ID) i got, i am making web service call.
Problem:
If i move to the 3rd page from 2page and again came back to the 2nd page, its again making web call. i.e. calling DownloadStringAsync again in below code.
i.e. If 2nd page is having ListBox with 5 data, now clicking on particular item i am moving to 3rd page, if i came back to 2nd page from page 3, items get doubled i.e. 10 items (just because its making call again)
Here is the possible code for the reference:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
type = Convert.ToInt32(NavigationContext.QueryString["Type"]);
if (type != 0)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
client.DownloadStringAsync(new Uri(Utils.Constant.WebService_URL));
}
else
{
MessageBox.Show("Please check internet connection!!");
}
}
}
Can't you use the following code to test if the user used the back button?
e.NavigationMode == System.Windows.Navigation.NavigationMode.Back
sometimes this method(QueryString) create problems.
In back event it create problems
its betters to store the id(parameter) in isolatedstorage application key
IsolatedStorageSettings.ApplicationSettings["id"] = "your data";
OnNavigatedTo is called whenever you navigate to the page, either by a forward navigation, or a back navigation. That's why it's retriggered when you navigate back from page #3 to page #2.
You can avoid this by only triggering the network call on a forward navigation.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (this.isInitialized) return;
type = Convert.ToInt32(NavigationContext.QueryString["Type"]);
if (type != 0)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
client.DownloadStringAsync(new Uri(Utils.Constant.WebService_URL));
}
else
{
MessageBox.Show("Please check internet connection!!");
}
}
this.isInitialized = true;
}
Beware that NetworkInterface.GetIsNetworkAvailable can block (in this case the UI thread) for a long time in some scenarios, to work around this you can use network detection events.

Windows phone navigation bug

I encountered an issue.
I have a loading page with progress bar. It is non-interactive, it only shows progress on loading data. AFter data is loaded - it navigates to MenuPage.
If user minimizes app during loading process sometimes a phantom corrupted entry is added to BackStack.
Problem:
If this corrupted entry is in backstack - NavigationService.RemoveBackEntry() throws NullReferenceException.
Question:
My goal is to exit app from 2nd page when user presses back. Can i somehow do that without removing items from backstack and throwing exceptions ?
In short, no. You can't directly quit an application and it sucks. However you can do it with a well handled exception.
private class QuitException : Exception { }
public static void Quit()
{
throw new QuitException();
}
private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is QuitException)
return;
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
}
Source:
http://www.imaginativeuniversal.com/blog/post/2010/08/22/How-to-Quit-a-WP7-Silverlight-Application.aspx

How to refresh date time when the app is reactivated in WP

i would like to know if it is possible to refresh date time when the app returns from a deactivated state in WP7.5. My app is basically a calendar type and when the app starts the current day is highlighted.
So if i start the app, then press the start button, my app goes to deactivated state, then go to settings and change the time zone, naturally the date and time may change and then come back to my app, it retains the old date.
eg.
Suppose current date is 20 and we change the timezone where the date is 19, ideally my app should highlight 19, but it does not. I assume that its becomes before the app goes into deactivated state, it stores all the states and when it returns, it loads the same data. Is there anyway i could refresh the datetime?
Alfah
It's been a while since I've done any WP7 development, but I'm sure there's an event raised when the app is reactivated - can't you just query DateTime.Now or DateTime.Today at that point?
EDIT: Looking at the docs, I think you want the Launching and Activated events. (Launching so that you check the time even on the initial launch; Activated for reactivation after becoming dormant.)
Assuming that you have a model class that contains a DateTime field called DateToDisplayAsToday, and that model is accessible within App.XAML, you will want to to the following in App.xaml.cs
private void Application_Launching(object sender, LaunchingEventArgs e)
{
// Application_Launching fires when the app starts up.
// retrieve any data you persisted the last time the app exited.
// Assumes you have a local instance of your model class called model.
model = new model();
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
// Application_Activated fires when you return to the foreground.
// retrieve any data you persisted in the Application_Deactivated
// and then you can set the current DateTime
model.DateToDisplayAsToday = DateTime.Now;
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
// persist an data you don't want to lose during tombstoning
}
private void Application_Closing(object sender, ClosingEventArgs e)
{
// persist any data you want to keep between separate executions of the app
}

how to disable location services in my WP7 app

I'm making a windows phone app which displays where the closest campus shuttles are (among other things). Windows Phone requires apps to allow the users to turn off location services within the app.
So, I added a toggle for it on a settings page, but it doesn't seem to do anything.
Here's the viewmodel where I declared the geocoordinatewatcher.
public MainViewModel()
{
geoWatcher = new GeoCoordinateWatcher();
if (geoWatcher.TryStart(false, TimeSpan.FromSeconds(30) )==false )
{ MessageBox.Show("The location services are disabled for this app. We can't detect the nearby stops. To turn location services back on, go to the settings page.", "Warning", MessageBoxButton.OK); }
}
private GeoCoordinateWatcher geoWatcher;
public GeoCoordinateWatcher GeoWatcher
{
get
{
return geoWatcher;
}
set
{
if (geoWatcher != value)
{
geoWatcher = value;
NotifyPropertyChanged("GeoWatcher");
}
if(geoWatcher.Status== GeoPositionStatus.Disabled)
{
geoWatcher.Stop();
}
}
}
and here's the bulk of the settings page
public SettingsPage()
{
InitializeComponent();
if (App.ViewModel.GeoWatcher.Status == GeoPositionStatus.Ready)
{
locToggle.IsChecked = true;
locToggle.Content = "On";
}
else
{
locToggle.IsChecked = false;
locToggle.Content = "Off";
}
}
private void toggleChecked(object sender, RoutedEventArgs e)
{
locToggle.Content = "On";
App.ViewModel.GeoWatcher.Start();
MessageBox.Show("this is the status " + App.ViewModel.GeoWatcher.Status.ToString(), "Info", MessageBoxButton.OK); //for debugging
}
private void toggleUnchecked(object sender, RoutedEventArgs e)
{
locToggle.Content = "Off";
App.ViewModel.GeoWatcher.Stop();
MessageBox.Show("this is the status " + App.ViewModel.GeoWatcher.Status.ToString(), "Info", MessageBoxButton.OK); //for debugging
}
When i turn the toggle off and click away from the Settings page, and go back to it, the toggle is re-enabled again.
I tried putting in a message box on the functions to debug but the status always says "Ready" and my app still uses the location services, even when I turn the toggle to "off".
Is there something I should be adding to the code so that the toggle will properly make my app stop using location services across my app if it's disabled on the settings page? Or should I be checking something else besides GeoPositionStatus? I couldn't figure out a way to make my app actually change the location services permissions or PositionStatus.
I looked at this page here, but am still confused since I followed the example at the bottom of the page, to no avail. I searched StackOverflow but I couldn't seem to find a similar question with WP. I also posted this on the AppHub forums though.
Thanks!
In your MainViewModel you need to check if they have allowed location services before you use the geocoordinatewatcher.
if(settings.LocationAllowed)
{all your code for using location}
You should probably take into account a few factors/points, most of which, you have. Anyway, you might find these helpful.
Your application settings toggle should only show when the location service is switched on on the device
GeoPositionStatus is just an Enum which contains the types of statuses.
StatusChanged is the event which is to be handled to check for changes in the device settings. See this.
You cannot change the device settings from the application.
Add event handlers before you call start on the watcher.

Resources