diff --git a/src/Umbraco.Core/Models/File.cs b/src/Umbraco.Core/Models/File.cs index aa2b6909b5..9b3229e016 100644 --- a/src/Umbraco.Core/Models/File.cs +++ b/src/Umbraco.Core/Models/File.cs @@ -14,11 +14,13 @@ namespace Umbraco.Core.Models public abstract class File : Entity, IFile { private string _path; + private string _originalPath; private string _content = string.Empty; //initialize to empty string, not null protected File(string path) { _path = path; + _originalPath = _path; } private static readonly PropertyInfo ContentSelector = ExpressionHelper.GetPropertyInfo(x => x.Content); @@ -75,6 +77,22 @@ namespace Umbraco.Core.Models } } + /// + /// Gets the original path of the file + /// + public string OriginalPath + { + get { return _originalPath; } + } + + /// + /// Called to re-set the OriginalPath to the Path + /// + public void ResetOriginalPath() + { + _originalPath = _path; + } + /// /// Gets or sets the Content of a File /// diff --git a/src/Umbraco.Core/Models/IFile.cs b/src/Umbraco.Core/Models/IFile.cs index 24bdd01424..de900c50ec 100644 --- a/src/Umbraco.Core/Models/IFile.cs +++ b/src/Umbraco.Core/Models/IFile.cs @@ -24,6 +24,16 @@ namespace Umbraco.Core.Models /// string Path { get; set; } + /// + /// Gets the original path of the file + /// + string OriginalPath { get; } + + /// + /// Called to re-set the OriginalPath to the Path + /// + void ResetOriginalPath(); + /// /// Gets or sets the Content of a File /// diff --git a/src/Umbraco.Core/Models/StylesheetProperty.cs b/src/Umbraco.Core/Models/StylesheetProperty.cs index 302989f621..fead6f033a 100644 --- a/src/Umbraco.Core/Models/StylesheetProperty.cs +++ b/src/Umbraco.Core/Models/StylesheetProperty.cs @@ -65,10 +65,5 @@ namespace Umbraco.Core.Models } } - - //public bool IsPartOfAtRule { get; set; } - ////This should never be used, it's here because we still have stylesheets based on DB ids and - //// we need to wrap the legacy classes - //internal int Id { get; set; } } } \ No newline at end of file diff --git a/src/Umbraco.Core/NameValueCollectionExtensions.cs b/src/Umbraco.Core/NameValueCollectionExtensions.cs index d47add61ed..7b55d8131a 100644 --- a/src/Umbraco.Core/NameValueCollectionExtensions.cs +++ b/src/Umbraco.Core/NameValueCollectionExtensions.cs @@ -8,6 +8,13 @@ namespace Umbraco.Core { internal static class NameValueCollectionExtensions { + public static IEnumerable> AsEnumerable(this NameValueCollection nvc) + { + foreach (string key in nvc.AllKeys) + { + yield return new KeyValuePair(key, nvc[key]); + } + } public static bool ContainsKey(this NameValueCollection collection, string key) { diff --git a/src/Umbraco.Core/Persistence/Repositories/FileRepository.cs b/src/Umbraco.Core/Persistence/Repositories/FileRepository.cs index 4020dbb713..391a777e5e 100644 --- a/src/Umbraco.Core/Persistence/Repositories/FileRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/FileRepository.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text; using Umbraco.Core.IO; using Umbraco.Core.Models; @@ -47,7 +48,7 @@ namespace Umbraco.Core.Persistence.Repositories public virtual void AddOrUpdate(TEntity entity) { - if (FileSystem.FileExists(entity.Path) == false) + if (FileSystem.FileExists(entity.OriginalPath) == false) { _work.RegisterAdded(entity, this); } @@ -146,6 +147,10 @@ namespace Umbraco.Core.Persistence.Repositories protected virtual void PersistUpdatedItem(TEntity entity) { + //TODO: A big problem here is if the entities 'Path' changes, if that is the case then + // we'd need to rename the underlying file, BUT how would we do this since we aren't storing an + // original path property. + using (var stream = GetContentStream(entity.Content)) { FileSystem.AddFile(entity.Path, stream, true); @@ -156,6 +161,15 @@ namespace Umbraco.Core.Persistence.Repositories entity.Key = entity.Path.EncodeAsGuid(); entity.VirtualPath = FileSystem.GetUrl(entity.Path); } + + //now that the file has been written, we need to check if the path had been changed + if (entity.Path.InvariantEquals(entity.OriginalPath) == false) + { + //delete the original file + FileSystem.DeleteFile(entity.OriginalPath); + //reset the original path on the file + entity.ResetOriginalPath(); + } } protected virtual void PersistDeletedItem(TEntity entity) @@ -178,15 +192,28 @@ namespace Umbraco.Core.Persistence.Repositories return new MemoryStream(Encoding.UTF8.GetBytes(content)); } - protected IEnumerable FindAllFiles(string path) + /// + /// Returns all files in the file system + /// + /// + /// + /// + /// Returns a list of all files with their paths. For example: + /// + /// \hello.txt + /// \folder1\test.txt + /// \folder1\blah.csv + /// \folder1\folder2\blahhhhh.svg + /// + protected IEnumerable FindAllFiles(string path, string filter) { var list = new List(); - list.AddRange(FileSystem.GetFiles(path, "*")); + list.AddRange(FileSystem.GetFiles(path, filter)); var directories = FileSystem.GetDirectories(path); foreach (var directory in directories) { - list.AddRange(FindAllFiles(directory)); + list.AddRange(FindAllFiles(directory, filter)); } return list; diff --git a/src/Umbraco.Core/Persistence/Repositories/Interfaces/IStylesheetRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Interfaces/IStylesheetRepository.cs index 5c06a107dd..81bbcac98e 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Interfaces/IStylesheetRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Interfaces/IStylesheetRepository.cs @@ -1,9 +1,20 @@ +using System.Collections.Generic; using Umbraco.Core.Models; namespace Umbraco.Core.Persistence.Repositories { public interface IStylesheetRepository : IRepository { + /// + /// Gets a list of all that exist at the relative path specified. + /// + /// + /// If null or not specified, will return the stylesheets at the root path relative to the IFileSystem + /// + /// + IEnumerable GetStylesheetsAtPath(string rootPath = null); + + bool ValidateStylesheet(Stylesheet stylesheet); } } \ No newline at end of file diff --git a/src/Umbraco.Core/Persistence/Repositories/PartialViewRepository.cs b/src/Umbraco.Core/Persistence/Repositories/PartialViewRepository.cs index b98b284a1f..2fd0240701 100644 --- a/src/Umbraco.Core/Persistence/Repositories/PartialViewRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/PartialViewRepository.cs @@ -73,7 +73,7 @@ namespace Umbraco.Core.Persistence.Repositories } else { - var files = FindAllFiles(""); + var files = FindAllFiles("", "*.*"); foreach (var file in files) { yield return Get(file); diff --git a/src/Umbraco.Core/Persistence/Repositories/ScriptRepository.cs b/src/Umbraco.Core/Persistence/Repositories/ScriptRepository.cs index ca2b1b262d..b48e096e3f 100644 --- a/src/Umbraco.Core/Persistence/Repositories/ScriptRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/ScriptRepository.cs @@ -78,7 +78,7 @@ namespace Umbraco.Core.Persistence.Repositories } else { - var files = FindAllFiles(""); + var files = FindAllFiles("", "*.*"); foreach (var file in files) { yield return Get(file); diff --git a/src/Umbraco.Core/Persistence/Repositories/StylesheetRepository.cs b/src/Umbraco.Core/Persistence/Repositories/StylesheetRepository.cs index d375ce4acb..dea4083299 100644 --- a/src/Umbraco.Core/Persistence/Repositories/StylesheetRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/StylesheetRepository.cs @@ -29,7 +29,7 @@ namespace Umbraco.Core.Persistence.Repositories { if (FileSystem.FileExists(id) == false) { - throw new Exception(string.Format("The file {0} was not found", id)); + return null; } string content; @@ -50,7 +50,7 @@ namespace Umbraco.Core.Persistence.Repositories Key = path.EncodeAsGuid(), CreateDate = created, UpdateDate = updated, - Id = GetStylesheetId(path), + Id = path.GetHashCode(), VirtualPath = FileSystem.GetUrl(id) }; @@ -62,46 +62,44 @@ namespace Umbraco.Core.Persistence.Repositories } - // Fix for missing Id's on FileService.GetStylesheets() call. This is needed as sytlesheets can only bo loaded in the editor via - // their Id so listing stylesheets needs to list there Id as well for custom plugins to render the build in editor. - // http://issues.umbraco.org/issue/U4-3258 - private int GetStylesheetId(string path) - { - var sql = new Sql() - .Select("*") - .From() - .Where("nodeObjectType = @NodeObjectType AND umbracoNode.text = @Alias", - new - { - NodeObjectType = UmbracoObjectTypes.Stylesheet.GetGuid(), - Alias = path.TrimEnd(".css").Replace("\\", "/") - }); - var nodeDto = _dbwork.Database.FirstOrDefault(sql); - return nodeDto == null ? 0 : nodeDto.NodeId; - } + //// Fix for missing Id's on FileService.GetStylesheets() call. This is needed as sytlesheets can only bo loaded in the editor via + //// their Id so listing stylesheets needs to list there Id as well for custom plugins to render the build in editor. + //// http://issues.umbraco.org/issue/U4-3258 + //private int GetStylesheetId(string path) + //{ + // var sql = new Sql() + // .Select("*") + // .From() + // .Where("nodeObjectType = @NodeObjectType AND umbracoNode.text = @Alias", + // new + // { + // NodeObjectType = UmbracoObjectTypes.Stylesheet.GetGuid(), + // Alias = path.TrimEnd(".css").Replace("\\", "/") + // }); + // var nodeDto = _dbwork.Database.FirstOrDefault(sql); + // return nodeDto == null ? 0 : nodeDto.NodeId; + //} - //This should be used later to do GetAll properly without individual selections - private IEnumerable> GetStylesheetIds(string[] paths) - { - var sql = new Sql() - .Select("*") - .From() - .Where("nodeObjectType = @NodeObjectType AND umbracoNode.text in (@aliases)", - new - { - NodeObjectType = UmbracoObjectTypes.Stylesheet.GetGuid(), - aliases = paths.Select(x => x.TrimEnd(".css").Replace("\\", "/")).ToArray() - }); - var dtos = _dbwork.Database.Fetch(sql); + ////This should be used later to do GetAll properly without individual selections + //private IEnumerable> GetStylesheetIds(string[] paths) + //{ + // var sql = new Sql() + // .Select("*") + // .From() + // .Where("nodeObjectType = @NodeObjectType AND umbracoNode.text in (@aliases)", + // new + // { + // NodeObjectType = UmbracoObjectTypes.Stylesheet.GetGuid(), + // aliases = paths.Select(x => x.TrimEnd(".css").Replace("\\", "/")).ToArray() + // }); + // var dtos = _dbwork.Database.Fetch(sql); - return dtos.Select(x => new Tuple( - //the id - x.NodeId, - //the original path requested for the id - paths.First(p => p.TrimEnd(".css").Replace("\\", "/") == x.Text))); - } - - //TODO: Get rid of N+1 + // return dtos.Select(x => new Tuple( + // //the id + // x.NodeId, + // //the original path requested for the id + // paths.First(p => p.TrimEnd(".css").Replace("\\", "/") == x.Text))); + //} public override IEnumerable GetAll(params string[] ids) { @@ -117,7 +115,7 @@ namespace Umbraco.Core.Persistence.Repositories } else { - var files = FindAllFiles(""); + var files = FindAllFiles("", "*.css"); foreach (var file in files) { yield return Get(file); @@ -125,6 +123,18 @@ namespace Umbraco.Core.Persistence.Repositories } } + /// + /// Gets a list of all that exist at the relative path specified. + /// + /// + /// If null or not specified, will return the stylesheets at the root path relative to the IFileSystem + /// + /// + public IEnumerable GetStylesheetsAtPath(string rootPath = null) + { + return FileSystem.GetFiles(rootPath ?? string.Empty, "*.css").Select(Get); + } + public bool ValidateStylesheet(Stylesheet stylesheet) { var dirs = SystemDirectories.Css; @@ -157,17 +167,15 @@ namespace Umbraco.Core.Persistence.Repositories protected override void PersistDeletedItem(Stylesheet entity) { //find any stylesheet props in the db - this is legacy!! we don't really care about the db but we'll try to keep it tidy - var props = _dbwork.Database.Fetch( - new Sql().Select("cmsStylesheetProperty.*") - .From("cmsStylesheetProperty") - .InnerJoin("umbracoNode") - .On("cmsStylesheetProperty.nodeId = umbracoNode.id") - .Where("umbracoNode.parentID = @id", new { Id = entity.Id })); + var props = _dbwork.Database.Fetch( + new Sql().Select("*") + .From("umbracoNode") + .Where("umbracoNode.parentID = @id AND nodeObjectType = @NodeObjectType", new { id = entity.Id, NodeObjectType = new Guid(Constants.ObjectTypes.StylesheetProperty) })); foreach (var prop in props) { _dbwork.Database.Execute("DELETE FROM cmsStylesheetProperty WHERE nodeId = @Id", new { Id = prop.NodeId }); - _dbwork.Database.Execute("DELETE FROM umbracoNode WHERE nodeId = @Id AND nodeObjectType = @NodeObjectType", new { Id = prop.NodeId, NodeObjectType = new Guid(Constants.ObjectTypes.StylesheetProperty) }); + _dbwork.Database.Execute("DELETE FROM umbracoNode WHERE id = @Id AND nodeObjectType = @NodeObjectType", new { Id = prop.NodeId, NodeObjectType = new Guid(Constants.ObjectTypes.StylesheetProperty) }); } _dbwork.Database.Execute("DELETE FROM cmsStylesheet WHERE nodeId = @Id", new { Id = entity.Id }); _dbwork.Database.Execute("DELETE FROM umbracoNode WHERE id = @Id AND nodeObjectType = @NodeObjectType", new { Id = entity.Id, NodeObjectType = new Guid(Constants.ObjectTypes.Stylesheet) }); diff --git a/src/Umbraco.Core/Services/FileService.cs b/src/Umbraco.Core/Services/FileService.cs index 258539b4c2..438287bd56 100644 --- a/src/Umbraco.Core/Services/FileService.cs +++ b/src/Umbraco.Core/Services/FileService.cs @@ -67,6 +67,21 @@ namespace Umbraco.Core.Services } } + /// + /// Gets a list of all that exist at the relative path specified. + /// + /// + /// If null or not specified, will return the stylesheets at the root path relative to the IFileSystem + /// + /// + public IEnumerable GetStylesheetsAtPath(string rootPath = null) + { + using (var repository = _repositoryFactory.CreateStylesheetRepository(_fileUowProvider.GetUnitOfWork(), _dataUowProvider.GetUnitOfWork())) + { + return repository.GetStylesheetsAtPath(rootPath); + } + } + /// /// Gets a object by its name /// diff --git a/src/Umbraco.Core/Services/IFileService.cs b/src/Umbraco.Core/Services/IFileService.cs index 6a340109ad..83ff3e5736 100644 --- a/src/Umbraco.Core/Services/IFileService.cs +++ b/src/Umbraco.Core/Services/IFileService.cs @@ -27,6 +27,15 @@ namespace Umbraco.Core.Services /// An enumerable list of objects IEnumerable GetStylesheets(params string[] names); + /// + /// Gets a list of all that exist at the relative path specified. + /// + /// + /// If null or not specified, will return the stylesheets at the root path relative to the IFileSystem + /// + /// + IEnumerable GetStylesheetsAtPath(string rootPath = null); + /// /// Gets a object by its name /// diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index fe18f018bb..0aa2028e39 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -374,6 +374,11 @@ namespace Umbraco.Core return input.EndsWith(value.ToString(CultureInfo.InvariantCulture)) ? input : input + value; } + public static string EnsureEndsWith(this string input, string toEndWith) + { + return input.EndsWith(toEndWith.ToString(CultureInfo.InvariantCulture)) ? input : input + toEndWith; + } + public static bool IsLowerCase(this char ch) { return ch.ToString(CultureInfo.InvariantCulture) == ch.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(); diff --git a/src/Umbraco.Web.UI/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx b/src/Umbraco.Web.UI/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx index c554ab88b9..96991df575 100644 --- a/src/Umbraco.Web.UI/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx +++ b/src/Umbraco.Web.UI/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx @@ -13,6 +13,7 @@ <%=umbraco.ui.Text("name", UmbracoUser)%>: +
<%=umbraco.ui.Text("stylesheet", "nameHelp", UmbracoUser)%> diff --git a/src/Umbraco.Web.UI/umbraco_client/Editors/EditStyleSheet.js b/src/Umbraco.Web.UI/umbraco_client/Editors/EditStyleSheet.js index b67e224d7b..7d0ab93bd8 100644 --- a/src/Umbraco.Web.UI/umbraco_client/Editors/EditStyleSheet.js +++ b/src/Umbraco.Web.UI/umbraco_client/Editors/EditStyleSheet.js @@ -37,14 +37,14 @@ codeVal = UmbEditor.GetCode(); } umbraco.presentation.webservices.codeEditorSave.SaveCss( - fileName, self._opts.originalFileName, codeVal, self._opts.cssId, - function(t) { self.submitSucces(t); }, + fileName, self._opts.originalFileName, codeVal, 0, + function (t) { self.submitSucces(t, fileName); }, function(t) { self.submitFailure(t); }); }, - submitSucces: function(t) { + submitSucces: function (t, fileName) { if (t != 'true') { top.UmbSpeechBubble.ShowMessage('error', unescape(this._opts.text.cssErrorHeader), unescape(this._opts.text.cssErrorText)); } @@ -53,7 +53,7 @@ } UmbClientMgr.mainTree().setActiveTreeType('stylesheets'); - UmbClientMgr.mainTree().syncTree("-1,init," + this._opts.cssId, true); + UmbClientMgr.mainTree().syncTree("-1,init," + fileName, true); //update the originalFileName prop this._opts.originalFileName = this._opts.nameTxtBox.val(); diff --git a/src/Umbraco.Web/Editors/StylesheetController.cs b/src/Umbraco.Web/Editors/StylesheetController.cs index 85dd63c022..119d959263 100644 --- a/src/Umbraco.Web/Editors/StylesheetController.cs +++ b/src/Umbraco.Web/Editors/StylesheetController.cs @@ -27,32 +27,31 @@ namespace Umbraco.Web.Editors { public IEnumerable GetAll() { - return StyleSheet.GetAll() + return Services.FileService.GetStylesheetsAtPath() .Select(x => new Stylesheet() { - Name = x.Text, + Name = x.Alias, Id = x.Id, - Path = SystemDirectories.Css + "/" + x.Text + ".css" + Path = x.VirtualPath }); } - public IEnumerable GetRules(int id) - { - var css = StyleSheet.GetStyleSheet(id, true, true); - if (css == null) - return Enumerable.Empty(); + //public IEnumerable GetRules(string name) + //{ + // var css = Services.FileService.GetStylesheetByName(name); + // if (css == null) + // return Enumerable.Empty(); - return css.Properties.Select(x => new StylesheetRule() { Id = x.Id, Name = x.Text, Selector = x.Alias }); - } + // return css.Properties.Select(x => new StylesheetRule() { Name = x.Name, Selector = x.Alias }); + //} public IEnumerable GetRulesByName(string name) { - var css = StyleSheet.GetByName(name); - + var css = Services.FileService.GetStylesheetByName(name); if (css == null) return Enumerable.Empty(); - return css.Properties.Select(x => new StylesheetRule() { Id = x.Id, Name = x.Text, Selector = x.Alias }); + return css.Properties.Select(x => new StylesheetRule() { Name = x.Name, Selector = x.Alias }); } } diff --git a/src/Umbraco.Web/Models/ContentEditing/StylesheetRule.cs b/src/Umbraco.Web/Models/ContentEditing/StylesheetRule.cs index 6d1cb38f65..343031ba19 100644 --- a/src/Umbraco.Web/Models/ContentEditing/StylesheetRule.cs +++ b/src/Umbraco.Web/Models/ContentEditing/StylesheetRule.cs @@ -16,7 +16,7 @@ namespace Umbraco.Web.Models.ContentEditing [DataMember(Name = "selector")] public string Selector { get; set; } - [DataMember(Name = "id")] - public int Id { get; set; } + //[DataMember(Name = "id")] + //public int Id { get; set; } } } diff --git a/src/Umbraco.Web/UI/LegacyDialogHandler.cs b/src/Umbraco.Web/UI/LegacyDialogHandler.cs index 50539face7..5ae7d0c627 100644 --- a/src/Umbraco.Web/UI/LegacyDialogHandler.cs +++ b/src/Umbraco.Web/UI/LegacyDialogHandler.cs @@ -184,6 +184,26 @@ namespace Umbraco.Web.UI : ""; } + internal static string Create(HttpContextBase httpContext, User umbracoUser, string nodeType, int nodeId, string text, IDictionary additionalValues, int typeId = 0) + { + var typeInstance = GetTaskForOperation(httpContext, umbracoUser, Operation.Create, nodeType); + + typeInstance.TypeID = typeId; + typeInstance.ParentID = nodeId; + typeInstance.Alias = text; + + // check for returning url + var returnUrlTask = typeInstance as LegacyDialogTask; + + returnUrlTask.AdditionalValues = additionalValues; + + typeInstance.Save(); + + return returnUrlTask != null + ? returnUrlTask.ReturnUrl + : ""; + } + private static XmlDocument GetXmlDoc() { // Load task settings diff --git a/src/Umbraco.Web/UI/LegacyDialogTask.cs b/src/Umbraco.Web/UI/LegacyDialogTask.cs index 537141e30a..1975021121 100644 --- a/src/Umbraco.Web/UI/LegacyDialogTask.cs +++ b/src/Umbraco.Web/UI/LegacyDialogTask.cs @@ -89,5 +89,7 @@ namespace Umbraco.Web.UI public abstract string ReturnUrl { get; } public abstract string AssignedApp { get; } + + public IDictionary AdditionalValues { get; set; } } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheetProperty.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheetProperty.cs index 5cd98c696a..b06487b11b 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheetProperty.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheetProperty.cs @@ -39,27 +39,27 @@ namespace umbraco rootNode.NodeType = "init" + TreeAlias; rootNode.NodeID = "init"; } - + public override void RenderJS(ref StringBuilder Javascript) { Javascript.Append( @" function openStylesheetProperty(name, prop) { - UmbClientMgr.contentFrame('settings/stylesheet/property/editStylesheetProperty.aspx?name=' + name + '&prop=' + prop); + UmbClientMgr.contentFrame('settings/stylesheet/property/editStylesheetProperty.aspx?id=' + name + '&prop=' + prop); } "); } public override void Render(ref XmlTree tree) { - StyleSheet sn = new StyleSheet(m_id); + var sheet = Services.FileService.GetStylesheetByName(NodeKey.EnsureEndsWith(".css")); - foreach (StylesheetProperty n in sn.Properties) + foreach (var prop in sheet.Properties) { - XmlTreeNode xNode = XmlTreeNode.Create(this); - xNode.NodeID = sn.Text + "_" + n.Text; //n.Id.ToString(CultureInfo.InvariantCulture); - xNode.Text = n.Text; - xNode.Action = "javascript:openStylesheetProperty('" + sn.Text + "','" + n.Text + "');"; + var xNode = XmlTreeNode.Create(this); + xNode.NodeID = sheet.Alias + "_" + prop.Name; + xNode.Text = prop.Name; + xNode.Action = "javascript:openStylesheetProperty('" + sheet.Name + "','" + prop.Name + "');"; xNode.Icon = "icon-brackets"; xNode.OpenIcon = "icon-brackets"; diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheets.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheets.cs index 8fce62acd2..d51c8ddc95 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheets.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadStylesheets.cs @@ -47,8 +47,8 @@ namespace umbraco { Javascript.Append( @" - function openStylesheet(id) { - UmbClientMgr.contentFrame('settings/stylesheet/editStylesheet.aspx?id=' + id); + function openStylesheet(name) { + UmbClientMgr.contentFrame('settings/stylesheet/editStylesheet.aspx?id=' + name); } "); } @@ -62,15 +62,15 @@ namespace umbraco public override void Render(ref XmlTree tree) { - foreach (StyleSheet n in StyleSheet.GetAll().Where(x => x.Id > 0)) + foreach (var sheet in Services.FileService.GetStylesheetsAtPath()) { - XmlTreeNode xNode = XmlTreeNode.Create(this); - xNode.NodeID = n.Text; //n.Id.ToString(CultureInfo.InvariantCulture); - xNode.Text = n.Text; - xNode.Action = "javascript:openStylesheet(" + n.Id + ");"; - loadStylesheetProperty styleSheetPropertyTree = new loadStylesheetProperty(this.app); - xNode.Source = styleSheetPropertyTree.GetTreeServiceUrl(n.Id); - xNode.HasChildren = n.HasChildren; + var xNode = XmlTreeNode.Create(this); + xNode.NodeID = sheet.Alias; + xNode.Text = sheet.Alias; + xNode.Action = "javascript:openStylesheet('" + sheet.Name + "');"; + var styleSheetPropertyTree = new loadStylesheetProperty(this.app); + xNode.Source = styleSheetPropertyTree.GetTreeServiceUrl(sheet.Alias); + xNode.HasChildren = sheet.Properties.Any(); xNode.Icon = " icon-brackets"; xNode.OpenIcon = "icon-brackets"; xNode.NodeType = "stylesheet"; //this shouldn't be like this, it should be this.TreeAlias but the ui.config file points to this name. diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs index 5d7be690e8..548146b74a 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/StylesheetTasks.cs @@ -16,17 +16,14 @@ namespace umbraco { int id = -1; - var checkingSheet = cms.businesslogic.web.StyleSheet.GetByName(Alias); - id = checkingSheet != null - ? checkingSheet.Id - : cms.businesslogic.web.StyleSheet.MakeNew(User, Alias, "", "").Id; - _returnUrl = string.Format("settings/stylesheet/editStylesheet.aspx?id={0}", id); + var checkingSheet = cms.businesslogic.web.StyleSheet.GetByName(Alias) ?? cms.businesslogic.web.StyleSheet.MakeNew(User, Alias, "", ""); + _returnUrl = string.Format("settings/stylesheet/editStylesheet.aspx?id={0}", checkingSheet.Text); return true; } public override bool PerformDelete() { - var s = new cms.businesslogic.web.StyleSheet(ParentID); + var s = cms.businesslogic.web.StyleSheet.GetByName(Alias); s.delete(); return true; } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/simple.ascx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/simple.ascx.cs index dd09363c34..06606d7b19 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/simple.ascx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/simple.ascx.cs @@ -1,5 +1,7 @@ using System.Web; using System.Web.UI; +using ClientDependency.Core; +using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Web.UI; using Umbraco.Web; @@ -9,6 +11,7 @@ using System.Web.UI.WebControls; using umbraco.BasePages; using umbraco.BusinessLogic; using Umbraco.Web; +using System.Linq; using UmbracoUserControl = Umbraco.Web.UI.Controls.UmbracoUserControl; namespace umbraco.cms.presentation.create.controls @@ -16,7 +19,7 @@ namespace umbraco.cms.presentation.create.controls /// /// Summary description for simple. /// - public partial class simple : UmbracoUserControl + public partial class simple : UmbracoUserControl { protected void Page_Load(object sender, EventArgs e) @@ -35,19 +38,20 @@ namespace umbraco.cms.presentation.create.controls if (int.TryParse(Request.QueryString["nodeId"], out nodeId) == false) nodeId = -1; - try + try { - var returnUrl = LegacyDialogHandler.Create( - new HttpContextWrapper(Context), - new User(Security.CurrentUser), - Request.GetItemAsString("nodeType"), - nodeId, - rename.Text.Trim()); + var returnUrl = LegacyDialogHandler.Create( + new HttpContextWrapper(Context), + new User(Security.CurrentUser), + Request.GetItemAsString("nodeType"), + nodeId, + rename.Text.Trim(), + Request.QueryString.AsEnumerable().ToDictionary(x => x.Key, x => (object)x.Value)); BasePage.Current.ClientTools .ChangeContentFrameUrl(returnUrl) - .ReloadActionNode(false, true) + .ReloadActionNode(false, true) .CloseModalWindow(); } catch (Exception ex) diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs index d49c5c835f..c1a05e7237 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/stylesheetPropertyTasks.cs @@ -3,6 +3,8 @@ using System.Data; using System.Linq; using System.Web.Security; using System.Windows.Forms; +using Umbraco.Core; +using Umbraco.Core.Models; using Umbraco.Web.UI; using umbraco.BusinessLogic; using umbraco.DataLayer; @@ -17,9 +19,13 @@ namespace umbraco public override bool PerformSave() { - var s = new cms.businesslogic.web.StyleSheet(ParentID); - var prop = s.AddProperty(Alias, User); - _returnUrl = string.Format("settings/stylesheet/property/EditStyleSheetProperty.aspx?name={0}&prop={1}", s.Text, prop.Text); + var stylesheetName = AdditionalValues["nodeId"].ToString(); + + var s = Umbraco.Core.ApplicationContext.Current.Services.FileService.GetStylesheetByName(stylesheetName.EnsureEndsWith(".css")); + s.AddProperty(new StylesheetProperty(Alias, "#" + Alias, "")); + Umbraco.Core.ApplicationContext.Current.Services.FileService.SaveStylesheet(s); + + _returnUrl = string.Format("settings/stylesheet/property/EditStyleSheetProperty.aspx?id={0}&prop={1}", s.Name, Alias); return true; } @@ -27,7 +33,7 @@ namespace umbraco { var parts = Alias.Split('_'); - var stylesheet = Umbraco.Core.ApplicationContext.Current.Services.FileService.GetStylesheetByName(parts[0] + ".css"); + var stylesheet = Umbraco.Core.ApplicationContext.Current.Services.FileService.GetStylesheetByName(parts[0].EnsureEndsWith(".css")); if (stylesheet == null) throw new InvalidOperationException("No stylesheet found by name: " + parts[0]); var prop = stylesheet.Properties.FirstOrDefault(x => x.Name == parts[1]); @@ -41,7 +47,7 @@ namespace umbraco } private string _returnUrl = ""; - + public override string ReturnUrl { get { return _returnUrl; } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/editstylesheet.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/editstylesheet.aspx.cs index ee93141972..7aa51f9af0 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/editstylesheet.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/editstylesheet.aspx.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Web.UI; using Umbraco.Core.IO; using Umbraco.Web; @@ -7,6 +8,7 @@ using umbraco.BusinessLogic; using umbraco.cms.businesslogic.web; using umbraco.cms.presentation.Trees; using umbraco.uicontrols; +using Umbraco.Core; namespace umbraco.cms.presentation.settings.stylesheet { @@ -15,7 +17,7 @@ namespace umbraco.cms.presentation.settings.stylesheet /// public partial class editstylesheet : UmbracoEnsuredPage { - private StyleSheet stylesheet; + private Umbraco.Core.Models.Stylesheet _sheet; protected MenuButton SaveButton; @@ -50,22 +52,24 @@ namespace umbraco.cms.presentation.settings.stylesheet pp_name.Text = ui.Text("name", UmbracoUser); pp_path.Text = ui.Text("path", UmbracoUser); - stylesheet = new StyleSheet(int.Parse(Request.QueryString["id"])); + _sheet = Services.FileService.GetStylesheetByName(Request.QueryString["id"]); + if (_sheet == null) throw new InvalidOperationException("No stylesheet found with name: " + Request.QueryString["id"]); + var appPath = Request.ApplicationPath; if (appPath == "/") appPath = ""; - lttPath.Text = "" + appPath + - SystemDirectories.Css + "/" + stylesheet.Text + ".css"; + lttPath.Text = "" + appPath + + SystemDirectories.Css + "/" + _sheet.Name + ""; if (IsPostBack == false) { - NameTxt.Text = stylesheet.Text; - editorSource.Text = stylesheet.Content; + NameTxt.Text = _sheet.Alias; + editorSource.Text = _sheet.Content; ClientTools - .SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree().Tree.Alias) - .SyncTree("-1,init," + stylesheet.Text, false); + .SetActiveTreeType(Constants.Trees.Stylesheets) + .SyncTree("-1,init," + _sheet.Alias, false); } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx.cs index 901abdb5da..06bbec6030 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/settings/stylesheet/property/EditStyleSheetProperty.aspx.cs @@ -14,6 +14,7 @@ using umbraco.cms.businesslogic.web; using Umbraco.Core; using Umbraco.Web; using umbraco.cms.presentation.Trees; +using Umbraco.Core; namespace umbraco.cms.presentation.settings.stylesheet { @@ -28,87 +29,73 @@ namespace umbraco.cms.presentation.settings.stylesheet } - private businesslogic.web.StylesheetProperty _stylesheetproperty; - private DropDownList _ddl = new DropDownList(); + private Umbraco.Core.Models.StylesheetProperty _stylesheetproperty; + private Umbraco.Core.Models.Stylesheet _sheet; - protected void Page_Load(object sender, EventArgs e) + /// + /// Raises the event. + /// + /// The object that contains the event data. + protected override void OnLoad(EventArgs e) { - //NOTE: Check for id for legacy reasons - if (Request.QueryString.ContainsKey("id")) - { - int propId; - if (int.TryParse(Request.QueryString["id"], out propId)) - { - _stylesheetproperty = new businesslogic.web.StylesheetProperty(propId); - } - } - else - { - var byName = Services.FileService.GetStylesheetByName(Request.QueryString["name"] + ".css"); - if (byName == null) throw new InvalidOperationException("No stylesheet found with name: " + Request.QueryString["name"]); - var prop = byName.Properties.FirstOrDefault(x => x.Name == Request.QueryString["prop"]); - if (prop == null) throw new InvalidOperationException("No stylesheet property found with name: " + Request.QueryString["prop"]); - _stylesheetproperty = new StylesheetProperty(byName, prop); - } + base.OnLoad(e); + + _sheet = Services.FileService.GetStylesheetByName(Request.QueryString["id"]); + if (_sheet == null) throw new InvalidOperationException("No stylesheet found with name: " + Request.QueryString["id"]); + + var propName = IsPostBack ? OriginalName.Value : Request.QueryString["prop"]; + + _stylesheetproperty = _sheet.Properties.FirstOrDefault(x => x.Name == propName); + if (_stylesheetproperty == null) throw new InvalidOperationException("No stylesheet property found with name: " + Request.QueryString["prop"]); Panel1.Text = ui.Text("stylesheet", "editstylesheetproperty", UmbracoUser); - var nodePath = string.Format("-1,init,{0},{0}_{1}", _stylesheetproperty.StylesheetItem.Alias, _stylesheetproperty.StylesheetProp.Name); - - if (IsPostBack == false) - { - _stylesheetproperty.RefreshFromFile(); - NameTxt.Text = _stylesheetproperty.Text; - Content.Text = _stylesheetproperty.value; - AliasTxt.Text = _stylesheetproperty.Alias; - - ClientTools - .SetActiveTreeType(Constants.Trees.Stylesheets) - .SyncTree(nodePath, false); - } - else - { - //true = force reload from server on post back - ClientTools - .SetActiveTreeType(Constants.Trees.Stylesheets) - .SyncTree(nodePath, true); - } - - - var bt = Panel1.Menu.NewButton(); bt.Click += SaveClick; bt.Text = ui.Text("save"); bt.ToolTip = ui.Text("save"); bt.ButtonType = uicontrols.MenuButtonType.Primary; bt.ID = "save"; - SetupPreView(); } + protected override void OnPreRender(EventArgs e) { - prStyles.Attributes["style"] = _stylesheetproperty.value; + NameTxt.Text = _stylesheetproperty.Name; + Content.Text = _stylesheetproperty.Value; + AliasTxt.Text = _stylesheetproperty.Alias; + OriginalName.Value = _stylesheetproperty.Name; + + prStyles.Attributes["style"] = _stylesheetproperty.Value; + + var nodePath = string.Format("-1,init,{0},{0}_{1}", _sheet.Alias, _stylesheetproperty.Name); + + ClientTools + .SetActiveTreeType(Constants.Trees.Stylesheets) + .SyncTree(nodePath, IsPostBack); + + prStyles.Attributes["style"] = _stylesheetproperty.Value; base.OnPreRender(e); } - private void SetupPreView() - { - prStyles.Attributes["style"] = _stylesheetproperty.value; - } - private void SaveClick(object sender, EventArgs e) { - _stylesheetproperty.value = Content.Text; - _stylesheetproperty.Text = NameTxt.Text; + _stylesheetproperty.Value = Content.Text; _stylesheetproperty.Alias = AliasTxt.Text; - //_stylesheetproperty.StyleSheet().saveCssToFile(); + if (_stylesheetproperty.Name != NameTxt.Text) + { + //to change the name we actually have to remove the property and re-add it as a different one + _sheet.AddProperty(new Umbraco.Core.Models.StylesheetProperty(NameTxt.Text, _stylesheetproperty.Alias, _stylesheetproperty.Value)); + _sheet.RemoveProperty(_stylesheetproperty.Name); + //reset our variable + _stylesheetproperty = _sheet.Properties.Single(x => x.Name == NameTxt.Text); + } + + Services.FileService.SaveStylesheet(_sheet); ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editStylesheetPropertySaved", UmbracoUser), ""); - SetupPreView(); - - _stylesheetproperty.Save(); } @@ -139,6 +126,8 @@ namespace umbraco.cms.presentation.settings.stylesheet /// protected global::umbraco.uicontrols.Pane Pane7; + protected global::System.Web.UI.WebControls.HiddenField OriginalName; + /// /// NameTxt control. /// diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx.cs index a375aba8f5..08217ad106 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/webservices/codeEditorSave.asmx.cs @@ -11,6 +11,7 @@ using System.Web.Services; using System.Web.UI; using System.Xml; using System.Xml.Xsl; +using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Web.WebServices; @@ -39,35 +40,19 @@ namespace umbraco.presentation.webservices { if (AuthorizeRequest(DefaultApps.settings.ToString())) { - string returnValue; - var stylesheet = new StyleSheet(fileID) - { - Content = fileContents, - Text = fileName - }; + var stylesheet = Services.FileService.GetStylesheetByName(oldName.EnsureEndsWith(".css")); + if (stylesheet == null) throw new InvalidOperationException("No stylesheet found with name " + oldName); - try + stylesheet.Content = fileContents; + if (fileName.InvariantEquals(oldName) == false) { - stylesheet.saveCssToFile(); - stylesheet.Save(); - returnValue = "true"; - - - //deletes the old css file if the name was changed... - if (fileName.ToLowerInvariant() != oldName.ToLowerInvariant()) - { - var p = IOHelper.MapPath(SystemDirectories.Css + "/" + oldName + ".css"); - if (File.Exists(p)) - File.Delete(p); - } - - } - catch (Exception ex) - { - return ex.ToString(); + //it's changed which means we need to change the path + stylesheet.Path = stylesheet.Path.TrimEnd(oldName.EnsureEndsWith(".css")) + fileName.EnsureEndsWith(".css"); } - return returnValue; + Services.FileService.SaveStylesheet(stylesheet, Security.CurrentUser.Id); + + return "true"; } return "false"; } diff --git a/src/umbraco.cms/businesslogic/Packager/Installer.cs b/src/umbraco.cms/businesslogic/Packager/Installer.cs index 09e2dc28a5..552a9e62e4 100644 --- a/src/umbraco.cms/businesslogic/Packager/Installer.cs +++ b/src/umbraco.cms/businesslogic/Packager/Installer.cs @@ -242,6 +242,9 @@ namespace umbraco.cms.businesslogic.packager //retrieve the manifest to continue installation var insPack = InstalledPackage.GetById(packageId); + //TODO: Depending on some files, some files should be installed differently. + //i.e. if stylsheets should probably be installed via business logic, media items should probably use the media IFileSystem! + // Move files //string virtualBasePath = System.Web.HttpContext.Current.Request.ApplicationPath; string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; diff --git a/src/umbraco.cms/businesslogic/web/StyleSheet.cs b/src/umbraco.cms/businesslogic/web/StyleSheet.cs index f0fe09a566..9146fa5a54 100644 --- a/src/umbraco.cms/businesslogic/web/StyleSheet.cs +++ b/src/umbraco.cms/businesslogic/web/StyleSheet.cs @@ -50,34 +50,12 @@ namespace umbraco.cms.businesslogic.web public string Content { get { return StylesheetItem.Content; } - set - { - StylesheetItem.Content = value; - //_content = value; - //SqlHelper.ExecuteNonQuery("update cmsStylesheet set content = @content where nodeId = @id", SqlHelper.CreateParameter("@content", this.Content), SqlHelper.CreateParameter("@id", this.Id)); - //InvalidateCache(); - } + set { StylesheetItem.Content = value; } } public StylesheetProperty[] Properties { - get - { - //if (_properties == null) - //{ - // var tmp = this.ChildrenOfAllObjectTypes; - // var retVal = new StylesheetProperty[tmp.Length]; - // for (var i = 0; i < tmp.Length; i++) - // { - // //So this will go get cached properties but yet the above call to ChildrenOfAllObjectTypes is not cached :/ - // retVal[i] = StylesheetProperty.GetStyleSheetProperty(tmp[i].Id); - // } - // _properties = retVal; - //} - //return _properties; - - return StylesheetItem.Properties.Select(x => new StylesheetProperty(StylesheetItem, x)).ToArray(); - } + get { return StylesheetItem.Properties.Select(x => new StylesheetProperty(StylesheetItem, x)).ToArray(); } } //static bool isInitialized = false; @@ -92,20 +70,17 @@ namespace umbraco.cms.businesslogic.web public StyleSheet(Guid id) : base(id) { - //SetupStyleSheet(true, true); } public StyleSheet(int id) : base(id) { - //SetupStyleSheet(true, true); } [Obsolete("This constructors parameters: setupStyleProperties, loadContentFromFile don't do anything")] public StyleSheet(int id, bool setupStyleProperties, bool loadContentFromFile) : base(id) { - //SetupStyleSheet(loadContentFromFile, setupStyleProperties); } /// @@ -121,7 +96,7 @@ namespace umbraco.cms.businesslogic.web /// /// Sort order does nothing for Stylesheets /// - [Obsolete("Sort order does nothing for Stylesheets")] + [Obsolete("Level does nothing for Stylesheets")] public override int Level { get { return 1; } @@ -176,94 +151,23 @@ namespace umbraco.cms.businesslogic.web "SELECT TOP 1 filename FROM cmsStylesheet WHERE nodeid=" + Id); if (found.IsNullOrWhiteSpace()) throw new ArgumentException(string.Format("No stylesheet exists with id '{0}'", Id)); - StylesheetItem = ApplicationContext.Current.Services.FileService.GetStylesheetByName(found + ".css"); + StylesheetItem = ApplicationContext.Current.Services.FileService.GetStylesheetByName(found.EnsureEndsWith(".css")); if (StylesheetItem == null) throw new ArgumentException(string.Format("No stylesheet exists with name '{0}.css'", found)); } - //private void SetupStyleSheet(bool loadFileData, bool updateStyleProperties) - //{ - // // Get stylesheet data - // using (var dr = SqlHelper.ExecuteReader("select filename, content from cmsStylesheet where nodeid = " + Id)) - // { - // if (dr.Read()) - // { - // if (!dr.IsNull("filename")) - // _filename = dr.GetString("filename"); - // // Get Content from db or file - // if (!loadFileData) - // { - // if (!dr.IsNull("content")) - // _content = dr.GetString("content"); - // } - // else if (File.Exists(IOHelper.MapPath(String.Format("{0}/{1}.css", SystemDirectories.Css, this.Text)))) - // { - // var propertiesContent = String.Empty; - - // using (var re = File.OpenText(IOHelper.MapPath(String.Format("{0}/{1}.css", SystemDirectories.Css, this.Text)))) - // { - // string input = null; - // _content = string.Empty; - // // NH: Updates the reader to support properties - // var readingProperties = false; - - // while ((input = re.ReadLine()) != null && true) - // { - // if (input.Contains("EDITOR PROPERTIES")) - // { - // readingProperties = true; - // } - // else - // if (readingProperties) - // { - // propertiesContent += input.Replace("\n", "") + "\n"; - // } - // else - // { - // _content += input.Replace("\n", "") + "\n"; - // } - // } - // } - - // // update properties - // if (updateStyleProperties) - // { - // if (propertiesContent != String.Empty) - // { - // ParseProperties(propertiesContent); - // } - // } - // } - // } - // } - //} - - //private void ParseProperties(string propertiesContent) - //{ - // var m = Regex.Matches(propertiesContent, "([^{]*){([^}]*)}", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - - // foreach (Match match in m) - // { - // var groups = match.Groups; - // var cssClass = groups[1].Value.Replace("\n", "").Replace("\r", "").Trim().Trim(Environment.NewLine.ToCharArray()); - // var cssCode = groups[2].Value.Trim(Environment.NewLine.ToCharArray()); - // foreach (StylesheetProperty sp in this.Properties) - // if (sp.Alias == cssClass && sp.value != cssCode) // check before setting to avoid invalidating cache unecessarily - // sp.value = cssCode; - // } - //} - + public static StyleSheet MakeNew(BusinessLogic.User user, string Text, string FileName, string Content) { if (FileName.IsNullOrWhiteSpace()) { - FileName = Text; + FileName = Text.EnsureEndsWith(".css"); } // validate if node ends with css, if it does we'll remove it as we append it later if (Text.ToLowerInvariant().EndsWith(".css")) { - Text = Text.Substring(0, Text.Length - 4); + Text = Text.TrimEnd(".css"); } var newSheet = new Stylesheet(FileName) @@ -272,12 +176,6 @@ namespace umbraco.cms.businesslogic.web }; ApplicationContext.Current.Services.FileService.SaveStylesheet(newSheet); - //// Create the umbraco node - //var newNode = CMSNode.MakeNew(-1, ModuleObjectType, user.Id, 1, Text, Guid.NewGuid()); - - //// Create the stylesheet data - //SqlHelper.ExecuteNonQuery(string.Format("insert into cmsStylesheet (nodeId, filename, content) values ('{0}','{1}',@content)", newNode.Id, FileName), SqlHelper.CreateParameter("@content", Content)); - var newCss = new StyleSheet(newSheet); var e = new NewEventArgs(); newCss.OnNew(e); @@ -288,54 +186,12 @@ namespace umbraco.cms.businesslogic.web public static StyleSheet[] GetAll() { var retval = ApplicationContext.Current.Services.FileService.GetStylesheets() + //Legacy would appear to have only ever loaded the stylesheets at the root level (no sub folders) + .Where(x => x.Path.Split(new char[]{'\\'}, StringSplitOptions.RemoveEmptyEntries).Count() == 1) .OrderBy(x => x.Alias) .Select(x => new StyleSheet(x)) .ToArray(); - //var dbStylesheets = new ArrayList(); - - //var topNodeIds = CMSNode.TopMostNodeIds(ModuleObjectType); - ////StyleSheet[] retval = new StyleSheet[topNodeIds.Length]; - //for (int i = 0; i < topNodeIds.Length; i++) - //{ - // //retval[i] = new StyleSheet(topNodeIds[i]); - // dbStylesheets.Add(new StyleSheet(topNodeIds[i]).Text.ToLower()); - //} - - //var fileStylesheets = new ArrayList(); - //var fileListing = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Css + "/")); - - //foreach (var file in fileListing.GetFiles("*.css")) - //{ - // if (!dbStylesheets.Contains(file.Name.Replace(file.Extension, "").ToLower())) - // { - // fileStylesheets.Add(file.Name.Replace(file.Extension, "")); - // } - //} - - //var retval = new StyleSheet[dbStylesheets.Count + fileStylesheets.Count]; - //for (int i = 0; i < topNodeIds.Length; i++) - //{ - // retval[i] = new StyleSheet(topNodeIds[i]); - - //} - - //for (int i = 0; i < fileStylesheets.Count; i++) - //{ - - // string content = string.Empty; - - // using (StreamReader re = File.OpenText(IOHelper.MapPath(string.Format("{0}/{1}.css", SystemDirectories.Css, fileStylesheets[i])))) - // { - // content = re.ReadToEnd(); - // } - - // retval[dbStylesheets.Count + i] = StyleSheet.MakeNew(new umbraco.BusinessLogic.User(0), fileStylesheets[i].ToString(), fileStylesheets[i].ToString(), content); - //} - - - //Array.Sort(retval, 0, retval.Length, new StyleSheetComparer()); - return retval; } @@ -353,14 +209,6 @@ namespace umbraco.cms.businesslogic.web { ApplicationContext.Current.Services.FileService.DeleteStylesheet(StylesheetItem.Path); - //File.Delete(IOHelper.MapPath(String.Format("{0}/{1}.css", SystemDirectories.Css, this.Text))); - //foreach (var p in Properties.Where(p => p != null)) - //{ - // p.delete(); - //} - //SqlHelper.ExecuteNonQuery("delete from cmsStylesheet where nodeId = @nodeId", SqlHelper.CreateParameter("@nodeId", this.Id)); - //base.delete(); - FireAfterDelete(e); } @@ -369,24 +217,6 @@ namespace umbraco.cms.businesslogic.web public void saveCssToFile() { ApplicationContext.Current.Services.FileService.SaveStylesheet(StylesheetItem); - - //if (this.Text.Contains('/')) - //{ - // var dir = string.Format("{0}/{1}", IOHelper.MapPath(SystemDirectories.Css), this.Text.Substring(0, this.Text.LastIndexOf('/'))); - // if (!Directory.Exists(dir)) - // Directory.CreateDirectory(dir); - //} - - //using (StreamWriter SW = File.CreateText(IOHelper.MapPath(string.Format("{0}/{1}.css", SystemDirectories.Css, this.Text)))) - //{ - // string tmpCss = this.Content ; - // tmpCss += "/* EDITOR PROPERTIES - PLEASE DON'T DELETE THIS LINE TO AVOID DUPLICATE PROPERTIES */\n"; - // foreach (StylesheetProperty p in this.Properties) - // { - // tmpCss += p + "\n"; - // } - // SW.Write(tmpCss); - //} } public XmlNode ToXml(XmlDocument xd) @@ -424,19 +254,6 @@ namespace umbraco.cms.businesslogic.web return new StyleSheet(s); - //return ApplicationContext.Current.ApplicationCache.GetCacheItem( - // GetCacheKey(id), - // TimeSpan.FromMinutes(30), () => - // { - // try - // { - // return new StyleSheet(id, setupStyleProperties, loadContentFromFile); - // } - // catch - // { - // return null; - // } - // }); } [Obsolete("Stylesheet cache is automatically invalidated by Umbraco when a stylesheet is saved or deleted")] @@ -444,14 +261,9 @@ namespace umbraco.cms.businesslogic.web { } - //private static string GetCacheKey(int id) - //{ - // return CacheKeys.StylesheetCacheKey + id; - //} - public static StyleSheet GetByName(string name) { - var found = ApplicationContext.Current.Services.FileService.GetStylesheetByName(name.EndsWith(".css") ? name : name + ".css"); + var found = ApplicationContext.Current.Services.FileService.GetStylesheetByName(name.EnsureEndsWith(".css")); if (found == null) return null; return new StyleSheet(found); } @@ -474,7 +286,7 @@ namespace umbraco.cms.businesslogic.web string alias = xmlHelper.GetNodeValue(prop.SelectSingleNode("Alias")); var sp = s.Properties.SingleOrDefault(p => p != null && p.Alias == alias); string name = xmlHelper.GetNodeValue(prop.SelectSingleNode("Name")); - if (sp == default(StylesheetProperty)) + if (sp == null) { sp = StylesheetProperty.MakeNew( name, diff --git a/src/umbraco.cms/businesslogic/web/StylesheetProperty.cs b/src/umbraco.cms/businesslogic/web/StylesheetProperty.cs index 4481570ebf..5541dfdaa6 100644 --- a/src/umbraco.cms/businesslogic/web/StylesheetProperty.cs +++ b/src/umbraco.cms/businesslogic/web/StylesheetProperty.cs @@ -26,12 +26,10 @@ namespace umbraco.cms.businesslogic.web public StylesheetProperty(int id) : base(id) { - //InitProperty(); } public StylesheetProperty(Guid id) : base(id) { - //InitProperty(); } /// @@ -44,31 +42,18 @@ namespace umbraco.cms.businesslogic.web if (foundProp == null) throw new ArgumentException(string.Format("No stylesheet property exists with an id '{0}'", Id)); - var found = ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar( - "WHERE nodeId = @id", new {id = foundProp.parentID}); + var found = ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar( + "SELECT filename FROM cmsStylesheet WHERE nodeId = @id", new { id = foundProp.parentID }); if (found == null) throw new ArgumentException(string.Format("No stylesheet exists with a property with id '{0}'", Id)); - StylesheetItem = ApplicationContext.Current.Services.FileService.GetStylesheetByName(found + ".css"); + StylesheetItem = ApplicationContext.Current.Services.FileService.GetStylesheetByName(found.EnsureEndsWith(".css")); if (StylesheetItem == null) throw new ArgumentException(string.Format("No stylesheet exists with name '{0}.css'", found)); StylesheetProp = StylesheetItem.Properties.FirstOrDefault(x => x.Alias == foundProp.stylesheetPropertyAlias); if (StylesheetProp == null) throw new ArgumentException(string.Format("No stylesheet property exists with alias {0}", foundProp.stylesheetPropertyAlias)); } - //private void InitProperty() - //{ - // var dr = SqlHelper.ExecuteReader("Select stylesheetPropertyAlias,stylesheetPropertyValue from cmsStylesheetProperty where nodeId = " + this.Id); - // if (dr.Read()) - // { - // _alias = dr.GetString("stylesheetPropertyAlias"); - // _value = dr.GetString("stylesheetPropertyValue"); - // } - // else - // throw new ArgumentException("NO DATA EXSISTS"); - // dr.Close(); - //} - public StyleSheet StyleSheet() { return new StyleSheet(StylesheetItem); @@ -81,10 +66,6 @@ namespace umbraco.cms.businesslogic.web if (StylesheetItem == null) throw new ArgumentException(string.Format("No stylesheet exists with name '{0}'", name)); StylesheetProp = StylesheetItem.Properties.FirstOrDefault(x => x.Alias == StylesheetProp.Alias); - - // ping the stylesheet - //var ss = new StyleSheet(this.Parent.Id); - //InitProperty(); } /// @@ -109,36 +90,14 @@ namespace umbraco.cms.businesslogic.web public string Alias { - get - { - return StylesheetProp.Alias; - //return _alias; - } - set - { - StylesheetProp.Alias = value; - //SqlHelper.ExecuteNonQuery(String.Format("update cmsStylesheetProperty set stylesheetPropertyAlias = '{0}' where nodeId = {1}", value.Replace("'", "''"), this.Id)); - //_alias=value; - - //InvalidateCache(); - } + get { return StylesheetProp.Alias; } + set { StylesheetProp.Alias = value; } } public string value { - get - { - return StylesheetProp.Value; - //return _value; - } - set - { - StylesheetProp.Value = value; - //SqlHelper.ExecuteNonQuery(String.Format("update cmsStylesheetProperty set stylesheetPropertyValue = '{0}' where nodeId = {1}", value.Replace("'", "''"), this.Id)); - //_value = value; - - //InvalidateCache(); - } + get { return StylesheetProp.Value; } + set { StylesheetProp.Value = value; } } public static StylesheetProperty MakeNew(string Text, StyleSheet sheet, BusinessLogic.User user) @@ -204,7 +163,7 @@ namespace umbraco.cms.businesslogic.web if (found == null) return null; - var stylesheetItem = ApplicationContext.Current.Services.FileService.GetStylesheetByName(found + ".css"); + var stylesheetItem = ApplicationContext.Current.Services.FileService.GetStylesheetByName(found.EnsureEndsWith(".css")); if (stylesheetItem == null) return null; var stylesheetProp = stylesheetItem.Properties.FirstOrDefault(x => x.Alias == foundProp.stylesheetPropertyAlias); @@ -213,17 +172,6 @@ namespace umbraco.cms.businesslogic.web return new StylesheetProperty(stylesheetItem, stylesheetProp); } - //[Obsolete("Umbraco automatically refreshes the cache when stylesheets and stylesheet properties are saved or deleted")] - //private void InvalidateCache() - //{ - // ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id)); - //} - - //private static string GetCacheKey(int id) - //{ - // return CacheKeys.StylesheetPropertyCacheKey + id; - //} - // EVENTS /// /// The save event handler diff --git a/src/umbraco.editorControls/tinyMCE3/TinyMCE.cs b/src/umbraco.editorControls/tinyMCE3/TinyMCE.cs index f6ec580a3d..f8de39e536 100644 --- a/src/umbraco.editorControls/tinyMCE3/TinyMCE.cs +++ b/src/umbraco.editorControls/tinyMCE3/TinyMCE.cs @@ -153,6 +153,8 @@ namespace umbraco.editorControls.tinyMCE3 if (styleSheetId.Trim() != "") try { + + //TODO: Fix this, it will no longer work! var s = StyleSheet.GetStyleSheet(int.Parse(styleSheetId), false, false); if (s.nodeObjectType == StyleSheet.ModuleObjectType)