Background agent error WP7 - windows-phone-7

When I try to add a periodic task in windows phone 7.5 it gives me a "BNS Error: The maximum number of ScheduledActions of this type have already been added." error while i haven't added any periodic task. The code works fine on Windows phone 8 but raises this error on WP7.5. Also the app schedules reminders and alarms.
string periodicTaskName = "myperiodictask";
PeriodicTask periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
if (periodicTask != null)
{
try
{
ScheduledActionService.Remove(periodicTaskName);
}
catch (Exception)
{ }
}
periodicTask = new PeriodicTask(periodicTaskName);
periodicTask.Description = "Updates LiveTile, Sessions and Assignments";
periodicTask.ExpirationTime = DateTime.Now.AddDays(10);
try
{
ScheduledActionService.Add(periodicTask);
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
MessageBox.Show("Background agents have been disabled by the user.");
if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
MessageBox.Show("maximum number of ScheduledActions of this type have already been added!");
}
catch (SchedulerServiceException)
{ }

How are you testing the background agent? Emulator or Device. Either way, you need to make sure you're not testing on a low memory 'device'.
On low memory devices (256mb), background agents are disabled. Unfortunately, the error thrown is the same as when the maximum number of agents are scheduled, i.e. "BNS Error: The maximum number of ScheduledActions of this type have already been added."

Please refer these posts.
http://codeblog.vurdalakov.net/2012/02/solution-bns-error-maximum-number-of.html
http://imjo.hn/2013/01/23/bns-error-the-maximum-number-of-scheduledactions-of-this-type-have-already-been-added/
In debugging you added some task and its registered your app but you are not removing earlier
tasks thats why this happening.

Related

Xamarin iOS Fails Calling DataServiceQuery

Just coming back to testing the iOS cross platform project of my solution today, I am receiving the error message "An error occured on client IDB4110776 while executing a reply for topic xvs/idb/4.11.0.776/stop-app" when trying to iterate the results of a DataServiceQuery, i.e.
foreach (IdentityEntitiesModel.Device device in response.EndExecute(result))
In general, looking at the response received, it looks basically ok, having the query path. It was working two months ago.
I am using Xcode 10.1 beta 2 (10O35n) against a iPhone with iOS 12.0 (16A366) from VS2017 15.8.5. Another developer just encountered the same error using Xcode 10 and IOS 10.14.1.
Where might I find details as to the "xvs/idb/4.11.0.776/stop-app" function?
It appears that iOS requires the call be marshalled to the main thread, i.e.
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
try
{
foreach (IdentityEntitiesModel.Device device in response.EndExecute(result))
{
if (device.MAC == DeviceID)
{
activeDevice = device;
activeICID = device.ICID;
// Remark to debug new device
DeviceFound = true;
}
}
}
catch (DataServiceQueryException ex)
{
string error = ex.Message.ToString() + cr;
}
});
The solution should work across platforms.

The given key was not found in the dictionary

I'm developing windows phone 8 application. In this, I have to integrate Twitter. So I have followed the below tutorial.
http://code.msdn.microsoft.com/wpapps/Latest-Twitter-integration-a42e8bb6
I've implemented successfully twitter in my application. I've tested this in Emulator and in device also. Everything was fine.
**Suddenly in the device the application is unable to open the twitter log in page. I'm getting the error in the below method at line started with .
void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
StreamReader reader = new StreamReader(e.Response);
string strResponse = reader.ReadToEnd();
var parameters = MainUtil.GetQueryParameters(strResponse);
**OAuthTokenKey = parameters["oauth_token"];**
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = AppSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey;
Dispatcher.BeginInvoke(() =>
{
this.loginBrowserControl.Navigate(new Uri(authorizeUrl, UriKind.RelativeOrAbsolute));
});
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
pi.IsVisible = false;
});
}
}
The given key was not present in the dictionary.
But in Emulator I'm successfully redirected to log in page if user is not logged in and posting the message.
I don't know what is the problem in the device.
This issue occurs when the the device you are using for testing the app is without simcard, as it the device without the simcard cannot match the timings of the twitter api server and this mismatch causes the authentication error, as for the api the credentials are invalid due to heavy difference in the timings between api server and device, hence try checking it on a device that has a simcard inside.

Is it possible to run background transfer from background audio agent?

I want to run Background file transfer from Background audio agent but I get error with example code which runs correct in foreground app.
Here is example:
string transferFileName = #"http://www.reggaeavenue.com/MP3/leave%20short.mp3";
Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
string downloadFile = "result.mp3";
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception)
{
MessageBox.Show("Unable to add background transfer request.");
}
On the line with adding transferRequest to BackgroundTransferService I get error:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.Phone.BackgroundTransfer.BackgroundTransferRequest.SubmitHelper()
at Microsoft.Phone.BackgroundTransfer.BackgroundTransferRequest.Submit()
at Microsoft.Phone.BackgroundTransfer.BackgroundTransferService.Add(BackgroundTransferRequest request)
at Project.AudioPlaybackAgent.AudioPlayer.CreateBackgroundTransfer()
So is it possible to run transferm from background agent? How can I fix this? Thanks
According to MSDN some API's (including background transfer) are not supported in background agents. Even if you manage to do some things, your app can fail certification tests.
Why not download files in main UI or play it directly from web source?

Background agent task is never executed in Mango

I have a background agent that i would like to be executed in Mango for updating the live tile.
The problem is that it is never executed.
Here is the code that i used:
//start background agent
PeriodicTask periodicTask = new PeriodicTask("BruceWpAgent");
periodicTask.Description = "BruceWp periodic live task";
periodicTask.ExpirationTime = System.DateTime.Now.AddDays(10);
// If the agent is already registered with the system,
if (ScheduledActionService.Find(periodicTask.Name) != null)
{
ScheduledActionService.Remove("BruceWpAgent");
}
ScheduledActionService.Add(periodicTask);
I've found my app name between that Apps that use background jobs but the task is never invoked.
What am i doing wrong?
This code may help you..
string periodicTaskName = "PeriodicAgent";
public bool agentsAreEnabled = true;
private void StartBackgroundAgent()
{
// Variable for tracking enabled status of background agents for this app.
agentsAreEnabled = true;
// Obtain a reference to the period task, if one exists
periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
// If the task already exists and background agents are enabled for the
// application, you must remove the task and then add it again to update
// the schedule
if (periodicTask != null)
{
RemoveAgent(periodicTaskName);
}
periodicTask = new PeriodicTask(periodicTaskName);
// The description is required for periodic agents. This is the string that the user
// will see in the background services Settings page on the device.
periodicTask.Description = "Task to update the Economic times tile.";
// Place the call to Add in a try block in case the user has disabled agents
try
{
ScheduledActionService.Add(periodicTask);
// If debugging is enabled, use LaunchForTest to launch the agent in one minute.
ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromMinutes(2));
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
agentsAreEnabled = false;
}
}
}
Check out this hands on lab for Adding Multitasking to Your Application in Windows Phone 7.5, that should cover it.

Is it possible to check whether the location services are active?

is it possible to check whether the location services are active?
I mean Settings > Location > Location services
There is probably no direct API for calling, but could it work with the GeoCoordinateWatcher?
GeoCoordinateWatcher g = new GeoCoordinateWatcher();
g.Start();
if (g.Permission.Equals(GeoPositionPermission.Granted))
{
//Your location services is enabled. Go ahead.
//Your codes goes here.
}
else if (g.Permission.Equals(GeoPositionPermission.Denied) || g.Permission.Equals(GeoPositionPermission.Unknown))
{
MessageBox.Show("Location services are disabled. To enable them, Goto Settings - Location - Enable Location Services.", "Location services", MessageBoxButton.OK);
}
You can use the following code to determine the status of the Location service:
var watcher = new GeoCoordinateWatcher();
if (GeoPositionStatus.Disabled == watcher.Status)
{
// Watcher is disabled.
}
More realistically, you'll want to pay more attention to change to the status (just because the service isn't disabled doesn't mean you've got location data), so you shoudl take a look at the MSDN Documentation for working with the Location service.
There's also a good post on filtering and emulating location data using the Reactive extensions, which is perfect for that pre-device testing, though to save you time on that front the Widnows Phone Team have released the Windows Phone GPS Emulator.
Even with the started GeoCoordinateWatcher you will get NoData if the sensor is disabled. What you should try using instead is TryStart:
GeoCoordinateWatcher g = new GeoCoordinateWatcher();
MessageBox.Show(g.TryStart(false,TimeSpan.FromSeconds(30)).ToString());
If it returns False, it means that the sensor is disabled. If it returns True, it is enabled. Set an appropriate timeout period (in the snippet above I am using 30 seconds) and delegate this process to a secondary thread, so it won't hang the UI.
You can add a StatusChanged event to your GeoCoordinateWatcher and test for GeoPositionPermission.Denied in the permissions when it fires.
watcher = new GeoCoordinateWatcher();
watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
watcher.Start();
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
if (watcher.Permission == GeoPositionPermission.Denied)
{
// Location services were disabled
}
}
Hope that helps.
Made this one based on TeJ's answer.
public override void OnNavigatedTo()
{
using (var watcher = new GeoCoordinateWatcher())
{
try
{
watcher.Start();
}
finally
{
IsAllowedInSystem = watcher.Permission.Equals(GeoPositionPermission.Granted);
watcher.Stop();
}
}
}
And my apps' ToggleSwitch.IsEnabled is binded to IsAllowedInSystem.
When i'm switching to Location Service, disable it and return back to app, my ToggleSwitch is disabled (also a string "Please, enable Location Service in System settings" in visible). When i'm switching to Location Service, enable it and return back to my app, my ToggleSwitch is enabled and user can set it up.

Resources