PageRenderTime 19ms CodeModel.GetById 9ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 1ms

/BlogEngine/BlogEngine.NET/App_Code/Controls/PostCalendar.cs

#
C# | 299 lines | 202 code | 40 blank | 57 comment | 27 complexity | 1de1685c8d6654360c672fd6192c2e46 MD5 | raw file
  1// --------------------------------------------------------------------------------------------------------------------
  2// <summary>
  3//   The Post Calendar
  4// </summary>
  5// --------------------------------------------------------------------------------------------------------------------
  6
  7namespace App_Code.Controls
  8{
  9    using System;
 10    using System.IO;
 11    using System.Linq;
 12    using System.Text;
 13    using System.Web;
 14    using System.Web.UI;
 15    using System.Web.UI.HtmlControls;
 16    using System.Web.UI.WebControls;
 17
 18    using BlogEngine.Core;
 19
 20    /// <summary>
 21    /// The Post Calendar
 22    /// </summary>
 23    public class PostCalendar : Calendar, ICallbackEventHandler
 24    {
 25        #region Constants and Fields
 26
 27        /// <summary>
 28        /// The callback.
 29        /// </summary>
 30        private string callback;
 31
 32        #endregion
 33
 34        #region Properties
 35
 36        /// <summary>
 37        /// Gets or sets a value indicating whether ShowPostTitles.
 38        /// </summary>
 39        public bool ShowPostTitles
 40        {
 41            get
 42            {
 43                return (bool)(this.ViewState["ShowPostTitles"] ?? default(bool));
 44            }
 45
 46            set
 47            {
 48                this.ViewState["ShowPostTitles"] = value;
 49            }
 50        }
 51
 52        #endregion
 53
 54        #region Implemented Interfaces
 55
 56        #region ICallbackEventHandler
 57
 58        /// <summary>
 59        /// Returns the results of a callback event that targets a control.
 60        /// </summary>
 61        /// <returns>The result of the callback.</returns>
 62        public string GetCallbackResult()
 63        {
 64            return this.callback;
 65        }
 66
 67        /// <summary>
 68        /// Processes a callback event that targets a control.
 69        /// </summary>
 70        /// <param name="eventArgument">A string that represents an event argument to pass to the event handler.</param>
 71        public void RaiseCallbackEvent(string eventArgument)
 72        {
 73            DateTime date;
 74            if (!DateTime.TryParse(eventArgument, out date))
 75            {
 76                return;
 77            }
 78
 79            this.VisibleDate = date;
 80            this.ShowTitle = false;
 81            using (var sw = new StringWriter())
 82            {
 83                this.RenderControl(new HtmlTextWriter(sw));
 84                this.callback = sw.ToString();
 85            }
 86        }
 87
 88        #endregion
 89
 90        #endregion
 91
 92        #region Methods
 93
 94        /// <summary>
 95        /// Raises the <see cref="E:System.Web.UI.WebControls.Calendar.DayRender"/> event of the <see cref="T:System.Web.UI.WebControls.Calendar"/> control and allows you to provide a custom handler for the <see cref="E:System.Web.UI.WebControls.Calendar.DayRender"/> event.
 96        /// </summary>
 97        /// <param name="cell">A <see cref="T:System.Web.UI.WebControls.TableCell"/> that contains information about the cell to render.</param>
 98        /// <param name="day">A <see cref="T:System.Web.UI.WebControls.CalendarDay"/> that contains information about the day to render.</param>
 99        protected override void OnDayRender(TableCell cell, CalendarDay day)
100        {
101            if (day.IsToday)
102            {
103                cell.Attributes["id"] += "today";
104            }
105
106            var list = Post.GetPostsByDate(day.Date, day.Date);
107            if (list.Count > 0)
108            {
109                cell.Controls.Clear();
110                if (this.ShowPostTitles)
111                {
112                    cell.Controls.Add(new LiteralControl(day.DayNumberText));
113                    foreach (var a in
114                        list.Where(post => post.IsVisible).Select(post => new HtmlAnchor { InnerHtml = string.Format("<br /><br />{0}", post.Title), HRef = post.RelativeLink }))
115                    {
116                        cell.Controls.Add(a);
117                    }
118                }
119                else
120                {
121                    if (list[0].IsVisible)
122                    {
123                        var a = new HtmlAnchor
124                            {
125                                InnerHtml = day.DayNumberText,
126                                HRef =
127                                    string.Format("{0}{1}/{2}/{3}/default{4}", Utils.RelativeWebRoot, day.Date.Year, day.Date.ToString("MM"), day.Date.ToString("dd"), BlogConfig.FileExtension)
128                            };
129                        a.Attributes["class"] = "exist";
130                        cell.Controls.Add(a);
131                    }
132                    else
133                    {
134                        cell.Text = day.DayNumberText;
135                    }
136                }
137            }
138            else
139            {
140                cell.Controls.Clear();
141                cell.Text = day.DayNumberText;
142            }
143        }
144
145        /// <summary>
146        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
147        /// </summary>
148        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
149        protected override void OnLoad(EventArgs e)
150        {
151            this.Page.ClientScript.GetCallbackEventReference(this, "arg", null, "context");
152            base.OnLoad(e);
153        }
154
155        /// <summary>
156        /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
157        /// </summary>
158        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains event data.</param>
159        protected override void OnPreRender(EventArgs e)
160        {
161            if (!this.Page.IsCallback && !this.Page.IsPostBack)
162            {
163                this.VisibleDate = DateTime.Now;
164            }
165
166            if (!this.Page.IsPostBack && this.Context.Request.QueryString["date"] != null)
167            {
168                DateTime date;
169                if (DateTime.TryParse(this.Context.Request.QueryString["date"], out date))
170                {
171                    this.VisibleDate = date;
172                }
173            }
174
175            base.OnPreRender(e);
176
177            if (!this.ShowPostTitles)
178            {
179                this.ShowTitle = false;
180            }
181        }
182
183        /// <summary>
184        /// Displays the <see cref="T:System.Web.UI.WebControls.Calendar"/> control on the client.
185        /// </summary>
186        /// <param name="writer">A <see cref="T:System.Web.UI.HtmlTextWriter"/> that contains the output stream for rendering on the client.</param>
187        protected override void Render(HtmlTextWriter writer)
188        {
189            if (this.ShowPostTitles && !this.Page.IsCallback)
190            {
191                base.Render(writer);
192            }
193            else
194            {
195                if ((this.Page.IsPostBack && !this.Page.IsCallback) || this.VisibleDate == DateTime.MinValue)
196                {
197                    this.VisibleDate = DateTime.Now;
198                }
199
200                writer.Write("<div id=\"calendarContainer\">");
201                writer.Write("<table class=\"calendar\" summary=\"\" style=\";border-collapse:collapse;\">");
202                writer.Write("<tr><td>");
203
204                var oldest = GetOldestPostDate();
205
206                if (this.VisibleDate.Year != oldest.Year || this.VisibleDate.Month != oldest.Month)
207                {
208                    writer.Write("<a href=\"javascript:BlogEngine.Calendar.nav('{0}')\">{1}</a>&nbsp;&nbsp;", this.VisibleDate.AddMonths(-1).ToString("yyyy-MM-dd"), HttpUtility.HtmlEncode(this.PrevMonthText));
209                }
210                else
211                {
212                    writer.Write("{0}&nbsp;&nbsp;", HttpUtility.HtmlEncode(this.PrevMonthText));
213                }
214
215                writer.Write("</td><td style=\"text-align:center;width:100px\">{0}</td><td align=\"right\">", this.VisibleDate.ToString("MMMM yyyy"));
216
217                if (this.VisibleDate.Year != DateTime.Now.Year || this.VisibleDate.Month != DateTime.Now.Month)
218                {
219                    writer.Write("&nbsp;&nbsp;<a href=\"javascript:BlogEngine.Calendar.nav('{0}')\">{1}</a>", this.VisibleDate.AddMonths(1).ToString("yyyy-MM-dd"), HttpUtility.HtmlEncode(this.NextMonthText));
220                }
221                else
222                {
223                    writer.Write("&nbsp;&nbsp;{0}", HttpUtility.HtmlEncode(this.NextMonthText));
224                }
225
226                writer.Write("</td></tr>");
227                writer.Write("</table>");
228
229                this.Attributes.Add("summary", "Post calendar");
230
231                try
232                {
233                    base.Render(writer);
234                }
235                catch (Exception)
236                {
237                    writer.Write("<a href=\"javascript:void(location.reload(true))\">Reload page</a>");
238                }
239
240                writer.Write("</div>");
241
242                if (!this.Page.IsCallback)
243                {
244                    writer.Write(this.Script());
245                }
246            }
247        }
248
249        /// <summary>
250        /// Gets the oldest post date.
251        /// </summary>
252        /// <returns>The oldest post date.</returns>
253        private static DateTime GetOldestPostDate()
254        {
255            return Post.Posts.Count > 0 ? Post.Posts[Post.Posts.Count - 1].DateCreated : DateTime.Now;
256        }
257
258        /// <summary>
259        /// Scripts this instance.
260        /// </summary>
261        /// <returns>The script.</returns>
262        private string Script()
263        {
264            var sb = new StringBuilder();
265            sb.AppendFormat(
266                @"<script type=""text/javascript"">
267function setupBlogEngineCalendar() {{
268  BlogEngine.Calendar = {{
269  	  months: {{}},
270	  nav: function(date) {{
271		  var m = BlogEngine.Calendar.months;
272		  if (m[date] == null || m[date] == 'undefined')  {{
273		  	  {0}
274		  }} else {{
275			  BlogEngine.updateCalendar(m[date], date);
276		  }}
277	  }}
278  }};
279}}
280</script>",
281                this.Page.ClientScript.GetCallbackEventReference(this, "date", "BlogEngine.updateCalendar", "date"));
282
283            /*
284            ");
285            sb.Append("var months = new Object();");
286            sb.Append("function CalNav(date){");
287            sb.Append("if (months[date] == null || months[date] == 'undefined')");
288            sb.Append("{" + Page.ClientScript.GetCallbackEventReference(this, "date", "BlogEngine.updateCalendar", "date") + "}");
289            sb.Append("else {BlogEngine.updateCalendar(months[date], date)}");
290            sb.Append("}");
291            sb.Append("</script>");
292            */
293
294            return sb.ToString();
295        }
296
297        #endregion
298    }
299}