PageRenderTime 58ms CodeModel.GetById 10ms app.highlight 41ms RepoModel.GetById 1ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/admin/Pages/EditPage.aspx.cs

#
C# | 410 lines | 262 code | 63 blank | 85 comment | 37 complexity | e9babeb20d42743ff918ff242ef54a9b MD5 | raw file
  1// --------------------------------------------------------------------------------------------------------------------
  2// <summary>
  3//   The page editor.
  4// </summary>
  5// --------------------------------------------------------------------------------------------------------------------
  6namespace Admin.Pages
  7{
  8    using System;
  9    using System.IO;
 10    using System.Linq;
 11    using System.Web.UI;
 12    using System.Web.UI.HtmlControls;
 13    using System.Web.UI.WebControls;
 14
 15    using BlogEngine.Core;
 16
 17    using Resources;
 18
 19    using Page = System.Web.UI.Page;
 20    using App_Code;
 21    using BlogEngine.Core.Providers;
 22
 23    public partial class EditPage : Page, ICallbackEventHandler
 24    {
 25        protected string PageUrl
 26        {
 27            get 
 28            {
 29                if (!String.IsNullOrEmpty(this.Request.QueryString["id"]) && this.Request.QueryString["id"].Length == 36)
 30                {
 31                    var id = new Guid(this.Request.QueryString["id"]);
 32                    BlogEngine.Core.Page pg = BlogEngine.Core.Page.GetPage(id);
 33                    return pg.RelativeLink;
 34                }
 35                return string.Empty;
 36            }
 37        }
 38        #region Constants and Fields
 39
 40        /// <summary>
 41        /// The callback.
 42        /// </summary>
 43        private string callback;
 44
 45        #endregion
 46
 47        #region Implemented Interfaces
 48
 49        #region ICallbackEventHandler
 50
 51        /// <summary>
 52        /// Returns the results of a callback event that targets a control.
 53        /// </summary>
 54        /// <returns>The result of the callback.</returns>
 55        public string GetCallbackResult()
 56        {
 57            return this.callback;
 58        }
 59
 60        /// <summary>
 61        /// Processes a callback event that targets a control.
 62        /// </summary>
 63        /// <param name="eventArgument">A string that represents an event argument to pass to the event handler.</param>
 64        public void RaiseCallbackEvent(string eventArgument)
 65        {
 66            this.callback = Utils.RemoveIllegalCharacters(eventArgument.Trim());
 67        }
 68
 69        #endregion
 70
 71        #endregion
 72
 73        #region Methods
 74
 75        /// <summary>
 76        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event to initialize the page.
 77        /// </summary>
 78        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
 79        protected override void OnInit(EventArgs e)
 80        {
 81            WebUtils.CheckRightsForAdminPagesPages(false);
 82            this.MaintainScrollPositionOnPostBack = true;
 83
 84            if (!String.IsNullOrEmpty(this.Request.QueryString["id"]) && this.Request.QueryString["id"].Length == 36)
 85            {
 86                var id = new Guid(this.Request.QueryString["id"]);
 87                this.BindPage(id);
 88                this.BindParents(id);
 89            }
 90            else if (!String.IsNullOrEmpty(this.Request.QueryString["delete"]) &&
 91                     this.Request.QueryString["delete"].Length == 36)
 92            {
 93                var id = new Guid(this.Request.QueryString["delete"]);
 94                this.DeletePage(id);
 95            }
 96            else
 97            {
 98                if (!Security.IsAuthorizedTo(Rights.CreateNewPages))
 99                {
100                    Response.Redirect(Utils.RelativeWebRoot);
101                    return;
102                }
103
104                this.BindParents(Guid.Empty);
105                this.cbPublished.Checked = Security.IsAuthorizedTo(Rights.PublishOwnPages);
106            }
107
108            this.btnUploadFile.Click += this.BtnUploadFileClick;
109            this.btnUploadImage.Click += this.BtnUploadImageClick;
110            this.btnUploadVideo.Click += this.BtnUploadVideoClick;
111            this.Page.Title = labels.pages;
112
113            base.OnInit(e);
114        }
115
116        /// <summary>
117        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
118        /// </summary>
119        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
120        protected override void OnLoad(EventArgs e)
121        {
122            base.OnLoad(e);
123
124            if (!this.Page.IsPostBack && !this.Page.IsCallback)
125            {
126                this.Page.ClientScript.GetCallbackEventReference(this, "title", "ApplyCallback", "slug");
127            }
128        }
129
130        /// <summary>
131        /// The bind page.
132        /// </summary>
133        /// <param name="pageId">
134        /// The page id.
135        /// </param>
136        private void BindPage(Guid pageId)
137        {
138            var page = BlogEngine.Core.Page.GetPage(pageId);
139
140            if (page == null || !page.CanUserEdit)
141            {
142                Response.Redirect(Request.Path);
143                return;
144            }
145
146            this.txtTitle.Text = page.Title;
147            this.txtContent.Text = page.Content;
148            this.txtDescription.Text = page.Description;
149            this.txtKeyword.Text = page.Keywords;
150            this.txtSlug.Text = page.Slug;
151            this.cbFrontPage.Checked = page.IsFrontPage;
152            this.cbShowInList.Checked = page.ShowInList;
153            this.cbPublished.Checked = page.IsPublished;
154        }
155
156        /// <summary>
157        /// The bind parents.
158        /// </summary>
159        /// <param name="pageId">
160        /// The page id.
161        /// </param>
162        private void BindParents(Guid pageId)
163        {
164            foreach (var page in BlogEngine.Core.Page.Pages.Where(page => pageId != page.Id))
165            {
166                this.ddlParent.Items.Add(new ListItem(page.Title, page.Id.ToString()));
167            }
168
169            this.ddlParent.Items.Insert(0, string.Format("-- {0} --", labels.noParent));
170            if (pageId == Guid.Empty)
171            {
172                return;
173            }
174
175            var parent = BlogEngine.Core.Page.GetPage(pageId);
176            if (parent != null)
177            {
178                this.ddlParent.SelectedValue = parent.Parent.ToString();
179            }
180        }
181
182        /// <summary>
183        /// Builds the child page list.
184        /// </summary>
185        /// <param name="page">The page to make a child list for.</param>
186        /// <returns>The page list.</returns>
187        private HtmlGenericControl BuildChildPageList(BlogEngine.Core.Page page)
188        {
189            var ul = new HtmlGenericControl("ul");
190            foreach (var childPage in BlogEngine.Core.Page.Pages.FindAll(p => p.Parent == page.Id))
191            {
192                var cLi = new HtmlGenericControl("li");
193                cLi.Attributes.CssStyle.Add("font-weight", "normal");
194                var cA = new HtmlAnchor { HRef = string.Format("?id={0}", childPage.Id), InnerHtml = childPage.Title };
195
196                var childText = new LiteralControl(string.Format(" ({0}) ", childPage.DateCreated.ToString("yyyy-dd-MM HH:mm")));
197
198                const string DeleteText = "Are you sure you want to delete the page?";
199                var delete = new HtmlAnchor { InnerText = labels.delete };
200                delete.Attributes["onclick"] = string.Format("if (confirm('{0}')){{location.href='?delete={1}'}}", DeleteText, childPage.Id);
201                delete.HRef = "javascript:void(0);";
202                delete.Style.Add(HtmlTextWriterStyle.FontWeight, "normal");
203
204                cLi.Controls.Add(cA);
205                cLi.Controls.Add(childText);
206                cLi.Controls.Add(delete);
207
208                if (childPage.HasChildPages)
209                {
210                    cLi.Attributes.CssStyle.Remove("font-weight");
211                    cLi.Attributes.CssStyle.Add("font-weight", "bold");
212                    cLi.Controls.Add(this.BuildChildPageList(childPage));
213                }
214
215                ul.Controls.Add(cLi);
216            }
217
218            return ul;
219        }
220
221        /// <summary>
222        /// The delete page.
223        /// </summary>
224        /// <param name="pageId">
225        /// The page id.
226        /// </param>
227        private void DeletePage(Guid pageId)
228        {
229            var page = BlogEngine.Core.Page.GetPage(pageId);
230            if (page == null)
231            {
232                return;
233            }
234            if (!page.CanUserDelete)
235            {
236                Response.Redirect(Utils.RelativeWebRoot);
237                return;
238            }
239
240            this.ResetParentPage(page);
241            page.Delete();
242            page.Save();
243            this.Response.Redirect("pages.aspx");
244        }
245
246        /// <summary>
247        /// Resets the parent page.
248        /// </summary>
249        /// <param name="page">The page to reset.</param>
250        private void ResetParentPage(BlogEngine.Core.Page page)
251        {
252            foreach (var child in BlogEngine.Core.Page.Pages.Where(child => page.Id == child.Parent))
253            {
254                child.Parent = Guid.Empty;
255                child.Save();
256                this.ResetParentPage(child);
257            }
258        }
259
260        /// <summary>
261        /// Formats the size.
262        /// </summary>
263        /// <param name="size">The size to format.</param>
264        /// <param name="formatString">The format string.</param>
265        /// <returns>The formatted string.</returns>
266        private static string SizeFormat(float size, string formatString)
267        {
268            if (size < 1024)
269            {
270                return string.Format("{0} bytes", size.ToString(formatString));
271            }
272
273            if (size < Math.Pow(1024, 2))
274            {
275                return string.Format("{0} kb", (size / 1024).ToString(formatString));
276            }
277
278            if (size < Math.Pow(1024, 3))
279            {
280                return string.Format("{0} mb", (size / Math.Pow(1024, 2)).ToString(formatString));
281            }
282
283            if (size < Math.Pow(1024, 4))
284            {
285                return string.Format("{0} gb", (size / Math.Pow(1024, 3)).ToString(formatString));
286            }
287
288            return size.ToString(formatString);
289        }
290
291        /// <summary>
292        /// Uploads the specified virtual folder.
293        /// </summary>
294        /// <param name="virtualFolder">The virtual folder.</param>
295        /// <param name="control">The control.</param>
296        /// <param name="fileName">Name of the file.</param>
297        private void Upload(string virtualFolder, FileUpload control, string fileName)
298        {
299            var folder = this.Server.MapPath(virtualFolder);
300            if (!Directory.Exists(folder))
301            {
302                Directory.CreateDirectory(folder);
303            }
304
305            control.PostedFile.SaveAs(folder + fileName);
306        }
307
308        /// <summary>
309        /// Handles the Click event of the btnSave control.
310        /// </summary>
311        /// <param name="sender">The source of the event.</param>
312        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
313        private void BtnSaveClick(object sender, EventArgs e)
314        {
315            if (!this.Page.IsValid)
316            {
317                throw new InvalidOperationException("One or more validators are invalid.");
318            }
319
320            var page = this.Request.QueryString["id"] != null ? BlogEngine.Core.Page.GetPage(new Guid(this.Request.QueryString["id"])) : new BlogEngine.Core.Page();
321
322            if (string.IsNullOrEmpty(this.txtContent.Text))
323            {
324                this.txtContent.Text = "[No text]";
325            }
326
327            page.Title = this.txtTitle.Text;
328            page.Content = this.txtContent.Text;
329            page.Description = this.txtDescription.Text;
330            page.Keywords = this.txtKeyword.Text;
331
332            if (this.cbFrontPage.Checked)
333            {
334                foreach (var otherPage in BlogEngine.Core.Page.Pages.Where(otherPage => otherPage.IsFrontPage))
335                {
336                    otherPage.IsFrontPage = false;
337                    otherPage.Save();
338                }
339            }
340
341            page.IsFrontPage = this.cbFrontPage.Checked;
342            page.ShowInList = this.cbShowInList.Checked;
343            page.IsPublished = this.cbPublished.Checked;
344
345            if (!string.IsNullOrEmpty(this.txtSlug.Text))
346            {
347                page.Slug = Utils.RemoveIllegalCharacters(this.txtSlug.Text.Trim());
348            }
349
350            page.Parent = this.ddlParent.SelectedIndex != 0 ? new Guid(this.ddlParent.SelectedValue) : Guid.Empty;
351
352            page.Save();
353
354            this.Response.Redirect(page.RelativeLink);
355        }
356
357        /// <summary>
358        /// Handles the Click event of the btnUploadFile control.
359        /// </summary>
360        /// <param name="sender">The source of the event.</param>
361        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
362        private void BtnUploadFileClick(object sender, EventArgs e)
363        {
364            var dirName = string.Format("/{0}/{1}", DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));
365            var dir = BlogService.GetDirectory(dirName);
366            var file = BlogService.UploadFile(txtUploadFile.PostedFile.InputStream, txtUploadFile.PostedFile.FileName, dir, true);
367            txtContent.Text += string.Format("<p><a href=\"{0}\">{1}</a></p>", file.FileDownloadPath, file.FileDescription);
368        }
369
370        /// <summary>
371        /// Handles the Click event of the btnUploadImage control.
372        /// </summary>
373        /// <param name="sender">The source of the event.</param>
374        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
375        private void BtnUploadImageClick(object sender, EventArgs e)
376        {
377            var dirName = string.Format("/{0}/{1}", DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));
378            var dir = BlogService.GetDirectory(dirName);
379            var file = BlogService.UploadFile(txtUploadImage.PostedFile.InputStream, txtUploadImage.PostedFile.FileName, dir, true);
380            txtContent.Text += string.Format("<img src=\"{0}\" />", file.AsImage.ImageUrl);
381        }
382
383        /// <summary>
384        /// Handles the Click event of the btnUploadVideo control.
385        /// </summary>
386        /// <param name="sender">The source of the event.</param>
387        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
388        protected void BtnUploadVideoClick(object sender, EventArgs e)
389        {
390
391            // default media folder
392            var mediaFolder = "media";
393
394            // get the mediaplayer extension and use it's folder
395            var mediaPlayerExtension = BlogEngine.Core.Web.Extensions.ExtensionManager.GetExtension("MediaElementPlayer");
396            mediaFolder = mediaPlayerExtension.Settings[0].GetSingleValue("folder");
397
398            var folder = "~/" + mediaFolder + "/";
399            var fileName = txtUploadVideo.FileName;
400
401            Upload(folder, txtUploadVideo, fileName);
402
403            var shortCode = "[video src=\"" + fileName + "\"]";
404
405            txtContent.Text += shortCode;
406        }
407
408        #endregion
409    }
410}