×

Discussion Board

Page 1 of 2 12 LastLast
Results 1 to 15 of 26
  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    14

    Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi everyone,
    I have a very strange problem. I am using a scheduled task to update my live tile, which is rendered using the TCD Controls live tile library through a JSON data retrieved from a REST API.
    The tile is updated normally on WP8 (lumia 620) and WP7.8 when connected to the debugger (Lumia 800).

    When WP7.8 is not connected to the debugger, the REST API is called, data retrieved but the tile won't be rendered... By debugging the app through toasts, I noticed the fault is inside the RenderTileTemplate method, which works good without the REST call, though (e.g.: getting the data locally, not through REST call).
    Can anyone help me? Here is the code:

    Code:
                Uri back = null;
                String txt = null;
                int fontSize = 0;
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    return;
                }
                var client = new RestClient("REST API URL");
                RestRequest reqCredit = new RestRequest();
                reqCredit.Resource = "allInfo";
                reqCredit.RootElement = "Values";
                reqCredit.AddParameter("uid", uid);
                reqCredit.AddParameter("pwd", pwd);
                reqCredit.RequestFormat = DataFormat.Json;
                reqCredit.Method = Method.GET;
    
                client.ExecuteAsync<AllInfoJSON>(reqCredit, (response)
                    =>
                {
                    if (response != null && response.StatusCode == HttpStatusCode.OK && !response.Data.status.Equals("error", StringComparison.OrdinalIgnoreCase))
                    {                    
                        txt = response.Data.creditValues[0].value;
                        
                        fontSize = 0;
                        
                        Deployment.Current.Dispatcher.BeginInvoke(new Action(delegate//rendering done on the UI thread!!!!!
                        {
                            //MediumTileTemplate is custom but works... changing it to default one doesn't help....
                            back = TileRenderer.RenderTileTemplate(new MediumTileTemplate(txt, fontSize), "creditoTreTile", TileSize.Medium_336x336);//render the tile
                        }));
                    }
                });            
                
                while (back == null)
                {
                    System.Threading.Thread.Sleep(1000);
                }
                // Code is never reached unless debugging on WP7.8 or WP8
                String backTitle = "Il " + DateTime.Now.Date.Day + "/" + DateTime.Now.Date.Month + "@" + DateTime.Now.ToString("HH:mm");
                if (TileSetter.IsNewTilesSupported) {
                    if (DBManagement.isInfoFrontOn())
                    {
                        TileSetter.SetPrimaryTileFlipTemplate(backTitle, "Credito Tre", "", "", 0, null, back, new Uri("Background.png", UriKind.Relative), null, null);
                    } else {
                        TileSetter.SetPrimaryTileFlipTemplate("Credito Tre", backTitle, "", "", 0, null, new Uri("Background.png", UriKind.Relative), back, null, null);
                    }
                } else {
                    if (DBManagement.isInfoFrontOn())
                    {
                        TileSetter.SetPrimaryTile(backTitle, "Credito Tre", "", 0, back, new Uri("Background.png", UriKind.Relative));
                    } else {
                        TileSetter.SetPrimaryTile("Credito Tre", backTitle, "", 0, new Uri("Background.png", UriKind.Relative), back);
                    }
                }
                
                NotifyComplete();
    And the RenderTileTemplate code, is public on NuGet, and reported here. The error is at the Render call or, time to time, at the Encode call:
    Code:
    public static Uri RenderTileTemplate(Control template, string filename, TileSize tileSize = TileSize.Medium_336x336)
            {
                string dims = tileSize.ToString();
                dims = dims.Substring(dims.LastIndexOf('_') + 1);
                int[] size = new int[] { Convert.ToInt32(dims.Substring(0, 3)), Convert.ToInt32(dims.Substring(4, 3)) };
                template.Measure(new Size(size[0], size[1]));
                template.Arrange(new Rect(0, 0, size[0], size[1]));
                WriteableBitmap wb = new WriteableBitmap(size[0], size[1]);
                wb.Render(template, null);
                wb.Invalidate();
                var encoder = new PngEncoder();
                using (var str = new IsolatedStorageFileStream(string.Format(pattern, filename), FileMode.Create, isoStore))
                {
                    encoder.Encode(wb.ToImage(), str);
                }
                return //The URI PATH;
            }
    Thanks a lot!

  2. #2
    Nokia Developer Champion
    Join Date
    Nov 2011
    Location
    la bouexiere, france
    Posts
    474

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi.
    I thinks this code is not executed

    Code:
     Deployment.Current.Dispatcher.BeginInvoke(new Action(delegate//rendering done on the UI thread!!!!!
    {
                            //MediumTileTemplate is custom but works... changing it to default one doesn't help....
                            back = TileRenderer.RenderTileTemplate(new MediumTileTemplate(txt, fontSize), "creditoTreTile", TileSize.Medium_336x336);//render the tile
    }));
    because you block principal thread with
    Code:
     while (back == null)
    {
        System.Threading.Thread.Sleep(1000);
     }

  3. #3
    Registered User
    Join Date
    Mar 2013
    Posts
    14

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi yan_,
    thanks for the reply. Actually the code is executed, even if the phone is not connected to the debugger. I am sure about that, because I added some toast notifications inside the RenderTileTemplate method....
    Moreover, i also tried both resorting to ManualResetEvent to wait for the rendering on the UI to complete, without success.

    Could you suggest some piece of code, with the same functionalities, that should work according to your understanding?

    Thanks!

  4. #4
    Nokia Developer Champion
    Join Date
    Nov 2011
    Location
    la bouexiere, france
    Posts
    474

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi.
    Normally, you can remove this test:
    Code:
     while (back == null)
    {
        System.Threading.Thread.Sleep(1000);
     }
    and move all code after in your Deployment.Current.Dispatcher.BeginInvoke call.

  5. #5
    Registered User
    Join Date
    Mar 2013
    Posts
    14

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Wouldn't that move all of the following code inside the UI Thread?
    Anyway, I just tested that, and no success: the Rendering code is executed but doesn't complete...

    Thanks anyway!

  6. #6
    Nokia Developer Champion
    Join Date
    Nov 2011
    Location
    la bouexiere, france
    Posts
    474

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi.
    I write wrong explanation when i say " this code block your thread"
    Code:
     while (back == null)
    {
        System.Threading.Thread.Sleep(1000);
     }
    ShedulerAgent and Deployment.Current.Dispatcher.BeginInvoke are not executed in same thread. Sorry.

    But make a loop to synchronize thread is not really good. It's better to
    1- use synchronization tools like http://msdn.microsoft.com/en-us/libr...v=vs.105).aspx
    2- in your case, move code in Deployment.Current.Dispatcher.BeginInvoke (yes it will be executed in principal Thread)
    3- use await/Async with WP8 : http://www.developer.nokia.com/Commu...indows_Phone_8

    Maybe this explain your problem :
    What happen if response == null || response.StatusCode != HttpStatusCode.OK || response.Data.status.Equals("error", StringComparison.OrdinalIgnoreCase) ?
    In you code, back is always null => your wait loop will never out.

  7. #7
    Registered User
    Join Date
    Mar 2013
    Posts
    14

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi yan_,
    thanks once more for the reply. I actually moved from the loop to the ManualResetEvent event (works like a semaphore), and tried calling the method as async, too. No success. I start thinking the problem is not in my code, but in the WP7.8 tile... I've been suggested elsewhere it may be this: http://www.wpcentral.com/microsoft-b...78-tile-update....

    The problem is that my applciation needs an update, and the new tile is one of its main features... Now, since i don't really wanna break compatibility with older versions (on WP8 it works good), I'll have to wait or release the update just for WP8...

    Thanks for your help!

  8. #8
    Nokia Developer Champion
    Join Date
    Jul 2012
    Posts
    88

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi Iacopo,
    Have you checked your background agent execution time/Memory usage ? There is limits of how a PeriodicTask can run : http://msdn.microsoft.com/en-us/libr...PeriodicAgents
    And Since It works when the debugger is attached I think that may be it
    •For Windows Phone OS 7.1 apps, memory and execution time policies are not enforced while the debugger is attached.
    source : http://msdn.microsoft.com/en-us/libr...v=vs.105).aspx

  9. #9
    Registered User
    Join Date
    Mar 2013
    Posts
    14

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Hi WP!
    Thanks a lot for your suggestion... I also had the feeling it could have been a problem of memory, so i started debugging the app. It turns out, the onInvoke method already starts with little more than 3.65 MB free... Shoudn't the limit be 11Mb? I tried cleaning up all my assemblies and referenced classes, but it just isn't enough: when the execution arrives at the rendering part, it has little more than 50kb left, and it is killed by the system.
    Does anyone know a way to optimize code? I basically need a Get request, deserialization of the JSON data and Bitmap Rendering....

    Thanks a lot for your help!

  10. #10
    Nokia Developer Champion
    Join Date
    Feb 2013
    Location
    Dublin, Ireland
    Posts
    568

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Is it possible to break the work up into pieces to reduce memory usage on each run?

    First run
    - Download data
    - Parse JSON
    - Save to Isolated Storage

    Second run
    - Get data from Isolated Storage
    - Generate Tile update

  11. #11
    Nokia Developer Champion
    Join Date
    Nov 2011
    Location
    la bouexiere, france
    Posts
    474

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    what is PngEncoder library ?
    Have you try to save in jpg?
    size[0] == size[1] == 336 ?

  12. #12
    Registered User
    Join Date
    Mar 2013
    Posts
    14

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Quote Originally Posted by theothernt View Post
    Is it possible to break the work up into pieces to reduce memory usage on each run?

    First run
    - Download data
    - Parse JSON
    - Save to Isolated Storage

    Second run
    - Get data from Isolated Storage
    - Generate Tile update
    I actually thought about this approach, but it would imply basically updating the live tile once an hour instead of half hour... The problem, I've tried, in fact, not making any REST call and just rendering tile, and it works. Also updating tile with native APIs works, even performing REST GET...

    I should try not using the restsharp package, and perform just HTTP calls... But I think, there, deserialization would kill my memory...

    Thanks for the tip!

  13. #13
    Registered User
    Join Date
    Mar 2013
    Posts
    14

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Quote Originally Posted by yan_ View Post
    what is PngEncoder library ?
    Have you try to save in jpg?
    size[0] == size[1] == 336 ?
    It's a nuget package called ImageTools if I am not wrong... Any suggestion for a lighter library?
    And yeah, that's the size of the tile... Moreover I think it doesn't even reach the encoder call... I will check out better today anyway, thanks!

  14. #14
    Nokia Developer Champion
    Join Date
    Nov 2011
    Location
    la bouexiere, france
    Posts
    474

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    I use same library.

    A scheduler agent have a limits in memory, times and cpu usage.

    Instate of native Jpeg encoder, Png encoder is a software encoder. Maybe http get + bitmap creation + png encoder you exceed cpu usage limit.

    In an application, i generate a bitmap tile and save it with ImageTools without problem. But i don't download data.

    Maybe you could use ShedulerAgent to download data and use an intensive agent to generate tiles.

  15. #15
    Nokia Developer Champion
    Join Date
    Sep 2012
    Location
    Morocco
    Posts
    297

    Re: Problem with ScheduledTaskAgent, RestSharp and WriteableBitmap

    Quote Originally Posted by yan_ View Post
    Maybe you could use ShedulerAgent to download data and use an intensive agent to generate tiles.
    I don't think that's a good idea "Resource-intensive agents do not run unless the device is connected to an external power source." so unless this requierement is met, his app won't be able to generate tiles.

Similar Threads

  1. Dynamic Live Tile issue WP8 [WriteableBitmap]
    By Mohab_Tarek in forum Windows Phone General
    Replies: 15
    Last Post: 2013-03-14, 22:17

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×