Update to Quote of the Day

Tuesday, 24 March 2009 06:49 AM
by Coose

The Quote of the Day post that I wrote earlier was my first widget for BlogEngine.net.  I quickly was not terribly pleased with it, so I made a few changes.

The biggest changes was the “one quote per day” vs “one quote per request” functionality.  Per request was too many changes…or what I call “shuckin’ and jivin’.”  One per day was not allowing my mindless quotes to be displayed too often.

So I made a change to the configuration to allow the quote to change every request, every minute, every hour, or every day.

So my edit.ascx file was changed to support a drop down combo box for the setting:

<asp:DropDownList ID="FrequencyBox" runat="server" />

and very minor code changes to handle the settings:

protected void Page_Load(object sender, EventArgs e)

{

    if (!Page.IsPostBack)

    {

        FrequencyBox.DataSource = Enum.GetNames(typeof(ChangeFrequency));

        FrequencyBox.DataBind();

 

        FrequencyBox.SelectedValue = ChangeFrequency.Always.ToString();

 

        StringDictionary settings = GetSettings();

        if (settings.ContainsKey("ChangeFrequency"))

        {

            FrequencyBox.SelectedValue = settings["ChangeFrequency"];

        }

    }

}

 

public override void Save()

{

    StringDictionary settings = GetSettings();

    settings["ChangeFrequency"] = FrequencyBox.SelectedValue;

    if (string.IsNullOrEmpty(settings["ChangeFrequency"]))

        settings["ChangeFrequency"] = ChangeFrequency.Always.ToString();

    SaveSettings(settings);

}

and another small change in the data object:

public static Quotation GetNextQuotation(ChangeFrequency frequency)

{

    using (BlogEngineEntities ctx = new BlogEngineEntities(ConnectionString))

    {

        Random r = _random;

 

        switch (frequency)

        {

            case ChangeFrequency.Daily:

                r = new Random(DateTime.Now.DayOfYear);

                break;

            case ChangeFrequency.Hourly:

                r = new Random(DateTime.Now.DayOfYear ^ (int)DateTime.Now.TimeOfDay.TotalHours);

                break;

            case ChangeFrequency.Minutely:

                r = new Random(DateTime.Now.DayOfYear ^ (int)DateTime.Now.TimeOfDay.TotalMinutes);

                break;

            case ChangeFrequency.Always:

                // just leave r equal to the _random

                break;

        }

 

        return ctx.QuotationSet.OrderBy(q => q.Added)

            .Skip(r.Next(0, ctx.QuotationSet.Count() - 1)).First();

    }

}

This should make the widget a little more flexible.  Using different random seeds ensures that the first “random” number in the sequence will be consistent with the same seed, and means I don’t have to maintain a timer, or state from previous requests.

Comment on this
Development

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading