Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Part 34: Creating a Background Agent for Scheduled Tasks

Download

Right click “Save as…”

Source Code: http://aka.ms/absbeginnerdevwp8
PDF Version: http://aka.ms/absbeginnerdevwp8pdf

At this point, our AroundMe app is missing just one final feature: the ability to randomly change the lock screen to one of the pictures we've selected every few moments, even if the AroundMe app isn't currently running.

This functionality requires we use a Scheduled Task Agent. The Scheduled Task Agent runs in the background and executes at specific intervals even when our program is not in the foreground -- in other words, when it is not the app you're working with on screen. In our case, we'll schedule the task to run every 30 seconds. When the scheduled task executes, it will call into our LockScreenHelper class' SetRandomImageFromLocalStorage() method.

To enable this functionality we will add a new Windows Phone Scheduled Task Agent project to our current solution. This poses a problem ... we will need to execute the code in our LockscreenHelper.cs from our new project. However, currently this file (as well as its dependencies, the FlickrImages.cs and Photo.cs class files) reside in our main project at the moment. We could merely cut, copy and paste the code files so that they reside in both projects, however the better solution (from a code maintenance perspective) would be to create a third project, a Windows Phone Class Library project, that will house the shared code files, then reference it from both projects. We typically want to share code rather than duplicate it so that any changes or updates can be made in one place and shared by all dependents.

Our game plan:

  1. We'll add a new Windows Phone Scheduled Task Agent project to our Solution
  2. We'll add a couple lines of code that will call the SetRandomImageFromLocalStorage() method and allow us to test it in the emulator
  3. We'll add a new Windows Phone Class Library project in our solution and will move our three class files into it that will be shared between the other two projects.
  4. We'll move those code files into the Windows Phone Class Library, we'll use NuGet to add in Newtonsoft's JSON library and the Microsoft.Net.Http library package, we'll clean up the namespaces and so on.
  5. We'll create references from the AroundMe project and the Scheduled Task Agent project to our new Class Library project.
  6. In the main AroundMe project, I'll need to introduce the Scheduled Task Agent to the operating system by launching it when AroundMe starts up, and configure the WMAppManifest.xml to be an extension in order to allow our app to be a Lock screen Background Provider.
  7. And if all goes well, we'll run it and watch the fireworks.
  8. I'm not going to submit this app to the store ... we've already seen that process in lesson 23, but I will show you some last steps required before submitting the app to the store, including how to get a token to properly license and use Map Services in your Phone Store app.

 

1. Add a new Windows Phone Scheduled Task Agent project to our solution called AroundMe.Scheduler

I don't believe I've ever demonstrated how to add a second project to a solution in the C# Fundamentals series. Assuming you do not know how to do this ...

 

  1. Right-click the solution name in the Solution Explorer
  2. Select Add
  3. New Project ...

The Add New Project dialog appears:

 

  1. Select the Visual C# Windows Phone templates
  2. Select Windows Phone Scheduled Task Agent project template
  3. Name it: AroundMe.Scheduler ... we'll use a common notation when naming projects, the dot notation, to match what we want the default namespace for our code in this project to have
  4. Click OK

You should now see a second project in the Solution Explorer. The most important part of this project is the ScheduledAgent.cs class.

 

 

Most of code in the ScheduledAgent.cs file is "boiler plate" meaning we will not need to change it, but it must be there in order to create a valid Scheduled Task Agent. However, if you scroll down near the bottom of the file, in line 41 you'll find the OnInvoke() method with a TODO comment. This is where we'll implement our code as follows:

 

 

As you can see, I added a TODO. We'll come back here later and add code that will set the random image from local storage. We have a little setup work to do first.

Before we do that, I've added one line of code (with about 10 lines of comments) that explain it's purpose. I copied it from this source:

http://msdn.microsoft.com/en-US/library/windowsphone/develop/microsoft.phone.scheduler.scheduledactionservice.launchfortest(v=vs.105).aspx

So, line 61 of the code snippet above:

ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));

... is merely for testing purposes in the Phone Emulator. This allows developers to watch the behavior of the task every 30 seconds. Otherwise, as we'll learn in a moment, when our app is deployed to a real Phone device, it will only run once every 20 to 40 minutes. More about that in just a moment.

As the comments above it explain, we need to either remove this line of code, or at least wrap it in an if statement like this:

if (Debugger.IsAttached) {

}

The original article references this additional background information:

http://msdn.microsoft.com/en-US/library/windowsphone/develop/hh202942(v=vs.105).aspx

That article is very important for our purposes, and if you think you need to do some background processing or scheduled processing, you MUST read that article. In a nutshell, there are two types of background tasks: ResourceIntensiveTasks and PeriodicTasks. Resource Intensive tasks run in the background because they may take a long time to complete ... they're processor intensive. PeriodicTasks run at set intervals. In our case, we're creating a PeriodicTask.

There are different rules and constraints depending on the type of background task we're working with. Both ResourceIntensiveTasks and PeriodicTasks share the following constraints:

  1. An application may have only one background agent, and only one instance of the agent runs at a time.
  2. We're limited by which of the Phone's APIs we can utilize from a background task
  3. We're limited by the amount of the phone's resources we can use ... no more than 11 megabytes for an application like ours
  4. Our scheduled task will only work for two weeks before it needs to be rescheduled by re-running the AroundMe app
  5. If our app crashes twice in a row, it will be unscheduled by the operating system

    In our case, since we're working with PeriodicTasks, we need to be aware of a few additional things:
  6. Our task will run about every 30 minutes, however the phone's operating system decides when to run the tasks. In fact, it might run ALL scheduled tasks at the same time because it's more efficient to use the phone's battery once every 30 minutes than a bunch of times during that same period for each individual Scheduled Task that wants to run. So, that 30 minute time frame can drift as much as 10 minutes in either direction. So, when we deploy our AroundMe app to a phone, it will change image every 20 to 40 minutes or so.
  7. Our Scheduled task can only run for 25 seconds before it is shut down by the operating system. That shouldn't affect us, but we should be aware of that for future reference.
  8. If the battery is low and the phone goes into Battery Saver mode, then our Scheduled Task may not run at all. If you have a Windows Phone 8 and your batter gets low, you'll see a little heart icon over the battery meaning that it has shut down scheduled tasks, turned off some of the functionality of the phone like the GPS and Bluetooth radio and more. Users can configure how aggressive they want Battery Saver to be in the Settings screen. I have a battery monitoring app on my start page, and I was getting low on battery, then I noticed that Battery Saver mode kicked in and I had 20 hours left. That's because it was throttling what was going on in the background. So, be aware of that when you create your own Scheduled Tasks.
  9. Finally, depending on each phone's configuration, there may be a limit to how many background agents can run at the same time. A few days ago I hit that limit and it asked me to choose some background tasks to shut down because the phone was low on memory.

So, if you plan on submitting a phone to the Store you'll need to be willing to support users. If you want to support your users, you'll need to know a little about how the phone and the operating system work with your app. If the user complains that their background is not changing often enough, you might want to ask a few questions about how many apps are currently running.

To see what's running in the background, go to your Windows Phone's settings, swipe over to the applications page. There you will find "background tasks" setting at the top of the list. Once inside the settings, you'll see a list of all the apps running in the background. To shut it down, just tap on the app and tap the "block" button. To confirm that you've shut down the app, press and hold the back button to view any open apps.

At any rate, that article also does a nice job of explaining the general lifecycle of a background agents. From the article:

"When the agent is launched, the operating system calls OnInvoke(ScheduledTask) ... When the agent has completed its task, it should call NotifyComplete() or Abort() to let the operating system know that it has completed. NotifyComplete should be used if the task was successful. If the agent is unable to perform its task – such as a needed server being unavailable - the agent should call Abort, which causes the IsScheduled property to be set to false."

So that is the purpose of the NotifyComplete() in line 63 of the code snippet above.

Again, we'll come back and revisit the TODO comment in line 45 after we've moved our class files from our main AroundMe project to a new Windows Phone Class Library project, which we'll do next.

 

2. Create a new Phone Class Library called AroundMe.Core and move class files to it

Just like in step 1, we'll add a new project to our solution. So, right-click the our solution entry in the Solution Explorer, select Add, New Project ... In the Add New Project dialog ...

 

  1. Select Visual C# Windows Phone templates
  2. Select the Windows Phone Class Library project template
  3. Rename to AroundMe.Core ... again, we're following a naming convention that will produce a namespace that we want to use in our solution. The term "Core" indicates essential functionality that will be utilized in other projects
  4. Click OK

Your Solution Explorer should look like this, with one solution and three projects:

 

 

NOTE: I deleted the Class.cs file from the new AroundMe.Core project. We won't need it. Selected it and hit the delete key on your keyboard.

Next, I'll drag my three class files:

  • FlickrImage.cs
  • LockScreenHelper.cs
  • Photo.cs

... from the AroundMe project to the AroundMe.Core project. THIS WILL MERELY COPY THE FILES ... you now have two copies of the files.

In the AroundMe project, select those three files and delete them. Those three files should only appear in your AroundMe.Core project:

 

 

Next, since these files depend on third-party or optional packages, we'll need to use NuGet to import the into our new AroundMe.Core project.

If it's not already open in Visual Studio, go to the Tools menu, select Library Package Manager menu option, then the Package Manager Console sub menu.

In the Package Manager Console:

 

 

  1. Make sure the Default project is set to: AroundMe.Core
  2. At the Package Manager prompt, type: install-package Newtonsoft.Json
  3. Ht enter.

Assuming that completes successfully ...

 

  1. At the Package Manager prompt, type: install-package Microsoft.Net.Http
  2. Ht enter.

We've talked about both of these before, so I'll not review that now. These are simply dependencies that the class files we moved will need. Confirm everything installed correctly in the Solution Explorer:

 

 

... your references should match what I have in the AroundMe.Core project.

Just to make sure everything works IN THAT PROJECT, right-click the AroundMe.Core project name in the Solution Explorer and select Build from the context menu:

 

 

... assuming everything builds without any errors, we're ready to reference our new Windows Phone Class Library project from our main AroundMe project and the Background Task Agent project.

In the Solution Explorer, in the AroundMe project, add a reference to the AroundMe.Core project:

 

3. Add reference from AroundMe to AroundMe.Core and fix any lingering problems from the refactoring

 

  1. Right-click References
  2. Select Add Reference ...

When the Reference Manager dialog appears ...

 

  1. Navigate to the Solution | Projects tab
  2. Place a check-mark next to AroundMe.Core
  3. Click OK

Now it's time to clean up our AroundMe project's source code. When you move things from one project to another, there's bound to be some problems. In our case, we need to comb through our code and make sure our AroundMe project can find the same code in the new AroundMe.Core Class Library project.

In the SearchResults.xaml.cs class, in the appBarButton_Click click event, I find my first problem ... I hover my mouse cursor over the blue squiggly line:

 

 

... and it tells me: "AroundMe.LockScreenHelpers is inaccessible due to its protection level".

When I see the term "protection level", that usually means a visibility problem ... in other words, our old code can't "see" our new code. And usually that's because I'm missing an accessibility modifier in the new code.

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

 

 

At this point you may need to re-build the AroundMe.Core project in order for the warnings in the SearchResults.xaml.cs class to go away.

But now that I'm looking at my LockScreenHelpers.cs class, I see something else ... I've moved these three files to a new project, and named the project deliberately to be in a different namespace. However, since I merely copied those files, the declared namespace remains as it did before ... simply:

namespace AroundMe { }

But do I want the namespace to be AroundMe? I think I would prefer it to match the project name, AroundMe.Core ... so I make that change to each of the class files in my AroundMe.Core project:

 

 

After I make that change, I Build the AroundMe.Core project again.

Now, I'll need to add a using statement to the SearchResults.xaml.cs file so that the compiler knows where to look for the LockScreenHelpers class:

 

 

By simply adding the:

using AroundMe.Core;

... to my using statements, that should fix any namespace problems I introduced with this change.

 

4. Create a reference from AroundMe.Scheduler to AroundMe.Core and write code to set background lock screen image

In the Solution Explorer:

  1. Right-click the References entry of associated with the AroundMe.Scheduler project
  2. Select Add Reference...

That will display the Reference Manager dialog ...

 

 

  1. Select the Solution | Projects tab
  2. Place a check-mark in the box next the to AroundMe.Core project
  3. Click OK

Next, add the following using statement to the ScheduledAgent.cs file:

using AroundMe.Core

 

 

In that same file, in the OnInvoke method near the bottom, it's time to revisit the TODO comment we added earlier.

We'll make the following changes to that method:

  1. Add this line of code at the top, removing the TODO comments: 
    ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
  2. Add the async modifier to the method declaration. We've talked about this at length in lesson 27.

 

5. Modify the AroundMe project's App.xaml.cs to introduce the background scheduled task agent to the operating system

Finally, we'll need to register our new background scheduled task agent with the operating system. We'll do this when our AroundMe app first starts up, so we'll be adding the code to the App.xaml.cs which handles the Application_Launching event.

In the App.xaml.cs file, add the following code to the Application_Launching event handler method stub:

 

 

There are two basic activities in this code passage:

  • Lines 65 - 72 -- Here we are trying to find any running versions of our background scheduled task agent. If it is running, we'll want to remove it from the ScheduledActionService which acts as a registrar for the operating system's scheduled tasks.
  • Lines 83 - 90 -- Here we create an instance of our background scheduled task agent and register it with the ScheduledActionService.

Why do we try to remove it, then re-add it? Keep in mind what we said earlier ... after 2 weeks, our scheduled tasks will be de-scheduled. This little dance simply keeps our background scheduled task agent scheduled and operating for another two weeks.

Notice that we set the task's Description property in line 84 ... this will be displayed to the end user if they look at the background tasks in Settings at the very bottom of the page where you can choose to block the app. It's a good reminder to the user of what this particular background scheduled task agent is doing ... in case they've forgotten that they installed your app.

  • In line 88 I'm creating this LaunchForTest() method like I did in the AroundMe.Scheduler to schedule the background task for its first execution for development purposes in the Phone Emulator.
  • Lines 74 - 81 -- this is a reminder to me and you ... we'll need to open up the WMAppManifest.xml file and add this ExtendedTask element.

We've already done this once or twice, but just to refresh your memory:

 

 

  1. In the Properties section / folder ...
  2. Right-click on the WMAppManifest.xml file ...
  3. Choose Open With ... from the menu

From the Open With dialog:

 

 

  1. Select XML (Text) Editor with Encoding
  2. Click OK

You will be asked about the "encoding" part in the next dialog:

 

 

Simply leave the "auto-detect" option and click OK.

We'll want to make changes INSIDE of the <Tasks> element, below the <DefaultTask> element like so:

 

 

We'll add the following XML:

<ExtendedTask Name="AroundMeLockScreenChangerTask">
<BackgroundServiceAgent Specifier="ScheduledTaskAgent" Name="AroundMeLockScreenChanger" Source="AroundMe.Scheduler" Type="AroundMe.Scheduler.ScheduledAgent" />
</ExtendedTask>

What does this do? Per this web page: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769509(v=vs.105).aspx

... in the section titled "ExtendedTasks Element" about mid-way through, it says:

"The ExtendedTasks element is a child of the Tasks element and contains BackgroundServiceAgent elements. This element defines the use of multiple tasks by an app. Extended tasks are named by the developer. Currently, you can use the ExtendedTasks element only to define background tasks."

Remember, the WMAppManifest.xml is there mostly for certification purposes into the Store, and is used to introduce your app to the phone's operating system and allow it to become part of the phone's ecosystem. Here's a great example ... we tell the phone's operating system that we want this part of our app, the AroundMe.Scheduler to be included with the other background task agents that are currently running. We're registering with the background task agent scheduler to let it know what we want it to run within our app, namely, the AroundMe.Scheduler, we give it a name, a description and so on.

In order for the main AroundMe app to register our AroundMe.Scheduler, we'll need to add a reference to it:

 

 

  1. In the AroundMe project, right-click the References folder
  2. Choose Add Reference ...

This will pop up the Reference Manager dialog ...

 

  1. Choose the Solutions | Project tab
  2. Place a check-mark next to the AroundMe.Scheduler project
  3. Click OK

Now we should be able to run our application in the Phone Emulator to see it at work.

 

5. Run the app in the Phone Emulator to make sure it works.

When running the app from a previous try, you may have left it on the lock screen to see whether or not it worked. If you did leave the Emulator on the lock screen, you may see this error message:

 

 

You merely need to unlock the Phone Emulator's lock screen by hitting F12 on the keyboard and / or use the swipe motion to unlock the phone. Then you can re-run / debug the app.

To test this, you just need to go through our usual script ... i.e., search, select a few Flickr images, click the Set button, approve the dialog boxes that appear, then hit the F12 key on your computer's keyboard twice to simulate clicking the phone's power button twice to lock then awaken the phone. Undoubtedly your photos will look different from mine.

 

 

After 30 seconds (maybe a little more, maybe a little less) it should change images to another of your selections.

 

 

And so we've completed the development of our project successfully!

But wait, there's just one or two more things we need to do before we submit this for inclusion in the store.

 

6. Clean up the code removing development only code, adding other details before submitting to the Store

There are a few final steps that we would need to take before we're ready to ship this and submit it to the Store for inclusion.

First, you'll recall in this lesson we used the LaunchForTest() method a couple of times to test the scheduled background task agent. Remember this?

 

 

We'll need to search the entire solution for the LaunchForTest method ... recall we have a reference to it as depicted (above) in the AroundMe.Scheduler project's ScheduledAgent.cs file as well as in the AroundMe project's App.xaml.cs file. As I said earlier, you either want to comment these out OR wrap them in a check for the debugger:

if (Debugger.IsAttached) {

}

Obviously we'll want to thoroughly test our app. I would recommend allowing friends and family to use it, or better yet, find a group of developers in your area that would be willing to take a look and make recommendations. I was at a Nokia developer event recently and there were a lot of developers exchanging business cards and showing each other what they were working on. This can be a great way to inexpensively find testers, and to build some contacts in the development community. So, I would recommend getting involved by checking in on their Events page:

http://www.dvlup.com/Events

Another option is to locate the Microsoft developer evangelist in your area and ask them if they have any events scheduled. I would search for something like:

  • Microsoft developer evangelist [Your city, state, region or country here]
  • windows phone user group [Your city, state, region or country here]

NOTE: You may have to be creative and try different wording to find a group or evangelist near you.

Developer evangelists usually have blogs, twitter accounts or mailing lists through MSDN or TechNet that you can subscribe to in order to learn about meet-ups, user groups or code camps in your local area. Or you could always write the developer evangelist an email and introduce yourself.

Once you're ready to submit to the store, you should pay particular attention to the APIs you'll be calling. For example, we used the Windows Phone 8 Maps control and Flickr. Make sure the account you're using is up to date, and you're using the correct credentials.

With regards to the Map control, we will need to get an ApplicationId and an Authentication Token from the developer center. For a full explanation of this, check out this page:

http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207033(v=vs.105).aspx#BKMK_appidandtoken

In a nut shell, I'll add a Loaded event handler:

 

 

And will implement the code like so ... I've comment it out for now:

 

 

If you recall from Lesson 23, we saw an optional set of tasks including Map Services ...

 

 

... this is where you would retrieve the token and the application id required to the use map services in your app. You would merely replace those literal strings with the supplied tokens from the store.

 

Recap

To recap, the big takeaway was how to create a scheduled task and share common code in a library, and how to test the scheduled task in the Emulator. We also learned about final steps, not the least of which is how to receive a token for Map Services.

In the next lesson, I'll have just a few comments and will wrap up this series.

Tags:

Follow the Discussion

  • 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.

  • 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).

  • Clint RutkasClint I'm a "developer"

    @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!

  • ViDaoViDao

    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,

  • ViDaoViDao

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

  • @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.

  • Clint RutkasClint I'm a "developer"

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

  • GeethaGeetha

    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.

  • Clint RutkasClint I'm a "developer"

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

  • GeethaGeetha

    @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?

  • Clint RutkasClint I'm a "developer"

    @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, ...

  • GeethaGeetha

    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.

  • Clint RutkasClint I'm a "developer"

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

  • Clint RutkasClint I'm a "developer"

    @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

  • AravindAravind

    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?

  • @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

  • AravindAravind

    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:

    http://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 :)

  • AravindAravind

    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.

  • Clint RutkasClint I'm a "developer"

    @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]

  • AravindAravind

    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.

  • Clint RutkasClint I'm a "developer"

    @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.  http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202941(v=vs.105).aspx and http://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

  • MichaelMichael

    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?

  • Clint RutkasClint I'm a "developer"

    @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!

  • Richard GarciaRichard 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)

  • Clint RutkasClint I'm a "developer"

    @Richard Garcia: did the background change from part 33?  http://channel9.msdn.com/Series/Windows-Phone-8-Development-for-Absolute-Beginners/Part-33-Working-with-the-Lock-Screen-to-Display-an-Image

  • Richard GarciaRichard 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.

  • Clint RutkasClint I'm a "developer"

    @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.

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

  • Clint RutkasClint I'm a "developer"

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

  • 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?

  • Clint RutkasClint I'm a "developer"

    @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.

  • 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.

  • Clint RutkasClint I'm a "developer"

    @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 http://dev.windowsphone.com or www.stackoverflow.com

  • MarkMark

    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

  • Clint RutkasClint I'm a "developer"

    @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.

  • VarijVarij

    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.

  • Clint RutkasClint I'm a "developer"
    @Varij: can you be a bit more descriptive of he exception?
  • Clint RutkasClint I'm a "developer"

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

  • HeenaHeena

    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 :(

  • Seke1412Seke1412

    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?

  • @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.

  • Clint RutkasClint I'm a "developer"

    @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?

  • VinuVinu

    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?

  • TillTill

    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?

  • 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

  • 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.

Remove this comment

Remove this thread

close

Comment on the Post

Already have a Channel 9 account? Please sign in