Part 34: Creating a Background Agent for Scheduled Tasks

Sign in to queue

The Discussion

  • User profile image
    wsantosf

    I believe the image after:

    "In my LockScreenHelpers.cs file I add the public accessibility modifier to the class declaration:"

    has been switched with the one from paragraph 4 further down the page.

  • User profile image
    tbarrasso

    Are you going to put together a series for Advanced Development? I love these videos and although I've been doing iOS and Android development for 2+ years, my first attempt at a Windows Phone 8 app is a struggle as I feel documentation is sparse (especially for WPtoolkit et al).

  • User profile image
    Clint

    @tbarrasso: for items like the Coding4Fun Toolkit and Phone Toolkit, most of the documentation is from the actual sample application that is included with the source code.  I know personally with the coding4fun toolkit, it is a todo on my list of things to get done but good documentation is a lot of work and takes time!

  • User profile image
    ViDao

    Dear,
    When I run app, the File Not FoundException was unhandled. I think maybe Change Background Task run before any file was set to IsolatedStorageFile.
    Help me to fix it please.
    Thanks && BestRegards,

  • User profile image
    ViDao

    Dear,
    I fixed it because of I do not set Source for BackgroundServiceAgent correctly.
    Sorry for the comment,
    Best Regards,

  • User profile image
    tbarrasso

    @Clint:That makes sense, thanks! Looking forward to documentation improvements, and if not perhaps more comprehensive samples. Most of the sames only show one or two items and often in their simplest forms (i.e. ContextMenu does not have a sample that shows it being used properly with a LongListSelector). I'd love advanced and "putting it all together" samples.

  • User profile image
    Clint

    @tbarrasso: the community has a ton of samples and documentation on both coding4fun toolkit and phone toolkit.

  • User profile image
    Geetha

    Why should ScheduledActionService.LaunchForTest() be called in 2 different places, in the Invoke event handler of ScheduledAgent and in Application_Launching event in App.xaml.cs? Please clarify.

  • User profile image
    Clint

    @Geetha:  You don't need to call LaunchForTest, it just helps do an instant check.  It is pure testing.  https://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.scheduler.scheduledactionservice.launchfortest(v=vs.105).aspx

  • User profile image
    Geetha

    @Clint: I understand it is for pure testing. But even from a testing perspective, what it does mean when it is called in the Invoke event handler of ScheduledAgent vs in Application_Launching event in App.xaml.cs? And why was it done in both places in this demo?

  • User profile image
    Clint

    @Geetha: Background task launches are handled by the OS, not invoked.  Part of it is you want to verify your task got properly hooked in along properly executes over and over again in different scenarios such as your app isn't running or the lock screen is up, location services aren't enabled, phone is in airplane mode, ...

  • User profile image
    Geetha

    Sorry, I am still not clear why LaunchForTest() has to be called twice for this demo to work. Looks like Microsoft has not done a good job on this. They should provide a cleaner solution for this.
    Also, since it gets called only in Debug mode, how does the agent get launched automatically in release mode? What will be the delay time used in release mode? May be I am missing something here. Sorry I am still confused.

  • User profile image
    Clint

    @Geetha: it doesn't.  It is there in both locations purely for testing in both locations

  • User profile image
    Clint

    @Geetha: Let me rephrase this, I [I created both samples] added those lines in for testing.  I found having both there were useful so the background service would constantly fire off along with instantly fire off when I started the application.

    to me: quicker debugging == awesome Smiley

  • User profile image
    Aravind

    I think this approach of using Client library for the app and the scheduled agent work only if the client library is stateless. How do we share the same instance of the client library between the app and the scheduled agent project?

    For example, in the client library I have something like the following:

    static class Foo {
    static int x = 0;
    public static void SetValue(int y)
    {
    x = y;
    }

    public static int GetValue()
    {
    return x;
    }

    }

    I was trying to set the value in the App by calling:

    Foo.SetValue(23);

    And in the scheduled agent code, I tried retrieving it by:

    Foo.GetValue();

    I expected 23 to be returned, but what I got was zero.

    The reason why I am doing it is that my client library stores some data to the local database.

    And my periodic agent needs to query the data from the database.

    When my periodic agent runs, it doesn't see the data set by the app.

    I believe the client library creates another database when it is referenced by the scheduled agent app.

    Any idea how I overcome the problem?

  • User profile image
    BobTabor

    @Aravind: Let me start by asking which database you're using?  Is that a common behavior of that database?  Perhaps THAT'S the problem.  If you could revert back to a text / xml / json file or something you can control in a central spot in the app's folder structure, you might be able to overcome this.  My solution personally would be to utilize Azure in some way, but again, that's just me and it may not fit every circumstance.

    You're probably right ... there are two instances of that class being created.  But being "stateless" doesn't sound like the solution alone ... the things we were doing in our example were ATOMic in nature.  I would test the behavior of the database and see if it indeed creates multiple instances and if there's a way to avoid that behavior in settings / etc.

    Good luck!  I've never tried what you're doing, so you're breaking new ground here.  Smiley

  • User profile image
    Aravind

    Dear Bob,
    Thanks for getting back to me quick. What I have is the following:

    [Database]
    public class MyDataContext : DataContext
    {
    private static readonly string db_string = "Data Source=isostore:/MyDB.sdf";

    public MyDataContext()
    : base(db_string)
    { }


    public Table<Table1> myTable1;
    public Table<Table2> myTable2;

    }

    I went through the following documentation to set it up:

    https://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202860(v=vs.105).aspx

    Right now all the DB code is buried in the client library and the client library stores some data to the DB.

    What I am doing right now, read the data and post it to an endpoint.

    Every thing works fine so far.

    I read upon background tasks lately, thought of implementing with using periodic task agent to see if there are any data in the DB.If it is, then read them from the DB, post it to an endpoint.

    This way I would be sending all latest data stored in the DB to be sent to the server.

    Please advise.

    Thanks a lot!

    PS: I just started Windows 8 phone development in the last month and I am new to the world of .Net :)

  • User profile image
    Aravind

    Hi,
    I spent some time and found that the DB is actually shared when you refer the client library with the phone app and the scheduled task agent app. In the client library I have a flag which I have to enable which I did in the phone app, but not in the scheduled agent app. As the flag was false, it resulted in nothing and I thought it created a different DB entirely.

    Still I am not convinced with the way we got to add the client library to both the apps.

    Let's say I internally maintain a flag which is set by the phone app. Based on the state of the flag, let's say I need to run something in the scheduled agent app, it will never work as the client library runs as 2 different instances.

    Example:
    Phone App calls the client library and set something:

    client.setFlag(true);

    And I need to retrieve it in the scheduled task agent code as:

    client.getFlag(); then I won't get the value set by the app.

    Anyway Windows 8 development is really interesting and I like to develop a lot.

  • User profile image
    Clint

    @Aravind: So first, we're here trying to keep questions on the video.

    Next, what I think you're misunderstanding how a static works along with how your application and the background service live.  The background service is separate.  It gets brought up / down by the operating system.  It does not always live in memory just like your application won't as well.

    If you want to do some smart caching of data, I'd suggest serializing an object and storing it in either ISO or the app settings [think a background service has access to this, I'd heavily recommend doing a quick, small scale test]

  • User profile image
    Aravind

    Thanks, Clint for your quick response. I may have used a bad example to explain the scenario above. My thought was that why we need to have a separate background agent project to be created to support the background task feature.

    I am curious to understand why it is created as a separate project? What I see in the project is a single class that extends another class and we put the biz logic in the OnInvoke() method. Cab't this class be embedded as part of the client library or the app? And annotate the class so that the OS knows the class is for running background jobs, treats it the same way as it treats the background task app.

    Anyway there must be some valid reason behind this approach (creating a new project of type windows background) and I don't want to comment on it.

    In my case, the client library stores some data in the DB and the dispatch timer runs every few minutes to query the DB. If data is present, then it submits the data to the server.

    If there is no data, then it stops the timer so that the timer doesn't run all the time to go query the DB. When I insert a row of data, then I turn on the timer.
    My intention is not to run anything even if it is something to do with creating a simple object. Example: string s = "foo";

    As we all know the app is going to run on a cellphone device and we know the limitation of creating objects, making networking calls, querying DB on the tiny device :)

    Coming back to the background task, its job is to go query the DB to see if there are any data in the DB and submit it to the server.

    For example, if my timer runs every 5 minutes and a user uses the app for a few minutes and backgrounds it, the timer never gets a chance to run.

    In this case, the periodic task running every 30-40 minutes will query the DB, submits data to the server so that I am not losing any data.


    I wanted to set a flag which indicates if the DB is empty or not. I wanted to preserve it in memory so that when the flag is true, the periodic task just reads it and doesn't do anything than go query the DB and make an expensive call.

    And this flag is set when the app is running.

    Example:

    App-> Client Library-> Read DB

    bool isDBEmpty = false;

    When count is 0, set the flag to True. (isDBEmpty = True)

    Background Task -> Client Library -> Read isDBEmpty.

    When it is True, don't do anything, just exit.
    If it is false, query the DB , submit to the server.

    This should have worked when the ScheduledAgent.cs is part of the library itself with some special annotations telling the OS it is background and the flag set is visible to the ScheduledAgent class as well.

    Anyway as you suggested, either I have to either set the value in ISO / app settings or query the DB to set if there is data in there.

    Thanks for your tip.

    Thanks again for your time.

    Have a good weekend!

    PS: All your video tutorials made me learn .Net and Windows in no time. Thanks for sharing all these.

  • User profile image
    Clint

    @Aravind: a background process is just that, a background process that runs separately of your application.  It spins up, does work, then spins back down again.  While the two are related, they are separate.  I'd suggest looking at the MSDN documentation on background processes for Windows Phone.  https://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202941(v=vs.105).aspx and https://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx

    For questions that aren't related to the video at hand [as this is], I suggest heading over to either the forums on http://dev.windowsphone.com or www.stackoverflow.com

  • User profile image
    Michael

    I'm developing a new app that will download than then change the image on the lock screen (that works great). Know I would like to be able to put text in the upper part of the lock screen but I don't know how that is done. For example how to the weather apps do this?

  • User profile image
    Clint

    @Michael: awesome job you're doing that!  The comments here we are trying to keep on task to only the videos.  With that said, I did a quick bing search: http://www.bing.com/search?q=windows+phone+adding+text+to+image&qs=n&form=QBRE&pq=windows+phone+adding+text+to+image&sc=0-18&sp=-1&sk=

    and hit: http://stackoverflow.com/questions/15083325/adding-text-to-cycle-tiles-windows-phone-8

    two great spots are www.stackoverflow.com and the forums over at http://dev.windowsphone.com for questions like these!

  • User profile image
    Richard Garcia

    I have everything you have, but when I test it on my device the wallpaper is not changing at all. Any tips on what could the problem be??

    ( What I do is I deploy the app to my device, and then open the app that is saved on my device)

  • User profile image
    Clint
  • User profile image
    Richard Garcia

    @Clint Yes it did. it changes the first time but the background task never seems to execute and I have it enabled and all.

  • User profile image
    Clint

    @Richard Garcia: can you zip up your solution and create a bug over at https://absolutebeginner.codeplex.com/WorkItem/Create so I can do a quick glance with a debugger.

  • User profile image
    richddr

    @Clint already created, here is the link to it: absolutebeginner.codeplex.com/workitem/1222

  • User profile image
    Clint

    @richddr: Hey Rich, found the typo and responded / closed the bug.  Was super subtle, took me a while to spot it

  • User profile image
    pari

    Hi

    i have created the agent and am setting the images to live tile form service but as image size is large those images are cutting on tile.Is there any solution to fit large image to tile from scheduled task agent?

  • User profile image
    Clint

    @pari: thought our version properly gave a smaller version of the image for the tile.  You can do a writable bitmap and resize the image accordingly is an option or get the properly image from flickr.

  • User profile image
    raghuramr4

    I am trying o create a app with the concept of Scheduling the SMS, and I see most of the apps display the popup and user had to interact with device to accept and send. is there any other option such as create a task at background and send out SMS / Email.

  • User profile image
    Clint

    @raghuramr4: SMS and email use tasks and require the user to do the final consent.  You can use an external service to accomplish this if you choose.

    This question is off topic from the video, for stuff like this, I suggest the forums over at https://dev.windowsphone.com or www.stackoverflow.com

  • User profile image
    Mark

    Hi,
    Thank you for the videos, amazingly helpful. Quick question : did you try to submit this app to the store for verification ? I ask because when I submitted an app that uses the location service on the phone, my app didn't pass for the following reasons :

    1- Your app must provide in-app settings that allow the user to enable and disable your app's access to and use of location from the Location Service API.

    2-The application does not include a privacy policy explaining how the application uses the location service API.

    I'm just curious if this is applicable to all apps that use the location service.

    Thanks
    Mark

  • User profile image
    Clint

    @Mark: We intentionally didn't cover any store submission stuff as it can change.  Makes supporting a video series hard since updating can change context of the past comments.

    Yes, with current store rules, you need a privacy policy (as one app may use location differently than another) and a way for an end user to turn off the location service for the application.  Check out the Twitter Windows Phone app for as an example.  They have both in their settings page.

  • User profile image
    Varij

    I downloaded the source code from the above links, but when i tried to run the app, it starts fine, but while searching for the images it stops with an error with an unhandled exeption occurs. Please help.

  • User profile image
    Clint
    @Varij: can you be a bit more descriptive of he exception?
  • User profile image
    Clint

    @Varij: I just downloaded and ran the code (in emulator) for lesson 34.  It didn't throw an exception.

  • User profile image
    Heena

    Hi, I am using SharedMediaTask in my app.
    On click of a button on a page I used to navigate->page with images->select one of the image -> share using ShareMediaTask
    It is working fine.
    But if I use button of data template & do the same on its click navigate->page with images->select one of the image -> share using ShareMediaTask the app crashes saying "System.Runtime.Serialization.debug.resources.DLL'. Module was built without symbols."
    Please help.
    I have done lot searching ...but :(

  • User profile image
    Seke1412

    Hi Bob;
    Your tutorial is really great, I've just successfully build this app. But i recognize that the Tile doesn't change, did I do something wrong? or this is it?

  • User profile image
    BobTabor

    @Seke1412: You mean the lock screen doesn't change?  If so, then Angel you may have to wait a while for it, and / or (b) restart the entire process ... restart the debugging session, restart Visual Studio, restart your computer.  (c) Try deploying to your device.  It works (assuming you've got the code and the project correctly configured) but I did notice some lag the first time I ran it.

  • User profile image
    Clint

    @Seke1412: are you sure you added the few lines into the WMAppManifest.xml file?  Did you set a break point to see if stuff is actually firing in the worker role?

  • User profile image
    Vinu

    Hello, I have my tests running against Windows phone 8 and the tests doesn't execute when the screen locks and would like to have the device not lock at all. When my windows phone 8 application page is on the foreground, the screen doesn't lock at all but when it moves away, the screen gets locked after the lock screen time set in the phone settings. So, I'm trying to create a backgroundagenttask to check whether the state of the screen is locked and if so to unlock it. Is this possible?

    Note: I tried Idledetection mode of PhoneApplicationService to disabled but it doesnt work, when the focus is moved from the application page. Could you please share your thoughts?

  • User profile image
    Till

    The ExtendedTask Element in WMAppManifest.xml is automatically created if it´s referenced in the Windows Phone 8 project. Why would you drclare it by hand?

  • User profile image
    mrobbins

    Getting the exception is Response status code does not indicate success: 404 An exception of type HttpRequestException' occurred in mscorlib.ni.dll

    in SearchResults.xaml.cs in the SearchResults_Loaded method for line var images = await FlickrImage.GetFlickrImages(

    This exception is sporadic

  • User profile image
    mrobbins

    The exception is also appearing in line

    awaitLockScreenHelpers.SetRandomImageFromLocalStorage();

    of the ScheduleAgent.cs OnInvoke method. This exception occurs in my code and the downloaded source code.

Add Your 2 Cents