using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace ReminderService_WebRole
{
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Einträge der nächsten Woche in ListBox ausgeben
        StorageAccountInfo tableInfo = StorageAccountInfo
            .GetDefaultTableStorageAccountFromConfiguration();
        //falls nicht existent: Tabellen erzeugen 
        TableStorage.CreateTablesFromModel(typeof(TerminContext), 
            tableInfo);
        TerminContext context = new TerminContext(tableInfo);
        DateTime today = DateTime.Today.ToUniversalTime();
        DateTime nextWeek = today.AddDays(7);

        //Termine aus TableStorage abfragen
        var results = from g in context.Termin
                      where g.Date > today && g.Date < nextWeek
                      select g;
        ListBox1.Items.Clear();
        foreach (Termin termin in results)
            ListBox1.Items.Add(termin.Date
                + " " + termin.Beschreibung + " "
                + termin.Ort);
    }
    protected void bt_speichern_Click(object sender, EventArgs e)
    {
        //Neues Terminobjekt mit Eingabedaten füllen
        Termin neuerTermin = new Termin()
        {
            Ort = tb_ort.Text,
            Date = Calendar1.SelectedDate,
            Beschreibung = tb_beschreibung.Text
        };
        neuerTermin.setKeys();

        //Termin serialisiert in Queue speichern
        StorageAccountInfo info = StorageAccountInfo
            .GetDefaultQueueStorageAccountFromConfiguration();
        QueueStorage qs = QueueStorage.Create(info);
        MessageQueue mq = qs.GetQueue("termine");

        mq.CreateQueue();
        Message msg = new Message(getByteArrayWithObject(neuerTermin));
        mq.PutMessage(msg);

    }
    //Hilfsmethode zum Serialisieren
    private String getByteArrayWithObject(Object o)
    {
        MemoryStream ms = new MemoryStream();

        XmlSerializer xs = new XmlSerializer(typeof(Termin));
        xs.Serialize(ms, o);
        return Encoding.ASCII.GetString(ms.ToArray());
    }
}
}
