So the topics we are going to cover in this post are:

  • Windows Phone Task Management
  • Multi-Tasking with Background Agents
  • Creating tasks in Visual Studio
  • File Transfer Tasks
  • Background Notifications
  • Background Music Playback Tasks

Prerequisites

  • Must have .Net and Silverlight development experience
  • Must have developed a windows phone apps.

Lets start

 

Windows Phone Task management

Forground Tasks

  • Normally a windows phone application runs in the foreground and interacts with the screen and user of the phone
  • There is only one foreground application active at a time though other may be running but are not active. This ensures better battery life for the user.

Background Tasks

  • A Windows Phone application can have only one background agent which can perform perodic tasks or resource intensive tasks or both.
  • The Agent can run when the application is not in the foreground.
  • The background tasks have limitations to what it can do and processor and other phone facilities. The logical reason that microsoft architect give is that if a background tasks goes out of control or does what it is not intended to do somehow it should not affect the battery life of the phone and the user user experience as well.
  • A background task can be used used to conatc the datbase and get the updates every half an hour or play music from a server online.

Background Agent Health Warning

  • There can only be limited number of background agents running at a point of time and this controlled by the oprating system.
  • A background agent will be started only when the operating system can give the agent processor resource.
  • If the phone goes to power saver mode then the background agents may stop running.
  • Also at any point of time the user can see the background tasks running and can manage them and choose to disable them.
  • So dont put any critical logic in background agent as it may not run. Its like icing on cake.

Multitasking with background agent

Agents and Tasks

  • The Agent is the container that is manged by the operating system and agent is the code that will run.
  • There are two kinds of tasks
    • Perodic
      • Will run every now and then (typicallyevery 30 minutes or so).
      • Intended to perform a task that runs regulary and complts quickly
      • Phone will have of limit on how many of them can be running.
      • Good for location tracking tracking and polling background services.
    • Resource intensive
      • Will run when the phone is in a postion to let them. This means it will run when
        • The phone is connected to mains
        • The phone is connected to Wi Fi
        • The phone is not being used (lock screen is displayed)
      • So if you rellay need this to run you need to made some recomendations to the user so that this resource intensive task runs successfully.
      • A Resource intensive agent can run upto 10 minutes.
      • Good for synchronization with host service, unpacking / preparing services, compressing database.

Dual Purpose Agents

  • An application can run both periodic and resource intensive tasks.
  • Can be achived though single background agent class.
  • When the agent start it can determine in which context it is running and behave appropriatly.

Creating tasks in visual studio

Creating an application

  • Lets Create a captians log application which will be a simple logging application.
    • Users can type log entries which are timestamped and stored in an isolated storage.
    • The tracking feature will be added using background agent.
    • The start tracking button click will fire up the background agent will be track the location of the captain and add it to the log. So the agent will update the position even when the program is not active.

  • Create a Windows Phone application solution and develop the foreground tasks and applications.
  • Add a new project to the application solution which is Windows Phone Scheduled task (VS Template). This will contain code will run when the agent is active.

  • Here is the solution file for the captians log which has got two projects:
    • Captians Log – The Windows Phone Silverlight Project which is the main application.
    • LocationTaskAgent – The background agent to perform the tracking.
  • Solutions may contain differnt projects and when the soltion is build all the assembly file outputs will be combined and sent to the phone.

  • Before this works we need to refernce the LocationTaskAgent Project in Captains Log

  • And when we do this the application manifest file adds a little bit of text to hold the description of the background agent and this is how the background agent is bound to the application. Here is the text added to the application manifest file.

  • So below is the code that will run when the agent wakes up so we need fill this OnInvoke method with our code that the agent will run. At the end to this code we need to call the method notify complete whcih will will notify the runtime system that it is done.

  • The Captains log datafile is shared between the application and agent and the first thing that the agent will do is load this datafile from the isolated storage.

  • Now we make use of GPS traking to find out the current loaction. So we make GeoCoordinateWatcher and start it and use it to get the location. Now before you start thinking about the performance hit this does i would like to tell you that there is a special version of this class provided for Background Agents which uses cached location data which is stored every 15 minutes.

  • And then agent just stores back this location to the application and goes to sleep.

  • Finally a notification is displayed to the user on which the user can click and go to the main application.

File transfer tasks

  • It is possible to create a background task to transfer files to and from application’s isolated storage.
  • The transfer will take place when the application is not running.
  • An application monitor the state of downloads and display their status
  • Files can be transferred from http or https hosts (ftp is not suppoerted currently)
  • The system maintains a queue of active transfers and services each one in turn.
  • Applications can query the state of active transfers.

Background Transfer Policies

  • Policies are :
    • Maximum upload file size is 5Mb
    • Maximum download file size over cellular (mobile phone) data : 20Mb
    • Maximum dowload file size over WiFi : 100Mb
  • These can be modified by settng the value of TransferPreferences on a particular File Transfer.

Background Transfer Namespace

  • The background transfer namespace is :

  • All the background transfer services are provided from the BackgroundTransfer namspace
  • Most instertingly you dont need to create additional projects to manage background transfers.

Create a Background Transfer

  • The following code creates a request and sets the source for transfer and it also sets the transfer method.

  • The following code sets the destination of the files transfer which is isolated storage of the application. Also it sets the preferences for the transfer. Now the transfer preferences can have multiple string so that you can set multiple properties.

  • The following code starts the transfer request by adding it to the list of active transfers. Also catches the exception if any and shows a message if it cannot proceed with the transfer.

  • The following code monitors the transfer by binding the methods to the events fired by the transfer request.

 

  • You can also kill the transfer by using the following code:

  • Windows phone appplication at any point of time can find out how many active transfers does have and as a rule of thumb you should always check the same whenever your application restarts because your transfers are still running when your application is not active. Below is the code that lets you do the same.

Scheduled Notifications

  • Windows phone app can create scheduled notifications and they are displayed when the application is running or not.
  • When the notification is diplayed the phone user has the option to respond to it or not. Also the notification can be liked to an application page.
  • The notifications can fire once or repeatedly at configurable intervals.
  • The notifications is maintained by phone operating system, once the application can started then it doen not have to do anything.

Sample Application

  • Lets make a simple timer application which will have two silverlight pages.
  • The user will set the time using the slider then preses the start timer button to create a notification.
  • When the notification will fire the 2nd page of the application which is egg ready page will be displayed and if the user clicks on the same then user will be taken to the application.
  • The sceen of the application will look something like this:

  • The code for the creating the reminder is as below. This code will create the reminder and then adds it as a sceduled service. The value eggTime holds the lenght of the delay and this code also sets the url of the page in application.

  • And before you add the reminder you need to check if its already present in the memory and if the that is the case it is removed from the memory. The code for doing that is as below:

Audio Playback Agents

  • It is possible to create a playback that will manage an application playlist and the mechanism is the same as for other background tasks.
  • The audio can be streamed or stored in application’s isolated storage.

  • This would also work pretty much like the things shown above in the post so i am not elaborating it.

 

You are free to ask any questions or leave your comments here…

 

Hey guys,

Here is some exiting news. Microsoft is giving credits to search on there search engine “Bing”.

Just follow the link below and join the bing rewards program and you will earn 1 credit for every 2 searches you do on bing.

http://go.microsoft.com/?linkid=9778718&rrid=565DA31D-6BE9-4965-861E-BA11A14CDCE1

You can see more information on Microsoft website itself.

Bing Rewards

Bing Rewards

Any questions or feedback will be really appritiated.

Thanks

Abhishek

www.abhishekshukla.com

Do not have a DVD drive in your laptop or netbook, facing problems with DVDs getting scratched.Here is a permanent solution to have a reliable Installation source as USB or Pen drive.Also the installation would be 3X faster. The USB drive should be atleast 4 GB in Size.

  1. We will use the DiskPart utility inbuilt in Windows operating system to prepare the usb drive as a installation source.
  2. Open the Windows command prompt by typing cmd in Run box.
  3.  Type diskpart in the command prompt .
  4. Type list disk command to check the status of your drive
  5. Type select disk 1 where the “1” is actually the corresponding number of your USB drive.(It may different on your system, check the size of the disk to confirm it is the USB drive.)
  6. Type clean.
  7. After the USB drive is clean, type create partition primary.
  8. Now make the partition active by typing command active
  9. Then you need to set up the file system as Fat32 by running format fs=fat32 quick
  10.  Type assign to give the USB drive a drive letter .
  11. Then copy all the files from the Windows 7 or Windows 8 installation DVD onto the USB drive. If you have Windows 7 or Windows 8 ISO You can actually copy all the contents after extracting the ISO.For extracting you can use Power ISO or other similiar utilities.
  12. Now you can install the Windows 7 using the USB drive(might need to change boot options to boot from USB in your system BIOS settings) .

The installation will be atleast 3X faster than DVD.

Tired of your Outlook’s slow performance, unwanted reminders popping up, or feeling that your calendar is messed up?  Here are few tips and tricks that would help your cause. This article is intended for Windows 7 and Outlook 2010, however some of these commands might work on XP and Vista and other Outlook versions.

Exit your Outlook and communicator before running the command line switches, also try to check in task manager that there isn’t any outlook.exe or communicator.exe running.

** Some of the commands may completely wipe off or delete your outlook settings so try at your own risk and with proper back up.

You can use either one of the 3 options for command line switches:

1) Open the Run command via Start-> Run

2) Press the Windows Logo + R on your keyboard

3) Open the Start Menu and use the Search field to type in for the next step.(see the pic)

 

 

 

 

 

1. Too many reminders keep popping on your on screen, try this command line to clear all the reminders and regenerate them.

outlook /cleanreminders 

2. Messed up with the Views, or new mails aren’t showing up in bold or facing similiar issues try the next command line switch.

outlook /cleanviews

3. Want to clean up all the rules and start off with new ones then try this

outlook /cleanrules

4. Want to start Outlook with reading pane off then use this switch

outlook /nopreview

5. Want to reset folder names to outlook default . It will only reset names of default Outlook folders not the folders created by you.

outlook /resetfoldernames

6. Reset ToDO bar task list

outlook /resettodobar

7. In order to load Outlook for a specific profile try using this, here profilename is name of your profile

outlook /profile “profilename”

8. Clear all the free busy information that might be slowing up Outlook

outlook /cleanfreebusy

9. Clear all the duplicate reminder messages

outlook /cleansniff

10. Want to run outlook as like the first time run

outlook /firstrun

11. Restore missing folders for default delivery location

outlook /resetfolders

12. Starts Outlook without extensions, Reading Pane, or toolbar customization.

outlook /safe

 

Happy trobleshooting

 

What is a resource (in terms on .net)?

A resource is a noncode piece of an application or compnent like bitmaps, fonts, audio / video files, string tables.

WPF supports 2 different types of resources –

Binary Resource

Binary resources are what the rest of the .NET framework conciders as resources and in WPF apps they are traditional items like bitmaps. You might also be surprised to know that XAML is also stored as a binary resource behiend the scenes. Binary resources are packaged in three different ways:

  • Embedded inside an assembly
  • Loose files that are known to the application at complie time
  • Loose files that are not known to the applcation to the compile time.

Now we can also categorize binary resources into Localizable (change depending on the current culture) and Non Localizable (do not change based on culture).

Lets see how can we define access and localize birary resources.

Defining a Binary Resource

As shown in the image below, you select the Build Action property and set it to either Resource or Content.

Define Resource Prop in VS

Define Resource Prop in VS

Select Build Action as Resource when you want to include your resource in the assembly and Select Build Action as Content when you want your resourcfe to be a loose file and only the existence and relative location of the file sould be included in the assembly.

Now if you would have noticed the above image carefully (you can have a look again if you want) then you will see there is another value by the name of Embedded Resource (this also embeds the resource into the assembly just like Resource). The use of this value is not recomended in WPF as this property belongs to old .net and was ment to be used with Windows Forms. Also if you select your resource to an Embedded Resource then you will not be able to access it in XAML (unless you write some custom code for the same).

[highlight]Note – As a rule of thumb you should embed the resource (with the Resource build action) only when the resouce is localizable or you specificly need single binary or resource within binary else you should prefer Content build action.[/highlight]

Accessing a Binary Resource

In WPF you can access a binary resource from code ox XAML through a URI (uniform resource identifier). And a types converter will help us to specify URIs in XAML as simple strings. The code below demonstrates how simple we can access resources whose build action property has been set to either Resource or Content but they have been included in the project

<Image Height=21Source=slideshow.gif/>

Note – A compiled XAML cannot reference a binary resource in the current  directory via its simple filename unless it has been added to the project. For  accessing files that are not added into the project either give the full path of the resource or access resource using Site of Origin url.

<Image Height=21Source=C:\\Users\\Adam\\Documents\\slideshow.gif/>

<Image Height=21Source=pack://siteOfOrigin:,,,/slideshow.gif/>

Below here is the list present for refernce of how to acces which binary resource.

Resource Type URI Mapping

Resource Type URI Mapping

 

Accessing Resources from Procedural Code

If you want to access resources from your C# or vb.net code the XAML specific shortcuts will not work but the URIO should be fully qualified. Below is an example for the same:

Image image = new Image();

image.Source = new BitmapImage(new Uri(“pack://application:,,,/logo.jpg”));

So the above lines of code will instantiate a System.Windows.Media.Imaging.BitmapImage object which ultimately derives from the abstract ImageSource type and this will work with popular image formats such as JPEG, PNG, GIF, BMP. The use of pack://application:,,,/ works only with resources belonging to the current project marked as Resource or Content. To reference relative loose files with no relation to the project, the easiest approach is to use a siteOfOrigin-based URI.

Localizing a Binary Resource

If your application contains some binary resources that are specific to certain cultures then we can partition them into satellite assemblies (one for each culture) and get them loaded automatically when appropriate. And if you are having binary resources for localization then there is a very good chance that you have string in your UI for localization. Here we could make use of LocBaml (sample tool in windows SDK) which will make it very easy to manage localization of strings and other items without removing them from XAML and manually apply a level of indirection. Lets have a look as to how can we use LocBaml and Satellite Assemblies. Remember this is just an overview on how you can proceed with it. To specify a default culture for resources and automatically build an appropriate satellite assembly, you must add a UICulture element to the project file. Visual Studio doesn’t have a means to set this within its environment, so you can open the project file in your favorite text editor instead. The UICulture element should be added under any or all  PropertyGroup elements corresponding to the build configurations you want to affect (Debug, Release, and so on), or to a property group unrelated to build configuration so it automatically applies to all of them. This setting should look as follows for a default culture of American English:

<Project …>

<PropertyGroup>

<UICulture>en-US</UICulture>

……

 

If you rebuild your project with this setting in place, you’ll find an en-US folder alongside your assembly, containing the satellite assembly named  assemblyName.resources.dll. You should also mark your assembly with the assembly-level NeutralResourcesLanguage custom attribute with a value matching your default UICulture setting, as follows:

[assembly: NeutralResourcesLanguage(“en-US”, UltimateResourceFallbackLocation.Satellite)]

The next step is to apply a Uid directive from the XAML language namespace (x:Uid) to every object element that needs to be localized. The value of each directive should be a unique identifier. This would be extremely tedious to do by hand, but it fortunately can be done automatically by invoking MSBuild from a command prompt, as follows:

msbuild/t:updateuid ProjectName.csproj

Running this gives every object element in every XAML file in the project an x:Uid directive with a unique value. You can add this MSBuild task inside your project before the Build task, although this might produce too much noise if you rebuild often.

After compiling a project that has been enhanced with Uids, you can run the LocBaml tool from the Windows SDK on a .resources file generated by the build process (found in the obj\debug directory), as follows:

LocBaml /parseProjectName.g.en-US.resources /out:en-US.csv

This generates a simple .csv text file containing all the property values you should need to localize. You can edit the contents of this file so it correctly corresponds to a new culture. (There’s no magic in this part of localization!) If you save the file, you can then use LocBaml in the reverse direction to generate a new satellite assembly from the .csv file!

For example, if you changed the contents of the .csv file to match the French Canadian culture, you could save the file as fr-CA.csv and then run LocBaml as follows:

LocBaml /generate ProjectName.resources.dll /trans:fr-CA.csv /cul:fr-CA

This new satellite assembly needs to be copied to a folder alongside the main assembly with a name that matches the culture (fr-CA in this case).

To test a different culture, you can set System.Threading.Thread.CurrentThread.CurrentUICulture (and System.Threading.Thread.CurrentThread.CurrentCulture) to an instance of the desired CultureInfo.

Logical Resource

As you might have gussed logical resources are the ones which are arbitary .NET objects stored in an element’s resources property (meant to be shared by multiple child elements). The base clases of both FrameworkElement and FrameworkContentElement have a Resource Property. The examples of logical resources are
styles,data provides, etc.

Lets see an XAML code for a logical resource which is Brush. The following example shows a simple windows with a row of buttons along the bottom which can be used in a photo gallery user interface. This example shows how to apply custom brush to each Button’s Background and BorderBrush.

<Window xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation Title =”Simple Window” Background=”Yellow”>

    <DockPanel>

        <StackPanel DockPanel.Dock=”Bottom” Orientation=”Horizontal” HorizontalAlignment=”Center”>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”zoom.gif”/>

            </Button>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”defaultThumbnailSize.gif”/>

            </Button>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”previous.gif”/>

            </Button>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”slideshow.gif”/>

            </Button>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”next.gif”/>

            </Button>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”counterclockwise.gif”/>

            </Button>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”clockwise.gif”/>

            </Button>

            <Button Background=”Yellow” BorderBrush=”Red” Margin=”5″>

                <Image Height=”21″ Source=”delete.gif”/>

            </Button>

        </StackPanel>

        <ListBox/>

    </DockPanel>

</Window>

Applying Custom Color Brushes Without Using Logical Resources

Applying Custom Color Brushes Without Using Logical Resources

Now lets implement Logical Resources

<Window xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=”http://schemas.microsoft.com/winfx/2006/xamlTitle=”Simple Window”>

<Window.Resources>

<LinearGradientBrush x:Key=”backgroundBrush” StartPoint=”0,0″ EndPoint=”1,1″>

<GradientStop Color=”Blue” Offset=”0″/>

<GradientStop Color=”White” Offset=”0.5″/>

<GradientStop Color=”Red” Offset=”1″/>

</LinearGradientBrush>

<SolidColorBrush x:Key=”borderBrush”>Red</SolidColorBrush>

</Window.Resources>

<Window.Background>

<StaticResource ResourceKey=”backgroundBrush”/>

</Window.Background>

<DockPanel>

<StackPanel DockPanel.Dock=”Bottom” Orientation=”Horizontal” HorizontalAlignment =”Center”>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush=”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”zoom.gif”/>

</Button>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush=”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”defaultThumbnailSize.gif”/>

</Button>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush=”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”previous.gif”/>

</Button>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush=”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”slideshow.gif”/>

</Button>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush=”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”next.gif”/>

</Button>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush=”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”counterclockwise.gif”/>

</Button>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush =”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”clockwise.gif”/>

</Button>

<Button Background=”{StaticResource backgroundBrush}” BorderBrush =”{StaticResource borderBrush}” Margin=”5″>

<Image Height=”21″ Source=”delete.gif”/>

</Button>

</StackPanel>

<ListBox/>

</DockPanel>

</Window>

 

Consolidating Color Brushes with Logical Resources

Consolidating Color Brushes with Logical Resources