How to cancel Contacts.SearchAsync before finish the search in WP8 - windows-phone-8

I'm using Contacts.SearchAsync to get all user's contacts, in an WP8 app.
But i realized that, when the user has many contacts (like 1000+), this search takes a long time...
So, I was thinking in add an button, so the user has the option to cancel this search...
But I couldn't find any method that cancels this search...
Is there a way to cancel it, before it finishes?
Thanks

I did not use this, but there is workaround.
If thread is terminated, all of its children-threads are terminated too.
Therefore if you run this method in new thread, you can always terminate it.

I am not aware of any way to cancel the search but an alternative approach is to just ignore the completion of the search.
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
if (!searchWasCancelled)
{
// Process the search results
}
}

Related

Windows 8 phone save state

I am quite new to windows 8 phone and I don't know all the life cycle methods and when what is called.
My problem is the following: I have a page that loads some data from the disk and when the user exits the program ( or suspends ) the data should be saved. As far as I can tell Page doesn't have an OnSuspending method only someOnNavigatingFrom, but those are not called when you just exit the program. So I read that I should use the OnSuspending in my App.xaml.cs, but this class doesn't have this data and also shouldn't have it, maybe only for OnSuspending. But I don't know how to get the data from my page in the OnSuspending method.
The OnSuspending event is quite fragile and you cannot expect it to run and save the state for a long time. But it depends on how long it would take for you to save. It doesn't even get triggered when you hit the home key while closing the app. If you really want an easy way. Just register a background task. While your app is in the background, the state can be saved and when you open the app again things are in place.
There are certain constraints With Background task as well, you cant do heavy lifting etc...here's a link you could use.
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977056.aspx
Implement an observer pattern (i.e. pub/sub) for your view-models to subscribe to in the event that your app is being suspended.
Your app handles the suspended event. As a result, publish a message for your view-models to respond to within your app's method handler for the suspended event.
You can use an EventAggregator or MessageBus (that I wrote).

Windows Phone 8 handling back key event

In my WP8 App, I am navigating from one screen to another based on some events. Say, after initiating the event(http call which would take me to a new screen, after successful response), I click on back key, the previous screen is shown to me, but since the earlier event was already fired, after the event completion a new screen is shown.
So, How should I handle this back key press.
I have tried searching it on net as well, but did not get much help.
[Edit :] I want to stop my async calls on the current screen when its back key is pressed,
I did some searching and found that using Cancellationtoken is one such approach. But, I would want to know how exactly to use it if I am using HttpWebRequest request, response classes
Since you did not mention what is the expected behavior, I would assume that what you want is that in some condition you expect that back key press won't lead you to the previous page. If so, you should override the BackKeyPress method in the page where back key is pressed.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (someCondition) {
e.Cancel = true;
}
base.OnBackKeyPress(e);
}
Please let me know if it is what you expected.

When to use Exception

I have a Form or Page and some privileges (Save, Modify, Delete etc.) assigned to a user that is using this page, let's assume this user only has Save and Modify privileges.
When user clicks Delete button, which he is not privileged to, I want to display a message to him to inform him that he doesnt have this privilege, how should my code look like?
Option 1
If(loggedUser.Privileges.Contains(PrivilegeTypes.Delete) == false)
{
MessageBox.Show("You dont have delete privilege!");
// Log that user tried to delete without permission etc
return;
}
Option 2
try
{
If(loggedUser.Privileges.Contains(PrivilegeTypes.Delete) == false)
{
// Throw custom exception
throw new UngrantedPrivilegeException(PrivilegeTypes.Delete, "Invalid privilege exception");
}
}
catch (UngrantedPrivilegeException ex)
{
if( ex.PrivilegeType == PrivilegeTypes.Delete)
{
MessageBox.Show("You dont have delete privilege!");
// Log that user tried to delete without permission etc
}
}
In this case i would go for first option since i know what are the possibilities and no need of creating unwanted exception object as burden on memory.
Exception should be used to handle unknown run time errors, not for logic conditions.
There is absolutely no reason to use an exception in this case. There is nothing exceptional about what the code is doing, and simple conditional logic is appropriate.
Consider the semantic logic of your first option:
Does the user have permission?
Tell the user they don't have permission.
Now consider the semantic logic of your second option:
Try to check for permission
Does the user have permission?
The user does not have permission.
Did the user have permission?
Tell the user they don't have permission.
Seems like a lot of redundancy in the second one, don't you think? You're also adding more overhead to the runtime by throwing an exception for the sole purpose of immediately handling it, when all you really wanted to do was check a condition. if statements exist to check conditions, there's no reason not to use one here. (Indeed, you are using one even in your second example.) It also pollutes the code with a lot of unnecessary things which distract from the basic business logic of what you're doing (checking a permission setting), making the code more difficult to support.
Don't use exceptions for logic flow. Use them to handle unexpected things that shouldn't happen, not to determine the logic flow of things that are expected to happen.

How should I perform an asynchronous action within an accessor?

I have a simple accessor in my class:
public function get loggedIn():Boolean
{
var loggedIn:Boolean = somePrivateMethodToCheckStatus();
return loggedIn;
}
The API I'm now working with checks login status in an asynchronous fashion:
API_Class.addEventListener(API_Class.LOGIN_STATUS,onStatusCheck);
API_Class.checkLoginStatus();
function onStatusCheck(evt:API_Event):void
{
//evt.loggedIn == true or false
}
Is there a way I can perform this asynchronous request without exiting my accessor?
Simple answer: No, there is not. You will have to set up login verification in an asynchronous fashion.
I am a bit curious: Why is there a need to repeatedly poll the login status remotely? If your user logged in from within the Flash application, the status should be known. Same goes for logging out. If login and logout is handled from outside the Flash app, why not implement a notification mechanism (via JavaScript or socket connection)?
Also, if not being logged in prevents users from performing actions on the server, you could check for authorization on the server, whenever remote calls are made, and return an error if the session has expired. This would still be more efficient than repeatedly polling status info.
Not really, no. Flash runs in a single thread, and every function has to finish before events etc will be called.
One (sort of) solution would be to return three values; "yes", "no" and "pending". If it's pending the loggedIn()-method would start a check, and the client of that method should check again in a little while.
Another way would be to have the loggedIn-method send the answer to a callback instead. Eg "getLoggedInStatus(callback:Function)"
You may be interested in http://www.as3commons.org/as3-commons-eventbus/index.html
It is a handy lib that focuses on asynchronous jobs.

How to implement a time wait before html form resubmission?

I have an html form which inserts data into a database. I just built it.. it's very basic, as I'm just doing this to learn. In doing this, I see that I can hit the back browser button and post again.. and again.. and again.. and it keeps writing to the db.
I've seen sites where I try to resubmit info and it tells me I must wait 60 seconds (or whatever). Is this the preferred method to solve this problem? If so, how does one go about implementing it?
Or maybe you would handle it a different way?
When you insert a row, store the submission time in the table, or in the user's session.
Whenever you process the form, compare that time to the current time. If it's within 60 seconds, display an error instead of inserting a row.
There are two methods :
i) Simple client side javascript:
Store the time of last event in a javascript variable,
when the user does the event again , send an alert message about timing.
( This method can be fooled though by users knowing javascript )
ii) Store the time of last event in your database at backend when the form post is done. When the same form post is done again, check for the time, if it is allowed, do the processing, else reply with a message about the timing.