Advertisement
Guest User

DateFolders-1.5.cs

a guest
Feb 12th, 2012
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 22.52 KB | None | 0 0
  1. /*
  2. DateFolders v1.5 for umbraco 4.5+
  3. Created by Stefan Kip (kipusoep), InfoCaster
  4. Modified by Niek Bosch, De Media Fabriek
  5.  
  6. MIT license
  7.  
  8. Copyright (c) 2011 InfoCaster
  9.  
  10. Permission is hereby granted, free of charge, to any person obtaining a copy
  11. of this software and associated documentation files (the "Software"), to deal
  12. in the Software without restriction, including without limitation the rights
  13. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. copies of the Software, and to permit persons to whom the Software is
  15. furnished to do so, subject to the following conditions:
  16.  
  17. The above copyright notice and this permission notice shall be included in
  18. all copies or substantial portions of the Software.
  19.  
  20. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. THE SOFTWARE.
  27. */
  28.  
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Configuration;
  32. using System.Linq;
  33. using System.Web;
  34. using umbraco.BasePages;
  35. using umbraco.BusinessLogic;
  36. using umbraco.cms.businesslogic;
  37. using umbraco.cms.businesslogic.web;
  38. using umbraco.presentation.nodeFactory;
  39.  
  40. namespace InfoCaster.Umbraco.Common
  41. {
  42.     /// <summary>
  43.     /// This package creates Datefolders (year/month(/day)) for the specified doctype for Umbraco 4.5+
  44.     ///
  45.     /// Behavior
  46.     ///
  47.     /// - When you create a document with doctype "itemDocType", this package will automatically create year/month/day folders for it
  48.     /// - When you edit the "itemDateProperty", the document is automatically moved to the correct year/month/day folder
  49.     /// - Automatically cleans up empty year, month and day folders
  50.     /// - Orders the items in the year, month and dayfolders by "itemDateProperty" with every action
  51.     ///
  52.     /// Configuration
  53.     ///
  54.     /// Add these keys/values to your appSettings section in the web.config:
  55.     /// - Key: "datefolders:ItemDocType" - the doctype alias to create datefolders for (e.g. "newsItem") - comma separated values are allowed for multiple doctype aliases
  56.     /// - Key: "datefolders:ItemDateProperty" - the property of the itemDocType to read the date from (e.g. "startDate") (don't add this key if you just want to use the document's create date)
  57.     /// - Key: "datefolders:DateFolderDocType" - the doctype to use for creating the year/month/day folders (e.g "DateFolder")
  58.     /// - Key: "datefolders:CreateDayFolders" - boolean indicating whether or not day folders should be created
  59.     /// - Key: "datefolders:ForceDateFolderStructure" - boolean indicating whether or not the year/month/day folder structure should be enforced
  60.     ///
  61.     /// Changelog
  62.     ///
  63.     /// Version 1.5
  64.     /// - Added support for enforcing the year/month/day folder structure.
  65.     ///
  66.     /// Version 1.4
  67.     /// - Removed Threading (Threading can cause the back-end to be out-of-sync, therefore removed)
  68.     /// - Changed configuration keys, added prefix (legacy still works)
  69.     /// - Added day folders feature (configurable, off by default)
  70.     /// - Fixed silly order by hard-coded propertyAlias bug
  71.     ///
  72.     /// Version 1.3
  73.     /// - Better exception handling (speechbubble)
  74.     /// - Exception get's handled when the datefoler document type doesn't exist
  75.     /// - Month folders are now named with a leading zero if the month number is a single number (01, 02 etc.)
  76.     /// - Exception get's handled when a date item is created under the 'Content' root node
  77.     ///
  78.     /// Version 1.2
  79.     /// - Support for multiple itemDocTypes (comma separated)
  80.     ///
  81.     /// Version 1.1
  82.     /// - Tree get's synced automatically
  83.     /// </summary>
  84.     public class DateFolders : ApplicationBase
  85.     {
  86.         readonly string[] _itemDocType;
  87.         readonly string _itemDateProperty;
  88.         readonly string _dateFolderDocType;
  89.         readonly bool _createDayFolders;
  90.         readonly bool _forceDateFolderStructure;
  91.  
  92.         static readonly object _syncer = new object();
  93.  
  94.         /* Configuration properties:
  95.          *
  96.          * datefolders:ItemDocType (string)
  97.          * datefolders:ItemDateProperty (string, optional, default create date)
  98.          * datefolders:DateFolderDocType (string)
  99.          * datefolders:CreateDayFolders (bool, optional, default false)
  100.          * datefolders:ForceDateFolderStructure (bool, optional, default false)
  101.          */
  102.  
  103.         /// <summary>
  104.         /// Constructor
  105.         /// </summary>
  106.         public DateFolders()
  107.         {
  108.             if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["datefolders:ItemDocType"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["datefolders:DateFolderDocType"]))
  109.             {
  110.                 _itemDocType = ConfigurationManager.AppSettings["datefolders:ItemDocType"].Split(',');
  111.                 _itemDateProperty = ConfigurationManager.AppSettings["datefolders:ItemDateProperty"];
  112.                 _dateFolderDocType = ConfigurationManager.AppSettings["datefolders:DateFolderDocType"];
  113.                 string createDayFoldersString = ConfigurationManager.AppSettings["datefolders:CreateDayFolders"];
  114.                 if (!string.IsNullOrEmpty(createDayFoldersString))
  115.                     bool.TryParse(createDayFoldersString, out _createDayFolders);
  116.                 string forceDateFolderStructureString = ConfigurationManager.AppSettings["datefolders:ForceDateFolderStructure"];
  117.                 if (!string.IsNullOrEmpty(forceDateFolderStructureString))
  118.                     bool.TryParse(forceDateFolderStructureString, out _forceDateFolderStructure);
  119.             }
  120.             else if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["itemDocType"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["dateFolderDocType"]))
  121.             {
  122.                 // Legacy
  123.                 _itemDocType = ConfigurationManager.AppSettings["itemDocType"].Split(',');
  124.                 _itemDateProperty = ConfigurationManager.AppSettings["itemDateProperty"];
  125.                 _dateFolderDocType = ConfigurationManager.AppSettings["dateFolderDocType"];
  126.                 string createDayFoldersString = ConfigurationManager.AppSettings["createDayFolders"];
  127.                 if (!string.IsNullOrEmpty(createDayFoldersString))
  128.                     bool.TryParse(createDayFoldersString, out _createDayFolders);
  129.                 string forceDateFolderStructureString = ConfigurationManager.AppSettings["forceDateFolderStructure"];
  130.                 if (!string.IsNullOrEmpty(forceDateFolderStructureString))
  131.                     bool.TryParse(forceDateFolderStructureString, out _forceDateFolderStructure);
  132.             }
  133.  
  134.             if (_itemDocType.Length > 0 && !string.IsNullOrEmpty(_dateFolderDocType))
  135.             {
  136.                 Document.New += new Document.NewEventHandler(Document_New);
  137.                 Document.AfterSave += new Document.SaveEventHandler(Document_AfterSave);
  138.                 Document.BeforeMoveToTrash += new Document.MoveToTrashEventHandler(Document_BeforeMoveToTrash);
  139.                 Document.AfterMoveToTrash += new Document.MoveToTrashEventHandler(Document_AfterMoveToTrash);
  140.             }
  141.         }
  142.  
  143.         /// <summary>
  144.         /// Before move to trash event
  145.         /// </summary>
  146.         /// <param name="doc">The document</param>
  147.         /// <param name="e">The event args</param>
  148.         void Document_BeforeMoveToTrash(Document doc, MoveToTrashEventArgs e)
  149.         {
  150.             if (_itemDocType.Contains(doc.ContentType.Alias))
  151.             {
  152.                 try
  153.                 {
  154.                     if (_createDayFolders)
  155.                     {
  156.                         HttpContext.Current.Items.Add("dayId", doc.ParentId);
  157.                         HttpContext.Current.Items.Add("monthId", doc.Parent.ParentId);
  158.                         HttpContext.Current.Items.Add("yearId", doc.Parent.Parent.ParentId);
  159.                     }
  160.                     else
  161.                     {
  162.                         HttpContext.Current.Items.Add("monthId", doc.ParentId);
  163.                         HttpContext.Current.Items.Add("yearId", doc.Parent.ParentId);
  164.                     }
  165.                 }
  166.                 catch (Exception ex)
  167.                 {
  168.                     if (BasePage.Current != null)
  169.                         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "DateFolders Document_BeforeMoveToTrash exception", ex.Message);
  170.                     umbraco.BusinessLogic.Log.Add(LogTypes.Error, -1, string.Format("DateFolders Document_BeforeMoveToTrash exception: {0}", ex.Message));
  171. #if DEBUG
  172.                     System.Diagnostics.Trace.TraceInformation(string.Format("DateFolders Document_BeforeMoveToTrash exception: {0}", ex.Message));
  173. #endif
  174.                 }
  175.             }
  176.         }
  177.  
  178.         /// <summary>
  179.         /// After move to trash event
  180.         /// </summary>
  181.         /// <param name="doc">The document</param>
  182.         /// <param name="e">The event args</param>
  183.         void Document_AfterMoveToTrash(Document doc, MoveToTrashEventArgs e)
  184.         {
  185.             if (_itemDocType.Contains(doc.ContentType.Alias))
  186.             {
  187.                 // Date item deleted
  188.                 try
  189.                 {
  190.                     int dayId = -100, monthId, yearId;
  191.  
  192.                     if (_createDayFolders)
  193.                     {
  194.                         dayId = int.Parse(HttpContext.Current.Items["dayId"].ToString());
  195.                         HttpContext.Current.Items.Remove("dayId");
  196.                         monthId = int.Parse(HttpContext.Current.Items["monthId"].ToString());
  197.                         yearId = int.Parse(HttpContext.Current.Items["yearId"].ToString());
  198.                     }
  199.                     else
  200.                     {
  201.                         monthId = int.Parse(HttpContext.Current.Items["monthId"].ToString());
  202.                         yearId = int.Parse(HttpContext.Current.Items["yearId"].ToString());
  203.                     }
  204.  
  205.                     HttpContext.Current.Items.Remove("monthId");
  206.                     HttpContext.Current.Items.Remove("yearId");
  207.  
  208.                     if (_createDayFolders)
  209.                     {
  210.                         Node day = new Node(dayId);
  211.                         if (day.Children.Count < 1)
  212.                             new Document(dayId).DeleteCompletely();
  213.                     }
  214.  
  215.                     Node month = new Node(monthId);
  216.                     if (month.Children.Count < 1)
  217.                     {
  218.                         new Document(monthId).DeleteCompletely();
  219.  
  220.                         Node year = new Node(yearId);
  221.                         if (year.Children.Count < 1)
  222.                             new Document(yearId).DeleteCompletely();
  223.                     }
  224.                 }
  225.                 catch (Exception ex)
  226.                 {
  227.                     if (BasePage.Current != null)
  228.                         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "DateFolders Document_AfterMoveToTrash exception", ex.Message);
  229.                     umbraco.BusinessLogic.Log.Add(LogTypes.Error, -1, string.Format("DateFolders Document_AfterMoveToTrash exception: {0}", ex.Message));
  230. #if DEBUG
  231.                     System.Diagnostics.Trace.TraceInformation(string.Format("DateFolders Document_AfterMoveToTrash exception: {0}", ex.Message));
  232. #endif
  233.                 }
  234.             }
  235.         }
  236.  
  237.         /// <summary>
  238.         /// After save event
  239.         /// </summary>
  240.         /// <param name="doc">The document</param>
  241.         /// <param name="e">The event args</param>
  242.         void Document_AfterSave(Document doc, SaveEventArgs e)
  243.         {
  244.             if (_itemDocType.Contains(doc.ContentType.Alias))
  245.             {
  246.                 DocumentType folderDocType = DocumentType.GetByAlias(_dateFolderDocType);
  247.                 if (folderDocType != null)
  248.                 {
  249.                     if (doc.ParentId > 0)
  250.                     {
  251.                         // Date item saved
  252.                         DateTime date = default(DateTime);
  253.                         if (!string.IsNullOrEmpty(_itemDateProperty))
  254.                         {
  255.                             string dateValue = doc.GetDatePropertyValue(_itemDateProperty);
  256.                             if (!string.IsNullOrEmpty(dateValue))
  257.                                 DateTime.TryParse(dateValue, out date);
  258.                         }
  259.                         if (date == default(DateTime))
  260.                             date = doc.CreateDateTime;
  261.  
  262.                         Document parent, monthFolder, yearFolder, dayFolder = null, dayDoc = null, monthDoc = null, yearDoc = null;
  263.  
  264.                         if (_createDayFolders)
  265.                         {
  266.                             dayFolder = new Document(doc.ParentId);
  267.                             monthFolder = new Document(dayFolder.ParentId);
  268.                             yearFolder = new Document(monthFolder.ParentId);
  269.                         }
  270.                         else
  271.                         {
  272.                             monthFolder = new Document(doc.ParentId);
  273.                             yearFolder = new Document(monthFolder.ParentId);
  274.                         }
  275.                         parent = new Document(yearFolder.ParentId);
  276.  
  277.                         bool yearChanged, monthChanged, dayChanged = false;
  278.                         yearChanged = date.Year.ToString() != yearFolder.Text;
  279.                         monthChanged = date.Month.ToString("00") != monthFolder.Text;
  280.                         if (_createDayFolders)
  281.                             dayChanged = date.Day.ToString("00") != dayFolder.Text;
  282.  
  283.                         if (yearChanged || monthChanged || dayChanged)
  284.                         {
  285.                             // Date changed
  286.                             Document newYearFolder = null, newMonthFolder = null, newDayFolder = null;
  287.                             if (yearChanged)
  288.                             {
  289.                                 // Year changed
  290.                                 newYearFolder = parent.Children.FirstOrDefault(x => x.ContentType.Alias == _dateFolderDocType && x.Text == date.Year.ToString());
  291.                                 if (newYearFolder == null)
  292.                                 {
  293.                                     // Create year folder
  294.                                     newYearFolder = Document.MakeNew(date.Year.ToString(), DocumentType.GetByAlias(_dateFolderDocType), doc.User, parent.Id);
  295.                                 }
  296.                             }
  297.                             else
  298.                                 newYearFolder = yearFolder;
  299.  
  300.                             // Month
  301.                             newMonthFolder = newYearFolder.Children.FirstOrDefault(x => x.ContentType.Alias == _dateFolderDocType && x.Text == date.Month.ToString("00"));
  302.                             if (newMonthFolder == null)
  303.                             {
  304.                                 // Create month folder
  305.                                 newMonthFolder = Document.MakeNew(date.Month.ToString("00"), DocumentType.GetByAlias(_dateFolderDocType), doc.User, newYearFolder.Id);
  306.                             }
  307.  
  308.                             if (_createDayFolders)
  309.                             {
  310.                                 // Day
  311.                                 newDayFolder = newMonthFolder.Children.FirstOrDefault(x => x.ContentType.Alias == _dateFolderDocType && x.Text == date.Day.ToString("00"));
  312.                                 if (newDayFolder == null)
  313.                                 {
  314.                                     // Create day folder
  315.                                     newDayFolder = Document.MakeNew(date.Day.ToString("00"), DocumentType.GetByAlias(_dateFolderDocType), doc.User, newMonthFolder.Id);
  316.                                 }
  317.                             }
  318.  
  319.                             // Move
  320.                             if (_createDayFolders)
  321.                                 doc.Move(newDayFolder.Id);
  322.                             else
  323.                                 doc.Move(newMonthFolder.Id);
  324.  
  325.                             if (doc.Published)
  326.                                 doc.SaveAndPublish();
  327.  
  328.                             int orderParentId = newMonthFolder.Id;
  329.                             if (_createDayFolders)
  330.                                 orderParentId = newDayFolder.Id;
  331.  
  332.                             if (!string.IsNullOrEmpty(_itemDateProperty))
  333.                                 OrderChildrenByDateProperty(new Document(orderParentId), _itemDateProperty);
  334.                             else
  335.                                 OrderChildrenByCreateDate(new Document(orderParentId));
  336.  
  337.                             if (newYearFolder != null)
  338.                                 newYearFolder.SaveAndPublish();
  339.                             if (newMonthFolder != null)
  340.                                 newMonthFolder.SaveAndPublish();
  341.                             if (newDayFolder != null)
  342.                                 newDayFolder.SaveAndPublish();
  343.  
  344.                             // Delete if empty
  345.                             if (_createDayFolders)
  346.                             {
  347.                                 dayDoc = new Document(dayFolder.Id);
  348.                                 if (dayDoc.ChildCount < 1)
  349.                                 {
  350.                                     dayDoc.DeleteCompletely();
  351.                                 }
  352.                             }
  353.  
  354.                             monthDoc = new Document(monthFolder.Id);
  355.                             if (monthDoc.ChildCount < 1)
  356.                             {
  357.                                 monthDoc.DeleteCompletely();
  358.  
  359.                                 yearDoc = new Document(yearFolder.Id);
  360.                                 if (yearDoc.ChildCount < 1)
  361.                                     yearDoc.DeleteCompletely();
  362.                             }
  363.  
  364.                             // Order
  365.                             OrderChildrenByName(new Document(parent.Id));
  366.                             OrderChildrenByName(new Document(newYearFolder.Id));
  367.                             if (_createDayFolders)
  368.                                 OrderChildrenByName(new Document(newMonthFolder.Id));
  369.  
  370.                             doc = new Document(doc.Id);
  371.  
  372.                             BasePage.Current.ClientTools
  373.                                 .ChangeContentFrameUrl(string.Concat("editContent.aspx?id=", doc.Id));
  374.                         }
  375.                     }
  376.                     else
  377.                     {
  378.                         // Item is created under 'Content' root, which is unsupported
  379.                         if (BasePage.Current != null)
  380.                             BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "Unsupported", "Creating a datefolders item under 'Content' root is unsupported");
  381.                     }
  382.                 }
  383.                 else
  384.                 {
  385.                     // Date folder doctype is null
  386.                     if (BasePage.Current != null)
  387.                         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "Configuration error", string.Format("The date folder doctype ('{0}') does not exist", _dateFolderDocType));
  388.                 }
  389.             }
  390.         }
  391.  
  392.         /// <summary>
  393.         /// New document event
  394.         /// </summary>
  395.         /// <param name="doc">The document</param>
  396.         /// <param name="e">The event args</param>
  397.         void Document_New(Document doc, NewEventArgs e)
  398.         {
  399.             try
  400.             {
  401.                 DocumentType folderDocType = DocumentType.GetByAlias(_dateFolderDocType);
  402.                 if (folderDocType != null)
  403.                 {
  404.                     Document parent = new Document(doc.ParentId);
  405.  
  406.                     if (_forceDateFolderStructure)
  407.                     {
  408.                         // Find first ancestor that is not a date folder
  409.                         while (parent.ContentType.Alias == _dateFolderDocType)
  410.                         {
  411.                             parent = new Document(parent.ParentId);
  412.                         }
  413.                     }
  414.  
  415.                     if (_itemDocType.Contains(doc.ContentType.Alias))
  416.                     {
  417.                         // Date item created
  418.                         DateTime now = DateTime.Now;
  419.  
  420.                         Document yearFolder = parent.Children.FirstOrDefault(x => x.ContentType.Alias == _dateFolderDocType && x.Text == now.Year.ToString());
  421.                         if (yearFolder == null)
  422.                         {
  423.                             // Create year folder
  424.                             yearFolder = Document.MakeNew(now.Year.ToString(), DocumentType.GetByAlias(_dateFolderDocType), doc.User, parent.Id);
  425.                         }
  426.  
  427.                         Document monthFolder = yearFolder.Children.FirstOrDefault(x => x.ContentType.Alias == _dateFolderDocType && x.Text == now.Month.ToString("00"));
  428.                         if (monthFolder == null)
  429.                         {
  430.                             // Create month folder
  431.                             monthFolder = Document.MakeNew(now.Month.ToString("00"), DocumentType.GetByAlias(_dateFolderDocType), doc.User, yearFolder.Id);
  432.                         }
  433.  
  434.                         Document dayFolder = null;
  435.                         if (_createDayFolders)
  436.                         {
  437.                             dayFolder = monthFolder.Children.FirstOrDefault(x => x.ContentType.Alias == _dateFolderDocType && x.Text == now.Day.ToString("00"));
  438.                             if (dayFolder == null)
  439.                             {
  440.                                 // Create day folder
  441.                                 dayFolder = Document.MakeNew(now.Day.ToString("00"), DocumentType.GetByAlias(_dateFolderDocType), doc.User, monthFolder.Id);
  442.                             }
  443.                         }
  444.  
  445.                         if (_createDayFolders)
  446.                             doc.Move(dayFolder.Id);
  447.                         else
  448.                             doc.Move(monthFolder.Id);
  449.                         doc.Save();
  450.  
  451.                         if (yearFolder != null)
  452.                             yearFolder.SaveAndPublish();
  453.                         if (monthFolder != null)
  454.                             monthFolder.SaveAndPublish();
  455.                         if (dayFolder != null)
  456.                             dayFolder.SaveAndPublish();
  457.  
  458.                         // Order
  459.                         OrderChildrenByName(new Document(parent.Id));
  460.                         OrderChildrenByName(new Document(yearFolder.Id));
  461.                         if (_createDayFolders)
  462.                             OrderChildrenByName(new Document(monthFolder.Id));
  463.                     }
  464.                 }
  465.                 else
  466.                 {
  467.                     // Date folder doctype is null
  468.                     if (BasePage.Current != null)
  469.                         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "Date folder property", string.Format("The date folder doctype does not exist ({0})", _dateFolderDocType));
  470.                 }
  471.             }
  472.             catch { }
  473.         }
  474.  
  475.         /// <summary>
  476.         /// Order the children by propertyAlias
  477.         /// </summary>
  478.         /// <param name="parent">The parent document</param>
  479.         /// <param name="propertyAlias">The property alias</param>
  480.         static void OrderChildrenByDateProperty(Document parent, string propertyAlias)
  481.         {
  482.             lock (_syncer)
  483.             {
  484.                 try
  485.                 {
  486.                     DoOrder(parent.Children.OrderBy(x => DateTime.Parse(x.GetPropertyValueAsString(propertyAlias))));
  487.                 }
  488.                 catch (Exception ex)
  489.                 {
  490.                     if (BasePage.Current != null)
  491.                         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "DateFolders OrderChildrenByDateProperty exception", ex.Message);
  492.                     umbraco.BusinessLogic.Log.Add(LogTypes.Error, -1, string.Format("DateFolders OrderChildrenByDateProperty exception: {0}", ex.Message));
  493. #if DEBUG
  494.                     System.Diagnostics.Trace.TraceInformation(string.Format("DateFolders OrderChildrenByDateProperty exception: {0}", ex.Message));
  495. #endif
  496.                 }
  497.             }
  498.         }
  499.  
  500.         /// <summary>
  501.         /// Order the children by createDate
  502.         /// </summary>
  503.         /// <param name="parent">The parent document</param>
  504.         static void OrderChildrenByCreateDate(Document parent)
  505.         {
  506.             lock (_syncer)
  507.             {
  508.                 try
  509.                 {
  510.                     DoOrder(parent.Children.OrderBy(x => x.CreateDateTime));
  511.                 }
  512.                 catch (Exception ex)
  513.                 {
  514.                     if (BasePage.Current != null)
  515.                         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "DateFolders OrderChildrenByCreateDate exception", ex.Message);
  516.                     umbraco.BusinessLogic.Log.Add(LogTypes.Error, -1, string.Format("DateFolders OrderChildrenByCreateDate exception: {0}", ex.Message));
  517. #if DEBUG
  518.                     System.Diagnostics.Trace.TraceInformation(string.Format("DateFolders OrderChildrenByCreateDate exception: {0}", ex.Message));
  519. #endif
  520.                 }
  521.             }
  522.         }
  523.  
  524.         /// <summary>
  525.         /// Order the children by name
  526.         /// </summary>
  527.         /// <param name="parent">The parent document</param>
  528.         static void OrderChildrenByName(Document parent)
  529.         {
  530.             lock (_syncer)
  531.             {
  532.                 try
  533.                 {
  534.                     DoOrder(parent.Children.OrderBy(x => int.Parse(x.Text)));
  535.                 }
  536.                 catch (Exception ex)
  537.                 {
  538.                     if (BasePage.Current != null)
  539.                         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "DateFolders OrderChildrenByName exception", ex.Message);
  540.                     umbraco.BusinessLogic.Log.Add(LogTypes.Error, -1, string.Format("DateFolders OrderChildrenByName exception: {0}", ex.Message));
  541. #if DEBUG
  542.                     System.Diagnostics.Trace.TraceInformation(string.Format("DateFolders OrderChildrenByName exception: {0}", ex.Message));
  543. #endif
  544.                 }
  545.             }
  546.         }
  547.  
  548.         /// <summary>
  549.         /// Order documents
  550.         /// </summary>
  551.         /// <param name="documents">The documents</param>
  552.         static void DoOrder(IEnumerable<Document> documents)
  553.         {
  554.             int sortOrder = 0;
  555.             foreach (Document objChild in documents)
  556.             {
  557.                 objChild.sortOrder = sortOrder;
  558.                 sortOrder++;
  559.             }
  560.         }
  561.     }
  562.  
  563.     static class UmbracoExtensions
  564.     {
  565.         /// <summary>
  566.         /// Deletes a document completely
  567.         /// </summary>
  568.         /// <param name="document">The document to delete completely</param>
  569.         public static void DeleteCompletely(this Document document)
  570.         {
  571.             if (document != null)
  572.             {
  573.                 if (document.Published)
  574.                 {
  575.                     document.UnPublish();
  576.                     umbraco.library.UnPublishSingleNode(document.Id);
  577.                 }
  578.                 document.delete(true);
  579.             }
  580.         }
  581.  
  582.         /// <summary>
  583.         /// Returns the value as string of the property with the given alias
  584.         /// </summary>
  585.         /// <param name="node">The document</param>
  586.         /// <param name="propertyAlias">The alias of the property</param>
  587.         /// <returns>The property's value</returns>
  588.         public static string GetPropertyValueAsString(this Document document, string propertyAlias)
  589.         {
  590.             if (document.getProperty(propertyAlias) != null && document.getProperty(propertyAlias).Value != null)
  591.                 return document.getProperty(propertyAlias).Value.ToString();
  592.  
  593.             return string.Empty;
  594.         }
  595.  
  596.         /// <summary>
  597.         /// Saves and publishes a document
  598.         /// </summary>
  599.         /// <param name="document">The document to save and publish</param>
  600.         public static void SaveAndPublish(this Document document)
  601.         {
  602.             if (document != null)
  603.             {
  604.                 document.Save();
  605.                 document.Publish(document.User);
  606.                 umbraco.library.UpdateDocumentCache(document.Id);
  607.             }
  608.         }
  609.  
  610.         /// <summary>
  611.         /// Gets the date property
  612.         /// </summary>
  613.         /// <param name="doc"></param>
  614.         /// <returns></returns>
  615.         public static string GetDatePropertyValue(this Document doc, string itemDateProperty)
  616.         {
  617.             if (string.IsNullOrEmpty(itemDateProperty))
  618.                 return doc.CreateDateTime.ToString();
  619.             return doc.GetPropertyValueAsString(itemDateProperty);
  620.         }
  621.     }
  622. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement