Jan 16 2012

SwimEventTimes W7P Development -- Live Tile

Category: � Administrator @ 12:18

If you have an app then you owe it to yourself and users of your app to get something relevant onto the "pinned" Application Tile.  For a user who has "pinned" your application they will quickly expect something to appear on the back portion of the application tile.  This is what people consider the "cool" factor of owning a Windows Phone.  Having my phone open in the elevator with lots of flipping tiles makes the Windows 7 Phone look impressive to those other phone owners.  If your application tile does not flip and reveal any tidbits of information then your app is doomed to live unpinned and probably unused.

What I decided to do for my app was to have the user of the app select which swimmer(s) stat would appear on the Live Tile.  Then when the agent code (usually every 30 minutes) runs it will select a ("Best") random stat from the selected swimmer(s).  This way every 30 minutes I get a new stat for a swimmer on the back of the Live Tile.  You only have about 45 characters to play with so be selective about what you will show on the back of the Live Tile.

 

Now for the code:

From your main page include the start of the agent in the constructor:

// Constructor
        public RequestedSwimmersPage()
        {
            InitializeComponent();
           
            AgentMgr.StartAgent();      
            
        }

I've added a separate class to handle the use of the agent.  Keeps the code cleaner for future changes:

public static class AgentMgr
    {
        private const String AgentName = "SwimmerAgent";
        private const String AgentDescription = "Custom background agent for Swim Event Times pinned Tile!";


        public static void StartAgent()
        {
            StopAgentIfStarted();

            PeriodicTask task = new PeriodicTask(AgentName);
            task.Description = AgentDescription;
            ScheduledActionService.Add(task);
#if DEBUG 
        // If we're debugging, attempt to start the task immediately
            ScheduledActionService.LaunchForTest(AgentName, new TimeSpan(0, 0, 1)); 
#endif
        }


        public  static void StopAgentIfStarted()
        {
            if (ScheduledActionService.Find(AgentName) != null)
            {
                ScheduledActionService.Remove(AgentName);
            }
        } 
         
    }
}

 

So to get things moving you'll need a separate project (for the Agent worker) added to your solution to have the agent run.  Select the "Scheduled Task Agent" project type when adding the project to your solution.  Once you have a separate (Agent) project then add a reference to that from your main application.

It runs on a 30 minute interval so the data that I'm pulling will change on the back of the pinned Application Tile on that interval.

Now the Agent project will have one class and one method (OnInvoke) that you need to be concerned with.  Place your code to get new information onto the back tile in this method:

/// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
        
            //Here is where you put the meat of the work to be done by the agent

            //get the data from ISO 
            ObservableCollection<Swimmer> Swimmers = BackgroundAgentRESTCall.GetSwimmers();
            ObservableCollection<RequestedSwimmer> RequestedSwimmers = BackgroundAgentRESTCall.GetRequestedSwimmers();

            //pull out those swimmers who have the Live Tile turned on
            //and only those that match the 'Course' selection
            IEnumerable<Swimmer> tileSwimmers = from swimmer in Swimmers
                                            join reqswimmer in RequestedSwimmers on swimmer.SwimmerID equals reqswimmer.SwimmerID
                                            where reqswimmer.UseOnLiveTile == true
                                            && reqswimmer.BestCourseSelection == swimmer.Course
                                            select swimmer;


            string tileText = String.Empty;
            string titleText = string.Empty;
            
            //make sure that we have at least one stroke for a swimmer.
            if (tileSwimmers.Count() != 0)
            {

                //pull out the best swims for all marked (Live Tile) swimmers
                var bestswims = from p in tileSwimmers
                                //where conditions or joins with other tables to be included here                           
                                group p by p.SwimmerID + p.Stroke + p.Course + p.Distance into grp
                                let MinTime = grp.Min(g => g.TimeSecs)
                                from p in grp
                                where p.TimeSecs == MinTime
                                orderby p.Course descending, p.StrokeOrder, p.Distance
                                select p;

                int count = bestswims.Count(); // 1st round-trip 
                int index = new Random().Next(count);

                var tileSwimmer = bestswims.Skip(index).FirstOrDefault(); // 2nd round-trip 
              

                //foreach (Swimmer tileSwimmer in tileSwim)
                //{
                //Debug.WriteLine("WWW-data.LastProcessToTouchFile=" + tileSwimmer.AltAdjTime);
                titleText = tileSwimmer.Distance + tileSwimmer.Stroke + ": " + tileSwimmer.Time;

                Guid NavGUID;
                NavGUID = (Guid)tileSwimmer.SwimmerID;

                var tileReqSwimmer = (from reqswimmer in RequestedSwimmers
                                      where reqswimmer.SwimmerID == NavGUID
                                      select reqswimmer).FirstOrDefault();

                int LastnamLen = tileReqSwimmer.LastName.Length;
                if (LastnamLen > 9)
                {
                    LastnamLen = 9;
                }


                int StandardLen = tileSwimmer.Standard.Length;
                if (StandardLen > 6)
                {
                    StandardLen = 6;
                }

                tileText = tileReqSwimmer.FirstName.Substring(0, 1) + tileReqSwimmer.LastName.Substring(0, LastnamLen)
                + " Age: " + tileSwimmer.Age + "   "
                + String.Format("{0:MMM yyyy}", tileSwimmer.MeetDate) + "  "
                + tileSwimmer.Course + "  " + tileSwimmer.Standard.Substring(0, StandardLen);
            }
            else
            {
                tileText = "Select a Swimmer to be shown.";
                titleText = "Event & Time";
            }

            UpdateAppTile(tileText, titleText);

           
        }

The above routine gets the data from Isolated Storage. 

Note: I used a mutex in the call for the ISO data since we could be writing to the same storage at the time we are trying to read from it.

  I made heavy use of the sample mutex code listed from the link below:
 http://www.31a2ba2a-b718-11dc-8314-0800200c9a66.com/2011/11/this-is-continuation-of-this-post.html

Then I used LINQ to pull out the data needed, format it and call the Update method for the Tile:

private void UpdateAppTile(string message, string backTitleText)
        {
            ShellTile appTile = ShellTile.ActiveTiles.First();
            if (appTile != null)
            {
                StandardTileData tileData = new StandardTileData
                {
                    BackContent = message
                    ,BackBackgroundImage = new Uri("/Images/LiveTileC173x173.png", UriKind.Relative)
                    ,BackTitle = backTitleText
                };

                appTile.Update(tileData);
            }
        }

That gives us a pinned Application Tile with swimmer(s) changing info. 

Swimmers like it since it randomly rotates through their "Best" swim times and it gives the app that cool flipping tile that other phone owners love to hate.

 

 

 

 

Tags: , , , , ,

Oct 2 2011

SwimEventTimes W7P Development -- HTML Agility Pack

Category: � Administrator @ 08:13

When this app started out, a long time ago, I happened upon the HTML Agility Pack or HAP.  This tool was originally written for .Net and used XPath to search and define the elements that you needed from the original source HTML.  So when it comes time to SCRAPE data from a page, you'll need a tool that provides a robust and almost carefree nature about the HTML structure.  It does so much for you that without it I would have never attempted what I was thinking:

http://htmlagilitypack.codeplex.com/

Kudos to the authors, especially DarthObiwan, of this fantastic piece of work.

Basically it allows you to define what tags you want from a page and search and pull out that piece of the text.  But the twist here is that for HAP to work on the phone it had to work without Xpath since Xpath was not supported in the OS 7.0 release on the phone.

So what took the place of the Xpath is LINQ.  This added yet another dimension to my learning since I had never really used LINQ and had only recently started looking into using LINQ when I thought about converting a project from XSLT.  It takes time to make the mental switch from Xpath to LINQ but there was no other way.  Also, at that time, none of the code releases for HAP worked on the phone but by getting the source and following the comments of the authors on how to re-engineer the code I was able to get it compile and now it works like a charm.

So now let's talk about how we use HAP:

Here we have entire HTML loaded up in htmDoc.

//let's detemine what came back on the response

HtmlAgilityPack.HtmlDocument htmDoc = new HtmlAgilityPack.HtmlDocument();
htmDoc.LoadHtml(responseData);

Next you can start to look for specific items:

string pattern = @".*txtSearchLastName$"; 
var SearchPagenode = htmDoc.DocumentNode
                      .Descendants("input")
                      .FirstOrDefault(x => Regex.IsMatch(x.Id, pattern));


So now I can look at the element and get the id:

CTLID = SearchPagenode.Id;

Other things like pulling out <a> tags out of table contained in the last <tr>:

pattern = @".*dgPersonSearchResults$"; 
var links = htmDoc.DocumentNode.Descendants("table")
           .First(n => Regex.IsMatch(n.Id, pattern))
          .Elements("tr").Last() .Descendants("a")
          .Select(x => x.GetAttributeValue("href", "")).ToArray();


You can go crazy with HAP and as your LINQ gets better you can go further and refine these queries.

HAP provides the foundation and performs the grunt work required to interrogate/parse a HTML source.


Tags: , , , ,

Sep 2 2011

W7P SwimEventTimes development - Fiddler2

Category: Features � Administrator @ 11:19

Back to the beginning.  When you need content and the content exists on other web sites you'll have to devise a way to acquire the data.  And I'm not talking about OData or some other nice structure of data lying around on the internet.  What I'm talking about is, for a lack of better term, "SCRAPING" data from other URL's.  Some would call this Web Scraping but this technique really applies to a whole realm of techniques and not just in use on the web.

Some believe that type of development is fraught with problems since your tying your app to a URL and that web design.  Just know these pitfalls up front and try to mitigate as many problems as possible.

Try and contact the URL's owners and try to get them to come onboard with your development.  That way at least you'll have knowledge of upcoming changes which could cause side-effects on your W7P app.

Disclaimer:  I'm a developer and not a copyright lawyer but be warned that some sites believe that they own the data and have the sole rights to that data.  It's the old "Creative" vs "Collection" argument. Collection of data is not creative but do your own copyright research.

Now let's talk about overall design.  Some designs call for an intermediate server to make the calls to the target URL but I opted to make the Windows 7 Phone software smart enough to exist on its own and pull the data directly from the target.  This minimizes the points of failure. It's either working from the W7P or not plus it also permits the phone to operate anonymously from the target URL's perspective.

Now the main tool that I quickly made use of is Fiddler2.  Fiddler2 allows you to look at the payload when making calls across the web.  This includes everything that is sent from your Request and the subsequent Response.

The site from which the data for this app will be scraped is an ASP.NET site.  I can't be sure but the site appears to make use of a Content Management System. I could have gone further into looking at the CMS since I believe that it's Open Source and pulling apart the code but I decided to spend the time on how and if I could get access to the data across the web from the phone. 

Other sites and their software platforms and how they implement cookies/session data etc. will change the makeup of how you access the pages but you need to start with Fiddler2.

I know IE9/Firefox have similar developer tools but when this application started up, Fiddler2 was my choice.

Get to know Fiddler2 and exactly what pages you need to hit.  Make screen shots of the flow that you'll need to capture and test scenarios that will cover the flow of pages.

You and Fiddler2 will spend many long nights together.

Tags: , ,

Aug 6 2011

W7P SwimEventTimes development - Touch and Hold Gesture vs Discovery

Category: Features � Administrator @ 11:20

I had implemented a "Touch and Hold" gesture for editing and deleting items from the Swimmer's page. 

The "Touch and Hold" would bring up a Context menu for editing and deleting a selected swimmer.

After receiving complaints from beta users that this was not discoverable I thought I needed to provide a better experience for the user. 

What I ended up using was a List box with check boxes and additional icons in the application bar to control the experience.  So before, I had a context menu with "Edit" and "Delete" which was revised into two additional icons on the application bar.

I made great use of the following example:

http://listboxwthcheckboxes.codeplex.com/

Now it's quite apparent on how to delete swimmers and edit the swimmer's date range when you need to refresh and download with the latest meet data.

 

 

 

Tags: , , , ,

Jul 5 2011

W7P SwimEventTimes development -- Tilt Effect

Category: Features � Administrator @ 05:38

As many developers, I've completed most of the development using the phone emulator since I wanted to wait until Verizon was offering a Windows 7 Phone.  While the emulator provides an invaluable tool, you soon realize you missed something when you start developing and testing with a real device.

For this development I immediately noticed that the "Tap" gesture was not fluid enough to give the user a feeling that they had just touched an element on the screen. 

So here I employed the the "Tilt Effect" as so nicely provided by:

http://www.scottlogic.co.uk/blog/colin/2011/05/metro-in-motion-part-4-tilt-effect/

I went with the following value since I think it gave me a better pushed-in effect:

<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" local:MetroInMotion.Tilt="5">

Now touching an element gives a nice feedback to the user so that they can feel as if the element on screen was pushed in.  I've used this in all the places where the action of touching the element would bring you another page.  Specifically I added it to the Swimmer's Page (Add, Edit, Delete) and the Panorama page displaying the "Best", "Meets" and "Strokes" data.

 

Tags: , , ,