Search Share Home Devices Settings


[#12] WP7Tips: Creare un handler generico da usare con le Live Tile “schedulate”

(c) lorenzo barbieri - 04/01/2011

Oltre Push Notification, è possibile anche schedulare l’aggiornamento delle Live Tile di Windows Phone 7 ogni ora, giorno, etc...

Nel secondo caso è possibile passare solo l’url dell’immagine da caricare, senza poter cambiare titolo, etc…

Per generare l’immagine nel formato giusto, può venir comodo questo handler ASHX, da copiare in un qualsiasi sito o applicazione ASP.NET, senza necessità di configurazione alcuna.

Usarlo è molto semplice, basta impostarlo come Uri della Tile schedulata, passando eventualmente sulla query string i parametri:

  • url – opzionale, contiene l’url dell’immagine da mostrare sulla tile, scalata a 173x173 in automatico
  • text – opzionale, contiene il testo da scrivere in basso sulla tile, al posto di quello di default. I caratteri “|” (pipe) vengono sostituiti con degli “\n” (a capo).

In questo esempio il caching dell’ASHX è impostato  10 minuti, ma può essere alzato ad 1 ora o ad 1 giorno, a seconda dell’uso che se ne deve fare.

 

<%@ WebHandler Language="C#" Class="Generic_Tile" %>

using System;
using System.Web;
using System.IO;
using System.Xml.Linq;
using System.Drawing;
using System.Net;
using System.Linq;

public class APOD_Tile : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {      
        //imposto il caching dell'ASHX per 10 minuti
        TimeSpan refresh = new TimeSpan(0, 10, 0);
        HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.Add(refresh));
        HttpContext.Current.Response.Cache.SetMaxAge(refresh);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Server);
        HttpContext.Current.Response.Cache.SetValidUntilExpires(true);

        string url = context.Request.QueryString["url"];
        if (url == null )
            url = "";

        string text = context.Request.QueryString["text"];
        if (text == null)
            text = "";
        text=text.Replace('|', '\n');
       
        //creo la live tile e la superficie grafica
        Image tile = new Bitmap(173, 173);
        Graphics artist = Graphics.FromImage(tile);

        // recupero l'immagine e la disegno
        // altrimenti creo una tile del colore del tema
        if (url != "")
        {
            WebRequest req = WebRequest.Create(new Uri(url));
            WebResponse response = req.GetResponse();
            Stream stream = response.GetResponseStream();
            Image img = Image.FromStream(stream);
            artist.DrawImage(img, 0, 0, 173, 173);
        }
        else
        {
            artist.Clear(Color.Transparent);
        }

        if (text != "")
        {
            // preparo un font "simile" a quello del telefono
            Font drawFont = new Font("Segoe UI", 14);
            SolidBrush drawBrush = new SolidBrush(Color.White);

            // controllo che la scritta stia su una riga, altrimenti riduco il font
            SizeF size = artist.MeasureString(text, drawFont);
            if (size.Width > 170)
            {
                drawFont.Dispose();
                drawFont = new Font("Segoe UI", 12);
            }

            // scrivo il testo in basso centrato, a 6px dal bordo
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Far;
            artist.DrawString(text, drawFont, drawBrush, new RectangleF(0, 0, 173, 173 - 6), sf);
        }
       
        artist.Dispose();

        // preparo lo stream con l'immagine in formato PNG
        MemoryStream imageStream = new MemoryStream();
        tile.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png);
        byte[] imageContent = new Byte[imageStream.Length];
        imageStream.Position = 0;
        imageStream.Read(imageContent, 0, (int)imageStream.Length);

        // invio l'immagine nella response, impostando il content type giusto
        context.Response.ContentType = "image/png";
        context.Response.BinaryWrite(imageContent);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

 

Se si usa il parametro text, bisogna “svuotare” il Title della Tile impostato nel file WMAppManifest.xml (attenzione, se si aprono le proprietà del progetto verrà rimesso il Title di default, ricordatevi di “svuotare” di nuovo il Title).

In questo caso ricordatevi anche di impostare un’icona 173x173 (Background.png se non avete modificato il template) “descrittiva”, con il nome della Tile già scritto in modo da farla sembrare “vera”, in quanto quelle schedulate inizieranno ad arrivare dopo un po’ di tempo (anche in base alla frequenza di aggiornamento).


<Deployment>
<App>
  <Tokens>
      <PrimaryToken>
        <TemplateType5>
          <BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
          <Count>0</Count>
          <Title> </Title>
        </TemplateType5>
      </PrimaryToken>
    </Tokens>
  </App>
</Deployment>

Tags: WP7 WP7Tips

Comments disabled in this version of the blog.