diff --git a/.gitignore b/.gitignore index 52035ca55..5e7dd7079 100644 --- a/.gitignore +++ b/.gitignore @@ -186,3 +186,5 @@ BlogEngine/.vs/ # Default extensions data BlogEngine/BlogEngine.NET/App_Data/datastore/extensions/*.xml +/.vs/slnx.sqlite +/.vs/BlogEngine.NET/config/applicationhost.config diff --git a/BlogEngine/BlogEngine.Core/API/MetaWeblog/MetaWeblogHandler.cs b/BlogEngine/BlogEngine.Core/API/MetaWeblog/MetaWeblogHandler.cs index 1352df106..d5851e32a 100644 --- a/BlogEngine/BlogEngine.Core/API/MetaWeblog/MetaWeblogHandler.cs +++ b/BlogEngine/BlogEngine.Core/API/MetaWeblog/MetaWeblogHandler.cs @@ -177,7 +177,7 @@ internal bool DeletePage(string blogId, string pageId, string userName, string p } catch (Exception ex) { - throw new MetaWeblogException("15", string.Format("DeletePage failed. Error: {0}", ex.Message)); + throw new MetaWeblogException("15", $"DeletePage failed. Error: {ex.Message}"); } return true; @@ -220,7 +220,7 @@ internal bool DeletePost(string appKey, string postId, string userName, string p } catch (Exception ex) { - throw new MetaWeblogException("12", string.Format("DeletePost failed. Error: {0}", ex.Message)); + throw new MetaWeblogException("12", $"DeletePost failed. Error: {ex.Message}"); } return true; @@ -712,7 +712,7 @@ internal MWAMediaInfo NewMediaObject( var mediaInfo = new MWAMediaInfo(); - var rootPath = string.Format("{0}files/", Blog.CurrentInstance.StorageLocation); + var rootPath = $"{Blog.CurrentInstance.StorageLocation}files/"; var serverPath = request.Server.MapPath(rootPath); var saveFolder = serverPath; string mediaObjectName = mediaObject.name.Replace(" ", "_"); @@ -749,7 +749,7 @@ internal MWAMediaInfo NewMediaObject( // Find unique fileName for (var count = 1; count < 30000; count++) { - var tempFileName = fileName.Insert(fileName.LastIndexOf('.'), string.Format("_{0}", count)); + var tempFileName = fileName.Insert(fileName.LastIndexOf('.'), $"_{count}"); if (File.Exists(saveFolder + tempFileName)) { continue; diff --git a/BlogEngine/BlogEngine.Core/API/MetaWeblog/XMLRPCRequest.cs b/BlogEngine/BlogEngine.Core/API/MetaWeblog/XMLRPCRequest.cs index 4bec51d6f..d2fd04f58 100644 --- a/BlogEngine/BlogEngine.Core/API/MetaWeblog/XMLRPCRequest.cs +++ b/BlogEngine/BlogEngine.Core/API/MetaWeblog/XMLRPCRequest.cs @@ -327,7 +327,7 @@ private static MWAPost GetPost(XmlNode node) /// private void LoadXmlRequest(string xml) { - var request = new XmlDocument(); + var request = new XmlDocument() { XmlResolver = null }; try { if (!(xml.StartsWith(" public static bool IsThemeRazor(string themeName) { - string path = HostingEnvironment.MapPath(string.Format("~/Custom/Themes/{0}/site.cshtml", themeName)); + string path = HostingEnvironment.MapPath($"~/Custom/Themes/{themeName}/site.cshtml"); return File.Exists(path); } @@ -421,27 +420,27 @@ public string Theme var request = context.Request; if (request.QueryString["theme"] != null) { - return request.QueryString["theme"]; + return request.QueryString["theme"].SanitizePath(); } var cookie = request.Cookies[this.ThemeCookieName]; if (cookie != null) { - return cookie.Value; + return cookie.Value.SanitizePath(); } if (Utils.ShouldForceMainTheme(request)) { - return this.configuredTheme; + return this.configuredTheme.SanitizePath(); } } - return this.configuredTheme; + return this.configuredTheme.SanitizePath(); } set { - this.configuredTheme = String.IsNullOrEmpty(value) ? String.Empty : value; + this.configuredTheme = String.IsNullOrEmpty(value) ? String.Empty : value.SanitizePath(); } } @@ -1312,7 +1311,7 @@ private void Load(Blog blog) } catch (Exception e) { - Utils.Log(string.Format("Error loading blog settings: {0}", e.Message)); + Utils.Log($"Error loading blog settings: {e.Message}"); } } diff --git a/BlogEngine/BlogEngine.Core/BusinessBase.cs b/BlogEngine/BlogEngine.Core/BusinessBase.cs index 2f05dc1be..addbb145f 100644 --- a/BlogEngine/BlogEngine.Core/BusinessBase.cs +++ b/BlogEngine/BlogEngine.Core/BusinessBase.cs @@ -2,13 +2,10 @@ { using System; using System.Collections.Generic; - using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.Security; using System.Text; - using System.Threading; - using System.Web.Security; /// /// This is the base class from which most business objects will be derived. diff --git a/BlogEngine/BlogEngine.Core/Category.cs b/BlogEngine/BlogEngine.Core/Category.cs index 03c1ba36c..c3e73d781 100644 --- a/BlogEngine/BlogEngine.Core/Category.cs +++ b/BlogEngine/BlogEngine.Core/Category.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Linq; - using System.Web; using BlogEngine.Core.Providers; @@ -366,7 +365,7 @@ public string CompleteTitle() var cat = GetCategory((Guid)parent, Blog.CurrentInstance.IsSiteAggregation); - return cat == null ? title : string.Format("{0} - {1}", cat.CompleteTitle(), title); + return cat == null ? title : $"{cat.CompleteTitle()} - {title}"; } diff --git a/BlogEngine/BlogEngine.Core/Comment.cs b/BlogEngine/BlogEngine.Core/Comment.cs index 7fe056d00..c3c7fbe9e 100644 --- a/BlogEngine/BlogEngine.Core/Comment.cs +++ b/BlogEngine/BlogEngine.Core/Comment.cs @@ -69,7 +69,7 @@ public Uri AbsoluteLink { get { - return new Uri(string.Format("{0}#id_{1}", Parent.AbsoluteLink, Id)); + return new Uri($"{Parent.AbsoluteLink}#id_{Id}"); } } @@ -240,7 +240,7 @@ public string RelativeLink { get { - return string.Format("{0}#id_{1}", Parent.RelativeLink, Id); + return $"{Parent.RelativeLink}#id_{Id}"; } } @@ -268,7 +268,7 @@ public string Teaser get { var ret = Utils.StripHtml(Content).Trim(); - return ret.Length > 120 ? string.Format("{0} ...", ret.Substring(0, 116)) : ret; + return ret.Length > 120 ? $"{ret.Substring(0, 116)} ..." : ret; } } diff --git a/BlogEngine/BlogEngine.Core/Data/BlogRepository.cs b/BlogEngine/BlogEngine.Core/Data/BlogRepository.cs index e786769c3..9925eb25a 100644 --- a/BlogEngine/BlogEngine.Core/Data/BlogRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/BlogRepository.cs @@ -2,7 +2,6 @@ using BlogEngine.Core.Data.Models; using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Linq.Dynamic; using System.Web.Hosting; @@ -52,7 +51,7 @@ public Models.Blog FindById(Guid id) if (!(Blog.CurrentInstance.IsPrimary && Security.IsAdministrator)) throw new UnauthorizedAccessException(); - var blog = Blog.Blogs.Where(b => b.Id == id).FirstOrDefault(); + var blog = Blog.Blogs.FirstOrDefault(b => b.Id == id); return ToJson(blog); } @@ -92,7 +91,7 @@ public bool Update(Models.Blog blog) throw new UnauthorizedAccessException(); try { - var coreBlog = Blog.Blogs.Where(b => b.Id == blog.Id).FirstOrDefault(); + var coreBlog = Blog.Blogs.FirstOrDefault(b => b.Id == blog.Id); return Save(coreBlog, blog); } catch (Exception) @@ -113,7 +112,7 @@ public bool Remove(Guid id) throw new UnauthorizedAccessException(); try { - var blog = Blog.Blogs.Where(b => b.Id == id).FirstOrDefault(); + var blog = Blog.Blogs.FirstOrDefault(b => b.Id == id); blog.Delete(); blog.Save(); return true; diff --git a/BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs b/BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs index a81bd871d..840eaa826 100644 --- a/BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs @@ -42,7 +42,7 @@ public IEnumerable Find(int take = 10, int skip = 0, string filter // add categories without posts foreach (var c in Category.Categories) { - var x = items.Where(i => i.Id == c.Id).FirstOrDefault(); + var x = items.FirstOrDefault(i => i.Id == c.Id); if (x == null) items.Add(new CategoryItem { Id = c.Id, Parent = OptionById(c.Parent), Title = c.Title, Description = c.Description, Count = 0 }); } @@ -87,11 +87,11 @@ public CategoryItem FindById(Guid id) // add categories without posts foreach (var c in Category.Categories) { - var x = items.Where(i => i.Id == c.Id).FirstOrDefault(); + var x = items.FirstOrDefault(i => i.Id == c.Id); if (x == null) items.Add(new CategoryItem { Id = c.Id, Parent = OptionById(c.Parent), Title = c.Title, Description = c.Description, Count = 0 }); } - return items.Where(c => c.Id == id).FirstOrDefault(); + return items.FirstOrDefault(c => c.Id == id); } /// /// Add new item @@ -115,7 +115,7 @@ public CategoryItem Add(CategoryItem item) } catch (Exception ex) { - Utils.Log(string.Format("CategoryRepository.Add: {0}", ex.Message)); + Utils.Log($"CategoryRepository.Add: {ex.Message}"); return null; } } @@ -172,7 +172,7 @@ public bool Remove(Guid id) } catch (Exception ex) { - Utils.Log(string.Format("CategoryRepository.Remove: {0}", ex.Message)); + Utils.Log($"CategoryRepository.Remove: {ex.Message}"); return false; } } diff --git a/BlogEngine/BlogEngine.Core/Data/CommentFilterRepository.cs b/BlogEngine/BlogEngine.Core/Data/CommentFilterRepository.cs index aaf73161d..56906cb9f 100644 --- a/BlogEngine/BlogEngine.Core/Data/CommentFilterRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/CommentFilterRepository.cs @@ -4,10 +4,8 @@ using System; using System.Collections.Generic; using System.Data; -using System.Globalization; using System.Linq; using System.Linq.Dynamic; -using System.Web.Hosting; namespace BlogEngine.Core.Data { diff --git a/BlogEngine/BlogEngine.Core/Data/CommentsRepository.cs b/BlogEngine/BlogEngine.Core/Data/CommentsRepository.cs index 7b52074d5..fc620ddb8 100644 --- a/BlogEngine/BlogEngine.Core/Data/CommentsRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/CommentsRepository.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Linq.Dynamic; using System.Web; using System.Web.Security; @@ -82,7 +81,7 @@ public CommentItem Add(CommentDetail item) var c = new Comment(); try { - var post = Post.Posts.Where(p => p.Id == item.PostId).FirstOrDefault(); + var post = Post.Posts.FirstOrDefault(p => p.Id == item.PostId); c.Id = Guid.NewGuid(); c.ParentId = item.ParentId; @@ -104,7 +103,7 @@ public CommentItem Add(CommentDetail item) post.AddComment(c); post.Save(); - var newComm = post.Comments.Where(cm => cm.Content == c.Content).FirstOrDefault(); + var newComm = post.Comments.FirstOrDefault(cm => cm.Content == c.Content); return Json.GetComment(newComm, post.Comments); } catch (Exception ex) diff --git a/BlogEngine/BlogEngine.Core/Data/Contracts/ICategoryRepository.cs b/BlogEngine/BlogEngine.Core/Data/Contracts/ICategoryRepository.cs index 7373a1bf7..6df8a0b97 100644 --- a/BlogEngine/BlogEngine.Core/Data/Contracts/ICategoryRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/Contracts/ICategoryRepository.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace BlogEngine.Core.Data.Contracts { diff --git a/BlogEngine/BlogEngine.Core/Data/Contracts/ICustomFieldRepository.cs b/BlogEngine/BlogEngine.Core/Data/Contracts/ICustomFieldRepository.cs index fdc12b43b..36e2646ee 100644 --- a/BlogEngine/BlogEngine.Core/Data/Contracts/ICustomFieldRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/Contracts/ICustomFieldRepository.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using BlogEngine.Core.Data.Models; namespace BlogEngine.Core.Data.Contracts diff --git a/BlogEngine/BlogEngine.Core/Data/Contracts/IFileManagerRepository.cs b/BlogEngine/BlogEngine.Core/Data/Contracts/IFileManagerRepository.cs index 7f6f3026f..5e096b856 100644 --- a/BlogEngine/BlogEngine.Core/Data/Contracts/IFileManagerRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/Contracts/IFileManagerRepository.cs @@ -1,6 +1,4 @@ -using BlogEngine.Core.Data.Models; -using BlogEngine.Core.FileSystem; -using System; +using BlogEngine.Core.FileSystem; using System.Collections.Generic; namespace BlogEngine.Core.Data.Contracts diff --git a/BlogEngine/BlogEngine.Core/Data/Contracts/IPackageRepository.cs b/BlogEngine/BlogEngine.Core/Data/Contracts/IPackageRepository.cs index 13943dcbf..96097a3a2 100644 --- a/BlogEngine/BlogEngine.Core/Data/Contracts/IPackageRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/Contracts/IPackageRepository.cs @@ -1,5 +1,4 @@ using BlogEngine.Core.Data.Models; -using BlogEngine.Core.Packaging; using System.Collections.Generic; namespace BlogEngine.Core.Data.Contracts diff --git a/BlogEngine/BlogEngine.Core/Data/Contracts/IRolesRepository.cs b/BlogEngine/BlogEngine.Core/Data/Contracts/IRolesRepository.cs index 80db6c579..1c3dcc289 100644 --- a/BlogEngine/BlogEngine.Core/Data/Contracts/IRolesRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/Contracts/IRolesRepository.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using BlogEngine.Core.Data.Models; namespace BlogEngine.Core.Data.Contracts diff --git a/BlogEngine/BlogEngine.Core/Data/Contracts/ITrashRepository.cs b/BlogEngine/BlogEngine.Core/Data/Contracts/ITrashRepository.cs index 1241492be..eb5764536 100644 --- a/BlogEngine/BlogEngine.Core/Data/Contracts/ITrashRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/Contracts/ITrashRepository.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using BlogEngine.Core.Data.Models; +using BlogEngine.Core.Data.Models; using System; namespace BlogEngine.Core.Data.Contracts diff --git a/BlogEngine/BlogEngine.Core/Data/Contracts/IUsersRepository.cs b/BlogEngine/BlogEngine.Core/Data/Contracts/IUsersRepository.cs index d3e40f490..df8ce0fc0 100644 --- a/BlogEngine/BlogEngine.Core/Data/Contracts/IUsersRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/Contracts/IUsersRepository.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using BlogEngine.Core.Data.Models; namespace BlogEngine.Core.Data.Contracts diff --git a/BlogEngine/BlogEngine.Core/Data/CustomFieldRepository.cs b/BlogEngine/BlogEngine.Core/Data/CustomFieldRepository.cs index 8cccea620..f6752c682 100644 --- a/BlogEngine/BlogEngine.Core/Data/CustomFieldRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/CustomFieldRepository.cs @@ -49,7 +49,7 @@ public CustomField FindById(string type, string id, string key) if (!Security.IsAuthorizedTo(Rights.AccessAdminPages)) throw new UnauthorizedAccessException(); - var cf = Find("").Where(f => f.CustomType == type && f.ObjectId == id && f.Key == key).FirstOrDefault(); + var cf = Find("").FirstOrDefault(f => f.CustomType == type && f.ObjectId == id && f.Key == key); return cf; } @@ -157,10 +157,10 @@ public void ClearCustomFields(string type, string id) bool AlreadyExists(CustomField item) { - var field = CustomFieldsParser.CachedFields.Where(f => f.BlogId == item.BlogId + var field = CustomFieldsParser.CachedFields.FirstOrDefault(f => f.BlogId == item.BlogId && f.CustomType == item.CustomType && f.ObjectId == item.ObjectId - && f.Key == item.Key).FirstOrDefault(); + && f.Key == item.Key); return field != null; } diff --git a/BlogEngine/BlogEngine.Core/Data/CustomFilterRepository.cs b/BlogEngine/BlogEngine.Core/Data/CustomFilterRepository.cs index 8c3e1f615..f476da6d2 100644 --- a/BlogEngine/BlogEngine.Core/Data/CustomFilterRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/CustomFilterRepository.cs @@ -81,11 +81,11 @@ public JsonResponse ResetCounters(string filterName) } ExtensionManager.SaveSettings("MetaExtension", CustomFilters); } - return new JsonResponse() { Success = true, Message = string.Format("Counters for {0} reset", filterName) }; + return new JsonResponse() { Success = true, Message = $"Counters for {filterName} reset"}; } catch (Exception ex) { - Utils.Log(string.Format("CustomFilterRepository.ResetCounters: {0}", ex.Message)); + Utils.Log($"CustomFilterRepository.ResetCounters: {ex.Message}"); return new JsonResponse() { Message = "Error resetting counters" }; } } diff --git a/BlogEngine/BlogEngine.Core/Data/FileManagerRepository.cs b/BlogEngine/BlogEngine.Core/Data/FileManagerRepository.cs index 6fcc91a98..096373bf9 100644 --- a/BlogEngine/BlogEngine.Core/Data/FileManagerRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/FileManagerRepository.cs @@ -1,13 +1,8 @@ using BlogEngine.Core.Data.Contracts; -using BlogEngine.Core.Data.Models; using BlogEngine.Core.FileSystem; using BlogEngine.Core.Providers; using System; using System.Collections.Generic; -using System.Linq; -using System.Linq.Dynamic; -using System.Web; -using System.Web.Security; namespace BlogEngine.Core.Data { @@ -23,6 +18,8 @@ public IEnumerable Find(int take = 10, int skip = 0, string path = var rwr = Utils.RelativeWebRoot; var responsePath = "root"; + path = path.SanitizePath(); + if(string.IsNullOrEmpty(path)) path = Blog.CurrentInstance.StorageLocation + Utils.FilesFolder; diff --git a/BlogEngine/BlogEngine.Core/Data/LookupsRepository.cs b/BlogEngine/BlogEngine.Core/Data/LookupsRepository.cs index 1d6eb3aa2..32842df9d 100644 --- a/BlogEngine/BlogEngine.Core/Data/LookupsRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/LookupsRepository.cs @@ -72,7 +72,7 @@ void LoadCultures() } else { - var path = HostingEnvironment.MapPath(string.Format("{0}App_GlobalResources/", Utils.ApplicationRelativeWebRoot)); + var path = HostingEnvironment.MapPath($"{Utils.ApplicationRelativeWebRoot}App_GlobalResources/"); foreach (var file in Directory.GetFiles(path, "labels.*.resx")) { var index = file.LastIndexOf(Path.DirectorySeparatorChar) + 1; diff --git a/BlogEngine/BlogEngine.Core/Data/Models/SelectOption.cs b/BlogEngine/BlogEngine.Core/Data/Models/SelectOption.cs index bb0e8dacf..0824caee9 100644 --- a/BlogEngine/BlogEngine.Core/Data/Models/SelectOption.cs +++ b/BlogEngine/BlogEngine.Core/Data/Models/SelectOption.cs @@ -14,6 +14,10 @@ public class SelectOption /// public string OptionValue { get; set; } /// + /// Option Summary + /// + public string OptionSummary { get; set; } + /// /// Is option selected /// public bool IsSelected { get; set; } diff --git a/BlogEngine/BlogEngine.Core/Data/PackageRepository.cs b/BlogEngine/BlogEngine.Core/Data/PackageRepository.cs index 04ab09acd..6c2e1377f 100644 --- a/BlogEngine/BlogEngine.Core/Data/PackageRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/PackageRepository.cs @@ -129,7 +129,7 @@ public bool Update(Package item) } else { - Utils.Log(string.Format("Failed to find extension {0} while trying to update package repository", item.Id)); + Utils.Log($"Failed to find extension {item.Id} while trying to update package repository"); } } break; diff --git a/BlogEngine/BlogEngine.Core/Data/PageRepository.cs b/BlogEngine/BlogEngine.Core/Data/PageRepository.cs index eb74f2269..994bab443 100644 --- a/BlogEngine/BlogEngine.Core/Data/PageRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/PageRepository.cs @@ -182,15 +182,15 @@ static string GetUniqueSlug(string slug) if (IsUniqueSlug(s)) break; - s = string.Format("{0}{1}", slug, i); + s = $"{slug}{i}"; } return s; } private static bool IsUniqueSlug(string slug) { - return Page.Pages.Where(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower()) - .FirstOrDefault() == null ? true : false; + return Page.Pages + .FirstOrDefault(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower()) == null ? true : false; } // if description not set, use first 100 chars in the post diff --git a/BlogEngine/BlogEngine.Core/Data/PostRepository.cs b/BlogEngine/BlogEngine.Core/Data/PostRepository.cs index e0f5e0be8..df347e25e 100644 --- a/BlogEngine/BlogEngine.Core/Data/PostRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/PostRepository.cs @@ -172,7 +172,7 @@ static void UpdatePostCategories(Post post, List categories) foreach (var cat in categories) { // add if category does not exist - var existingCat = Category.Categories.Where(c => c.Title == cat.Title).FirstOrDefault(); + var existingCat = Category.Categories.FirstOrDefault(c => c.Title == cat.Title); if (existingCat == null) { var repo = new CategoryRepository(); @@ -208,7 +208,7 @@ static List FilterTags(List tags) foreach (var t in tags) { - if (!uniqueTags.Any(u => u.TagName == t.TagName)) + if (uniqueTags.All(u => u.TagName != t.TagName)) { uniqueTags.Add(t); } @@ -226,15 +226,15 @@ static string GetUniqueSlug(string slug) if (IsUniqueSlug(s)) break; - s = string.Format("{0}{1}", slug, i); + s = $"{slug}{i}"; } return s; } static bool IsUniqueSlug(string slug) { - return Post.ApplicablePosts.Where(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower()) - .FirstOrDefault() == null ? true : false; + return Post.ApplicablePosts + .FirstOrDefault(p => p.Slug != null && p.Slug.ToLower() == slug.ToLower()) == null ? true : false; } // if description not set, use first 100 chars in the post diff --git a/BlogEngine/BlogEngine.Core/Data/RolesRepository.cs b/BlogEngine/BlogEngine.Core/Data/RolesRepository.cs index 7f07aacbc..906f9c1e5 100644 --- a/BlogEngine/BlogEngine.Core/Data/RolesRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/RolesRepository.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Linq.Dynamic; using System.Web.Security; using System.Reflection; @@ -53,7 +52,7 @@ public RoleItem FindById(string id) var roles = new List(); roles.AddRange(System.Web.Security.Roles.GetAllRoles().Select(r => new Data.Models.RoleItem { RoleName = r, IsSystemRole = Security.IsSystemRole(r) })); - return roles.Where(r => r.RoleName.ToLower() == id.ToLower()).FirstOrDefault(); + return roles.FirstOrDefault(r => r.RoleName.ToLower() == id.ToLower()); } /// @@ -67,7 +66,7 @@ public RoleItem Add(Data.Models.RoleItem role) { throw new System.UnauthorizedAccessException(); } - else if (Utils.StringIsNullOrWhitespace(role.RoleName)) + else if (String.IsNullOrWhiteSpace(role.RoleName)) { throw new ApplicationException("Role name is required"); } @@ -101,7 +100,7 @@ public bool Update(RoleItem role, string oldRole) if (!Security.IsAuthorizedTo(Rights.EditRoles)) throw new System.UnauthorizedAccessException(); - var updateRole = System.Web.Security.Roles.GetAllRoles().Where(r => r.ToString() == oldRole).FirstOrDefault(); + var updateRole = Roles.GetAllRoles().FirstOrDefault(r => r.ToString() == oldRole); if (updateRole == null) throw new ApplicationException("Role not found"); @@ -121,7 +120,7 @@ public bool Remove(string id) if (!Security.IsAuthorizedTo(Rights.DeleteRoles)) throw new System.UnauthorizedAccessException(); - if (Utils.StringIsNullOrWhitespace(id)) + if (String.IsNullOrWhiteSpace(id)) throw new ApplicationException("Role name is required"); try @@ -172,7 +171,7 @@ public IEnumerable GetRoleRights(string role) var category = rightDetails == null ? RightCategory.General : rightDetails.Category; - var group = groups.Where(g => g.Title == category.ToString()).FirstOrDefault(); + var group = groups.FirstOrDefault(g => g.Title == category.ToString()); var prm = new Permission(); var rt = Right.GetRightByName(right.ToString()); @@ -234,7 +233,7 @@ public bool SaveRights(List rights, string id) { throw new System.UnauthorizedAccessException(); } - else if (Utils.StringIsNullOrWhitespace(id)) + else if (String.IsNullOrWhiteSpace(id)) { throw new ApplicationException("Invalid role name"); } diff --git a/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs b/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs index 0052850c8..a1b88ee4a 100644 --- a/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs +++ b/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs @@ -1,7 +1,6 @@ using System.Security.Cryptography; using System.Text; using System.Web; -using System.Web.Security; namespace BlogEngine.Core.Data.Services { @@ -10,8 +9,8 @@ namespace BlogEngine.Core.Data.Services /// public class Avatar { - private static string _noAvatar = string.Format("{0}Content/images/blog/noavatar.jpg", Utils.AbsoluteWebRoot); - private static string _pingImg = string.Format("{0}Content/images/blog/pingback.png", Utils.AbsoluteWebRoot); + private static string _noAvatar = $"{Utils.AbsoluteWebRoot}Content/images/blog/noavatar.jpg"; + private static string _pingImg = $"{Utils.AbsoluteWebRoot}Content/images/blog/pingback.png"; /// /// Get avatar image source @@ -43,13 +42,13 @@ public static string GetSrc(string email, string website = "") return src; // default noavatar if nothing worked - return string.Format("{0}Content/images/blog/noavatar.jpg", Utils.AbsoluteWebRoot); + return $"{Utils.AbsoluteWebRoot}Content/images/blog/noavatar.jpg"; } static string ThemeNoAvatar(string email) { - var themeAvatar = string.Format( - "{0}Custom/Themes/{1}/noavatar.jpg", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.Theme); + var themeAvatar = + $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{BlogSettings.Instance.Theme}/noavatar.jpg"; if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(themeAvatar))) return themeAvatar; @@ -65,7 +64,7 @@ static string Gravatar(string email) if (hash != null) hash = hash.ToLowerInvariant(); - var gravatar = string.Format("http://www.gravatar.com/avatar/{0}.jpg?d=", hash); + var gravatar = $"http://www.gravatar.com/avatar/{hash}.jpg?d="; switch (BlogSettings.Instance.Avatar) { diff --git a/BlogEngine/BlogEngine.Core/Data/Services/CustomFieldsParser.cs b/BlogEngine/BlogEngine.Core/Data/Services/CustomFieldsParser.cs index df2b5cb26..1601944a6 100644 --- a/BlogEngine/BlogEngine.Core/Data/Services/CustomFieldsParser.cs +++ b/BlogEngine/BlogEngine.Core/Data/Services/CustomFieldsParser.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Linq.Dynamic; using System.Text.RegularExpressions; using System.Web; using System.Web.Caching; @@ -117,8 +116,8 @@ static string ReplaceCustomFields(string html) if (s[1] == "POST") { - var cf = postFields.Where(f => f.Key.ToLower() == key.ToLower() - && f.ObjectId.ToLower() == id.ToLower()).FirstOrDefault(); + var cf = postFields.FirstOrDefault(f => f.Key.ToLower() == key.ToLower() + && f.ObjectId.ToLower() == id.ToLower()); if (cf != null) val = cf.Value; @@ -126,8 +125,8 @@ static string ReplaceCustomFields(string html) if (s[1] == "THEME") { - var cf = themeFields.Where(f => f.Key.ToLower() == key.ToLower() - && f.ObjectId.ToLower() == id.ToLower()).FirstOrDefault(); + var cf = themeFields.FirstOrDefault(f => f.Key.ToLower() == key.ToLower() + && f.ObjectId.ToLower() == id.ToLower()); if (cf != null) val = cf.Value; @@ -159,7 +158,7 @@ static List LoadFields() static List FromThemeTemplates() { var dirPath = HttpContext.Current.Server.MapPath( - string.Format("{0}Custom/Themes", Utils.ApplicationRelativeWebRoot)); + $"{Utils.ApplicationRelativeWebRoot}Custom/Themes"); var items = new List(); diff --git a/BlogEngine/BlogEngine.Core/Data/Services/Json.cs b/BlogEngine/BlogEngine.Core/Data/Services/Json.cs index c89006bee..e23501d19 100644 --- a/BlogEngine/BlogEngine.Core/Data/Services/Json.cs +++ b/BlogEngine/BlogEngine.Core/Data/Services/Json.cs @@ -141,7 +141,7 @@ public static CommentItem GetComment(Comment c, List postComments) jc.Title = c.Teaser.Length < 80 ? c.Teaser : c.Teaser.Substring(0, 80) + "..."; jc.DateCreated = c.DateCreated.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture); jc.RelativeLink = c.RelativeLink; - jc.HasChildren = postComments.Where(pc => pc.ParentId == c.Id).FirstOrDefault() != null; + jc.HasChildren = postComments.FirstOrDefault(pc => pc.ParentId == c.Id) != null; jc.Avatar = Gravatar(c); return jc; } @@ -223,7 +223,7 @@ static SelectOption ItemParent(Guid? id) if (id == null || id == Guid.Empty) return null; - var item = Category.Categories.Where(c => c.Id == id).FirstOrDefault(); + var item = Category.Categories.FirstOrDefault(c => c.Id == id); return new SelectOption { OptionName = item.Title, OptionValue = item.Id.ToString() }; } diff --git a/BlogEngine/BlogEngine.Core/Data/Services/TagCloud.cs b/BlogEngine/BlogEngine.Core/Data/Services/TagCloud.cs index f892ed71a..ae60713e8 100644 --- a/BlogEngine/BlogEngine.Core/Data/Services/TagCloud.cs +++ b/BlogEngine/BlogEngine.Core/Data/Services/TagCloud.cs @@ -34,8 +34,8 @@ public List Links() { var link = string.Format( Link, - string.Format("{0}?tag={1}", Utils.AbsoluteWebRoot, HttpUtility.UrlEncode(key)), - WeightedList[key], string.Format("Tag: {0}", key), key); + $"{Utils.AbsoluteWebRoot}?tag={HttpUtility.UrlEncode(key)}", + WeightedList[key], $"Tag: {key}", key); links.Add(link); } return links; diff --git a/BlogEngine/BlogEngine.Core/Data/StatsRepository.cs b/BlogEngine/BlogEngine.Core/Data/StatsRepository.cs index d4b027922..478f9ab79 100644 --- a/BlogEngine/BlogEngine.Core/Data/StatsRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/StatsRepository.cs @@ -1,7 +1,6 @@ using BlogEngine.Core.Data.Contracts; using BlogEngine.Core.Data.Models; using System.Linq; -using System.Text; namespace BlogEngine.Core.Data { @@ -26,11 +25,11 @@ public Stats Get() if (!Security.IsAuthorizedTo(Rights.EditOtherUsersPosts)) postList = postList.Where(p => p.Author.ToLower() == Security.CurrentUser.Identity.Name.ToLower()).ToList(); - stats.PublishedPostsCount = postList.Where(p => p.IsPublished == true).Count(); - stats.DraftPostsCount = postList.Where(p => p.IsPublished == false).Count(); + stats.PublishedPostsCount = postList.Count(p => p.IsPublished == true); + stats.DraftPostsCount = postList.Count(p => p.IsPublished == false); - stats.PublishedPagesCount = Page.Pages.Where(p => p.IsPublished == true && p.IsDeleted == false).Count(); - stats.DraftPagesCount = Page.Pages.Where(p => p.IsPublished == false && p.IsDeleted == false).Count(); + stats.PublishedPagesCount = Page.Pages.Count(p => p.IsPublished == true && p.IsDeleted == false); + stats.DraftPagesCount = Page.Pages.Count(p => p.IsPublished == false && p.IsDeleted == false); CountComments(stats); @@ -70,9 +69,9 @@ void CountComments(Stats stats) if (post.Author.ToLower() != Security.CurrentUser.Identity.Name.ToLower()) continue; - stats.PublishedCommentsCount += post.Comments.Where(c => c.IsPublished == true && c.IsDeleted == false).Count(); - stats.UnapprovedCommentsCount += post.Comments.Where(c => c.IsPublished == false && c.IsSpam == false && c.IsDeleted == false).Count(); - stats.SpamCommentsCount += post.Comments.Where(c => c.IsPublished == false && c.IsSpam == true && c.IsDeleted == false).Count(); + stats.PublishedCommentsCount += post.Comments.Count(c => c.IsPublished == true && c.IsDeleted == false); + stats.UnapprovedCommentsCount += post.Comments.Count(c => c.IsPublished == false && c.IsSpam == false && c.IsDeleted == false); + stats.SpamCommentsCount += post.Comments.Count(c => c.IsPublished == false && c.IsSpam == true && c.IsDeleted == false); } } diff --git a/BlogEngine/BlogEngine.Core/Data/TagRepository.cs b/BlogEngine/BlogEngine.Core/Data/TagRepository.cs index 1829ea854..55b91992d 100644 --- a/BlogEngine/BlogEngine.Core/Data/TagRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/TagRepository.cs @@ -87,7 +87,7 @@ public bool Save(string updateFrom, string updateTo) } catch (Exception ex) { - Utils.Log(string.Format("TagRepository.Update: {0}", ex.Message)); + Utils.Log($"TagRepository.Update: {ex.Message}"); return false; } } @@ -117,7 +117,7 @@ public bool Delete(string id) } catch (Exception ex) { - Utils.Log(string.Format("Tags.Delete: {0}", ex.Message)); + Utils.Log($"Tags.Delete: {ex.Message}"); return false; } } diff --git a/BlogEngine/BlogEngine.Core/Data/TrashRepository.cs b/BlogEngine/BlogEngine.Core/Data/TrashRepository.cs index 9ebc34525..b2f50165f 100644 --- a/BlogEngine/BlogEngine.Core/Data/TrashRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/TrashRepository.cs @@ -152,11 +152,11 @@ public bool Restore(string trashType, Guid id) } break; case "Post": - var delPost = Post.DeletedPosts.Where(p => p.Id == id).FirstOrDefault(); + var delPost = Post.DeletedPosts.FirstOrDefault(p => p.Id == id); if (delPost != null) delPost.Restore(); break; case "Page": - var delPage = Page.DeletedPages.Where(pg => pg.Id == id).FirstOrDefault(); + var delPage = Page.DeletedPages.FirstOrDefault(pg => pg.Id == id); if (delPage != null) delPage.Restore(); break; default: @@ -189,11 +189,11 @@ public bool Purge(string trashType, Guid id) } break; case "Post": - var delPost = Post.DeletedPosts.Where(p => p.Id == id).FirstOrDefault(); + var delPost = Post.DeletedPosts.FirstOrDefault(p => p.Id == id); if (delPost != null) delPost.Purge(); break; case "Page": - var delPage = Page.DeletedPages.Where(pg => pg.Id == id).FirstOrDefault(); + var delPage = Page.DeletedPages.FirstOrDefault(pg => pg.Id == id); if (delPage != null) delPage.Purge(); break; default: diff --git a/BlogEngine/BlogEngine.Core/Data/UsersRepository.cs b/BlogEngine/BlogEngine.Core/Data/UsersRepository.cs index f577e7020..a574298e4 100644 --- a/BlogEngine/BlogEngine.Core/Data/UsersRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/UsersRepository.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic; -using System.Web; using System.Web.Security; namespace BlogEngine.Core.Data @@ -99,6 +98,9 @@ public BlogUser Add(BlogUser user) if (!Security.IsAuthorizedTo(Rights.CreateNewUsers)) throw new UnauthorizedAccessException(); + if (user.UserName.Contains("/") || user.UserName.Contains(@"\")) + throw new ApplicationException("Error adding new user; Invalid character detected in UserName"); + // create user var usr = Membership.CreateUser(user.UserName, user.Password, user.Email); if (usr == null) @@ -226,7 +228,7 @@ public bool Remove(string id){ static Profile GetProfile(string id) { - if (!Utils.StringIsNullOrWhitespace(id)) + if (!String.IsNullOrWhiteSpace(id)) { var pf = AuthorProfile.GetProfile(id); if (pf == null) diff --git a/BlogEngine/BlogEngine.Core/Data/ViewModels/BlogRollVM.cs b/BlogEngine/BlogEngine.Core/Data/ViewModels/BlogRollVM.cs index 8eea069e1..8f10a2e46 100644 --- a/BlogEngine/BlogEngine.Core/Data/ViewModels/BlogRollVM.cs +++ b/BlogEngine/BlogEngine.Core/Data/ViewModels/BlogRollVM.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.ServiceModel.Syndication; using System.Xml; -using System.Web; -using System.Linq; using System.Collections.Specialized; namespace BlogEngine.Core.Data.ViewModels diff --git a/BlogEngine/BlogEngine.Core/Data/ViewModels/CommentsVM.cs b/BlogEngine/BlogEngine.Core/Data/ViewModels/CommentsVM.cs index 5d0bc74ce..0687f27bb 100644 --- a/BlogEngine/BlogEngine.Core/Data/ViewModels/CommentsVM.cs +++ b/BlogEngine/BlogEngine.Core/Data/ViewModels/CommentsVM.cs @@ -1,9 +1,5 @@ using BlogEngine.Core.Data.Models; -using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace BlogEngine.Core.Data.ViewModels { diff --git a/BlogEngine/BlogEngine.Core/Data/ViewModels/DashboardVM.cs b/BlogEngine/BlogEngine.Core/Data/ViewModels/DashboardVM.cs index bee28943b..a12909082 100644 --- a/BlogEngine/BlogEngine.Core/Data/ViewModels/DashboardVM.cs +++ b/BlogEngine/BlogEngine.Core/Data/ViewModels/DashboardVM.cs @@ -123,9 +123,9 @@ private void LoadPosts() foreach (var p in posts) { - ApprovedCommentsCnt += p.Comments.Where(c => c.IsPublished && !c.IsDeleted).Count(); - PendingCommentsCnt += p.Comments.Where(c => !c.IsPublished && !c.IsSpam && !c.IsDeleted).Count(); - SpamCommentsCnt += p.Comments.Where(c => !c.IsPublished && c.IsSpam && !c.IsDeleted).Count(); + ApprovedCommentsCnt += p.Comments.Count(c => c.IsPublished && !c.IsDeleted); + PendingCommentsCnt += p.Comments.Count(c => !c.IsPublished && !c.IsSpam && !c.IsDeleted); + SpamCommentsCnt += p.Comments.Count(c => !c.IsPublished && c.IsSpam && !c.IsDeleted); _comments.AddRange(p.Comments); } } @@ -146,7 +146,7 @@ private void LoadTrash() { var posts = Post.DeletedPosts; _trash = new List(); - if (posts.Count() > 0) + if (posts.Any()) { foreach (var p in posts) { @@ -162,7 +162,7 @@ private void LoadTrash() } } var pages = Page.DeletedPages; - if (pages.Count() > 0) + if (pages.Any()) { foreach (var page in pages) { @@ -187,7 +187,7 @@ private void LoadTrash() comms.AddRange(p.DeletedComments); } - if (comms.Count() > 0) + if (comms.Any()) { foreach (var c in comms) { diff --git a/BlogEngine/BlogEngine.Core/Extensions.cs b/BlogEngine/BlogEngine.Core/Extensions.cs index 953eaf6d3..1f326c445 100644 --- a/BlogEngine/BlogEngine.Core/Extensions.cs +++ b/BlogEngine/BlogEngine.Core/Extensions.cs @@ -92,5 +92,27 @@ public static bool TryParse(this string theString, out T output) return success; } + + /// + /// Sanitize path by removing invalid characters. Valid path should look similar to "path/to/sub/folder" + /// + /// String to sanitize + /// Optionally validate datastore root + /// String out + public static string SanitizePath(this string str, string root = "") + { + if (str.Contains("..")) + return ""; + + if (str.StartsWith("~/") && !string.IsNullOrEmpty(root) && !str.StartsWith(root)) + return ""; + + str = str.Replace(".", "").Replace("\\", "").Replace("%2F", ""); + + if (str.Contains("//")) + return ""; + + return str; + } } } diff --git a/BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs b/BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs index a4520b763..8f1bc8f32 100644 --- a/BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs +++ b/BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs @@ -116,7 +116,7 @@ public static bool ValidateProperties(string blogName, string userName, string e return false; } - if (Blog.Blogs.Where(b => b.Name.ToLower() == blogName.ToLower()).FirstOrDefault() != null) + if (Blog.Blogs.FirstOrDefault(b => b.Name.ToLower() == blogName.ToLower()) != null) { message = "Blog with this name already exists; Please select different name."; return false; @@ -150,7 +150,7 @@ public static bool CopyTemplateBlogFolder(string blogName, string userName, stri if (!Directory.Exists(templateFolderPath)) { - throw new Exception(string.Format("Template folder for new blog does not exist. Directory not found is: {0}", templateFolderPath)); + throw new Exception($"Template folder for new blog does not exist. Directory not found is: {templateFolderPath}"); } } catch (Exception ex) @@ -165,7 +165,7 @@ public static bool CopyTemplateBlogFolder(string blogName, string userName, stri { if (Directory.Exists(newBlogFolderPath)) { - throw new Exception(string.Format("Blog destination folder already exists. {0}", newBlogFolderPath)); + throw new Exception($"Blog destination folder already exists. {newBlogFolderPath}"); } } catch (Exception ex) @@ -174,7 +174,7 @@ public static bool CopyTemplateBlogFolder(string blogName, string userName, stri throw; // re-throw error so error message bubbles up. } if (!Utils.CreateDirectoryIfNotExists(newBlogFolderPath)) - throw new Exception(string.Format("Can not create blog directory: {0}", newBlogFolderPath)); + throw new Exception($"Can not create blog directory: {newBlogFolderPath}"); // Copy the entire directory contents. DirectoryInfo source = new DirectoryInfo(templateFolderPath); diff --git a/BlogEngine/BlogEngine.Core/Helpers/Pager.cs b/BlogEngine/BlogEngine.Core/Helpers/Pager.cs index 9693338f6..4b0b59ea2 100644 --- a/BlogEngine/BlogEngine.Core/Helpers/Pager.cs +++ b/BlogEngine/BlogEngine.Core/Helpers/Pager.cs @@ -100,7 +100,7 @@ public static string Render(string callback = "false") var linkFormat = "{1}"; - var pageLink = string.Format("Showing {0} - {1} of {2}", From, To, Total); + var pageLink = $"Showing {From} - {To} of {Total}"; if (CurrentPage > 1) { diff --git a/BlogEngine/BlogEngine.Core/Helpers/Utils.cs b/BlogEngine/BlogEngine.Core/Helpers/Utils.cs index 428a7841a..d790bd134 100644 --- a/BlogEngine/BlogEngine.Core/Helpers/Utils.cs +++ b/BlogEngine/BlogEngine.Core/Helpers/Utils.cs @@ -127,7 +127,7 @@ public static string FeedUrl { return !string.IsNullOrEmpty(BlogSettings.Instance.AlternateFeedUrl) ? BlogSettings.Instance.AlternateFeedUrl - : string.Format("{0}syndication.axd", AbsoluteWebRoot); + : $"{AbsoluteWebRoot}syndication.axd"; } } @@ -259,7 +259,7 @@ public static bool IsCurrentRequestForHomepage if (RelativeWebRoot.Equals(VirtualPathUtility.AppendTrailingSlash(path), StringComparison.OrdinalIgnoreCase)) return true; - else if (path.Equals(string.Format("{0}default.aspx", RelativeWebRoot), StringComparison.OrdinalIgnoreCase)) + else if (path.Equals($"{RelativeWebRoot}default.aspx", StringComparison.OrdinalIgnoreCase)) return true; return false; @@ -402,7 +402,7 @@ public static void AddJavaScriptInclude(System.Web.UI.Page page, string url, boo if (placeInBottom) { var deferAttr = (addDeferAttribute ? " defer=\"defer\"" : string.Empty); - var script = string.Format("", deferAttr, url); + var script = $""; page.ClientScript.RegisterStartupScript(page.GetType(), url.GetHashCode().ToString(), script); } else @@ -460,7 +460,7 @@ public static IEnumerable CodeAssemblies() { for (var i = 0; i < s.CodeSubDirectories.Count; i++) { - assemblyName = string.Format("App_SubCode_{0}", s.CodeSubDirectories[i].DirectoryName); + assemblyName = $"App_SubCode_{s.CodeSubDirectories[i].DirectoryName}"; codeAssemblies.Add(Assembly.Load(assemblyName)); } } @@ -514,7 +514,7 @@ public static Uri ConvertToAbsolute(string relativeUri) { if (String.IsNullOrEmpty(relativeUri)) { - throw new ArgumentNullException("relativeUri"); + throw new ArgumentNullException(nameof(relativeUri)); } var absolute = AbsoluteWebRoot.ToString(); @@ -609,9 +609,9 @@ public static string ConvertPublishablePathsToAbsolute(string content, IPublisha string.Format("\"{0}image.axd", publishable.Blog.AbsoluteWebRoot.AbsolutePath), "\"" + publishable.Blog.AbsoluteWebRoot + "image.axd"); content = content.Replace( string.Format("\"{0}file.axd", publishable.Blog.AbsoluteWebRoot.AbsolutePath), "\"" + publishable.Blog.AbsoluteWebRoot + "file.axd"); - content = content.Replace(string.Format("href=\"{0}{1}", publishable.Blog.RelativeWebRoot, string.Empty), string.Format("href=\"{0}", publishable.Blog.AbsoluteWebRoot)); + content = content.Replace($"href=\"{publishable.Blog.RelativeWebRoot}", $"href=\"{publishable.Blog.AbsoluteWebRoot}"); - content = content.Replace("href=\"/", string.Format("href=\"{0}", publishable.Blog.AbsoluteWebRoot)); + content = content.Replace("href=\"/", $"href=\"{publishable.Blog.AbsoluteWebRoot}"); return content; } @@ -675,7 +675,7 @@ public static Dictionary FindSemanticDocuments(Uri url, string public static CultureInfo GetDefaultCulture() { var settingsCulture = BlogSettings.Instance.Culture; - if (Utils.StringIsNullOrWhitespace(settingsCulture) || + if (String.IsNullOrWhiteSpace(settingsCulture) || settingsCulture.Equals("Auto", StringComparison.OrdinalIgnoreCase)) { return CultureInfo.InstalledUICulture; @@ -795,7 +795,7 @@ public static void InjectUserControls(System.Web.UI.Control containerControl, st { // Whoopss, can't load that control so lets output something that tells the developer that theres a problem. containerControls.Add( - new LiteralControl(string.Format("ERROR - UNABLE TO LOAD CONTROL : {0}", match.Groups[1].Value))); + new LiteralControl($"ERROR - UNABLE TO LOAD CONTROL : {match.Groups[1].Value}")); } currentPosition = match.Index + match.Groups[0].Length; @@ -969,7 +969,7 @@ public static void Log(string format, params object[] args) /// public static void Log(string methodName, Exception ex) { - Log(String.Format("{0}: {1}", methodName, ex.Message)); + Log($"{methodName}: {ex.Message}"); } /// @@ -1031,7 +1031,7 @@ public static string RenderControl(System.Web.UI.Control control) { if (control == null) { - throw new ArgumentNullException("control"); + throw new ArgumentNullException(nameof(control)); } using (var sWriter = new System.IO.StringWriter()) @@ -1108,7 +1108,7 @@ public static string SendMailMessage(MailMessage message, string smtpServer = "" int intPort = BlogSettings.Instance.SmtpServerPort; if (message == null) - throw new ArgumentNullException("message"); + throw new ArgumentNullException(nameof(message)); try { @@ -1212,7 +1212,7 @@ public static bool SetConditionalGetHeaders(DateTime date) var response = HttpContext.Current.Response; var request = HttpContext.Current.Request; - var etag = string.Format("\"{0}\"", date.Ticks); + var etag = $"\"{date.Ticks}\""; var incomingEtag = request.Headers["If-None-Match"]; DateTime incomingLastModifiedDate; @@ -1232,16 +1232,6 @@ public static bool SetConditionalGetHeaders(DateTime date) return false; } - /// - /// Returns whether a string is null, empty, or whitespace. Same implementation as in String.IsNullOrWhitespace in .Net 4.0 - /// - /// - /// - public static bool StringIsNullOrWhitespace(string value) - { - return ((value == null) || (value.Trim().Length == 0)); - } - /// /// Strips all HTML tags from the specified string. /// @@ -1253,7 +1243,7 @@ public static bool StringIsNullOrWhitespace(string value) /// public static string StripHtml(string html) { - return Utils.StringIsNullOrWhitespace(html) ? string.Empty : RegexStripHtml.Replace(html, string.Empty).Trim(); + return String.IsNullOrWhiteSpace(html) ? string.Empty : RegexStripHtml.Replace(html, string.Empty).Trim(); } /// @@ -1313,8 +1303,8 @@ public static string Translate(string text, string defaultValue, CultureInfo cul return resource != null ? resource.ToString() : (string.IsNullOrEmpty(defaultValue) - ? string.Format("Missing Resource [{0}]", text) - : defaultValue); + ? $"Missing Resource [{text}]" + : defaultValue); } /// @@ -1330,7 +1320,7 @@ public static bool CanWrite(string url, string file = "") if (dir != null && Directory.Exists(dir)) { if (string.IsNullOrEmpty(file)) - file = string.Format("test{0}.txt", DateTime.Now.ToString("ddmmhhssss")); + file = $"test{DateTime.Now.ToString("ddmmhhssss")}.txt"; try { @@ -1552,7 +1542,7 @@ private static XmlDocument LoadDocument(Uri url, Uri xmlUrl) } else { - absoluteUrl = string.Format("{0}://{1}{2}", url.Scheme, url.Authority, xmlUrl); + absoluteUrl = $"{url.Scheme}://{url.Authority}{xmlUrl}"; } var readerSettings = new XmlReaderSettings diff --git a/BlogEngine/BlogEngine.Core/Helpers/XmlSafeResolver.cs b/BlogEngine/BlogEngine.Core/Helpers/XmlSafeResolver.cs index e4f763916..c0aeb66bf 100644 --- a/BlogEngine/BlogEngine.Core/Helpers/XmlSafeResolver.cs +++ b/BlogEngine/BlogEngine.Core/Helpers/XmlSafeResolver.cs @@ -75,13 +75,13 @@ public override object GetEntity(Uri absoluteUri, string role, Type typeOfObject response = request.GetResponse(); if (response == null) { - Utils.Log(string.Format("Could not resolve external entity ({0})", absoluteUri)); + Utils.Log($"Could not resolve external entity ({absoluteUri})"); return null; } } catch (Exception) { - Utils.Log(string.Format("Could not resolve external entity ({0})", absoluteUri)); + Utils.Log($"Could not resolve external entity ({absoluteUri})"); return null; } diff --git a/BlogEngine/BlogEngine.Core/Page.cs b/BlogEngine/BlogEngine.Core/Page.cs index 1472c9e7f..d0f69b359 100644 --- a/BlogEngine/BlogEngine.Core/Page.cs +++ b/BlogEngine/BlogEngine.Core/Page.cs @@ -349,7 +349,7 @@ public string RelativeLink get { var theslug = Utils.RemoveIllegalCharacters(this.Slug) + BlogConfig.FileExtension; - return string.Format("{0}page/{1}", Utils.RelativeWebRoot, theslug); + return $"{Utils.RelativeWebRoot}page/{theslug}"; } } diff --git a/BlogEngine/BlogEngine.Core/Post.cs b/BlogEngine/BlogEngine.Core/Post.cs index ceccbb7cd..fed08b3ea 100644 --- a/BlogEngine/BlogEngine.Core/Post.cs +++ b/BlogEngine/BlogEngine.Core/Post.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Net.Mail; using System.Text; + using System.Text.RegularExpressions; using System.Web; using BlogEngine.Core.Data.Models; @@ -478,7 +479,7 @@ public Uri PermaLink { get { - return new Uri(string.Format("{0}post.aspx?id={1}", this.Blog.AbsoluteWebRoot, this.Id)); + return new Uri($"{Blog.AbsoluteWebRoot}post.aspx?id={Id}"); //return new Uri(string.Format("{0}post/{1}", this.Blog.AbsoluteWebRoot, this.Slug)); } } @@ -659,7 +660,7 @@ public Uri TrackbackLink { get { - return new Uri(string.Format("{0}trackback.axd?id={1}", this.Blog.AbsoluteWebRoot, this.Id)); + return new Uri($"{Blog.AbsoluteWebRoot}trackback.axd?id={Id}"); } } @@ -694,28 +695,27 @@ public bool IsVisibleToPublic } /// - /// URL of the first image in the post, if any + /// URL of the first image in the post, if any. + /// If there's no first image, returns the URL to "images/defaultImg.jpg" in the current theme used in the blog /// public string FirstImgSrc { get { - int idx = Content.IndexOf("", RegexOptions.Multiline | RegexOptions.IgnoreCase); + if (match.Success) { - idx = idx + 10; - var idxEnd = Content.IndexOf("\"", idx); - if (idxEnd > idx) - { - var len = idxEnd - idx; - return Content.Substring(idx, len); - } + srcValue = match.Groups[2].Value; } - catch (Exception) { } } - return ""; + if (string.IsNullOrEmpty(srcValue)) + { + srcValue = Utils.RelativeWebRoot + "Custom/Themes/" + BlogSettings.Instance.Theme + "/images/defaultImg.jpg"; + } + return srcValue; } } @@ -1180,7 +1180,7 @@ public static string GetUniqueSlug(string slug, Guid postId) if (IsUniqueSlug(s, postId)) break; - s = string.Format("{0}{1}", slug, i); + s = $"{slug}{i}"; } return s; } @@ -1950,7 +1950,7 @@ private void SendNotifications(Comment comment) var mail = new MailMessage { From = new MailAddress(BlogSettings.Instance.Email, BlogSettings.Instance.Name), - Subject = string.Format("New comment on {0}", this.Title), + Subject = $"New comment on {Title}", Body = sb.ToString() }; diff --git a/BlogEngine/BlogEngine.Core/Properties/AssemblyInfo.cs b/BlogEngine/BlogEngine.Core/Properties/AssemblyInfo.cs index 8cbb71e53..0bc198c31 100644 --- a/BlogEngine/BlogEngine.Core/Properties/AssemblyInfo.cs +++ b/BlogEngine/BlogEngine.Core/Properties/AssemblyInfo.cs @@ -13,11 +13,11 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BlogEngine.NET")] -[assembly: AssemblyCopyright("Copyright @ 2007-2016")] +[assembly: AssemblyCopyright("Copyright @ 2007-2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: ComVisible(false)] [assembly: AllowPartiallyTrustedCallers] -[assembly: AssemblyVersion("3.3.5.0")] -[assembly: SecurityRules(SecurityRuleSet.Level1)] +[assembly: AssemblyVersion("3.3.8.0")] +[assembly: SecurityRules(SecurityRuleSet.Level1)] \ No newline at end of file diff --git a/BlogEngine/BlogEngine.Core/Providers/BlogProviderCollection.cs b/BlogEngine/BlogEngine.Core/Providers/BlogProviderCollection.cs index 5fa895f15..087c8b12c 100644 --- a/BlogEngine/BlogEngine.Core/Providers/BlogProviderCollection.cs +++ b/BlogEngine/BlogEngine.Core/Providers/BlogProviderCollection.cs @@ -36,12 +36,12 @@ public override void Add(ProviderBase provider) { if (provider == null) { - throw new ArgumentNullException("provider"); + throw new ArgumentNullException(nameof(provider)); } if (!(provider is BlogProvider)) { - throw new ArgumentException("Invalid provider type", "provider"); + throw new ArgumentException("Invalid provider type", nameof(provider)); } base.Add(provider); diff --git a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbBlogProvider.cs b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbBlogProvider.cs index aa562249d..dcdc7ee73 100644 --- a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbBlogProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbBlogProvider.cs @@ -52,7 +52,7 @@ public override void Initialize(string name, NameValueCollection config) { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (String.IsNullOrEmpty(name)) @@ -101,7 +101,7 @@ public override void Initialize(string name, NameValueCollection config) var attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) { - throw new ProviderException(string.Format("Unrecognized attribute: {0}", attr)); + throw new ProviderException($"Unrecognized attribute: {attr}"); } } } @@ -124,7 +124,7 @@ public override List FillBlogs() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT BlogId, BlogName, Hostname, IsAnyTextBeforeHostnameAccepted, StorageContainerName, VirtualPath, IsPrimary, IsActive, IsSiteAggregation FROM {0}Blogs ", this.tablePrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT BlogId, BlogName, Hostname, IsAnyTextBeforeHostnameAccepted, StorageContainerName, VirtualPath, IsPrimary, IsActive, IsSiteAggregation FROM {tablePrefix}Blogs ")) { using (var rdr = cmd.ExecuteReader()) { @@ -233,7 +233,7 @@ public override void DeleteBlog(Blog blog) { if (conn.HasConnection) { - var sqlQuery = string.Format("DELETE FROM {0}Blogs WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + var sqlQuery = $"DELETE FROM {tablePrefix}Blogs WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); @@ -272,133 +272,133 @@ public override bool DeleteBlogStorageContainer(Blog blog) // foreign key constraints are setup (SQL Server is one). The data // in the referencing tables needs to be deleted first. - var sqlQuery = string.Format("DELETE FROM {0}PostTag WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + var sqlQuery = $"DELETE FROM {tablePrefix}PostTag WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}PostNotify WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}PostNotify WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}PostComment WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}PostComment WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}PostCategory WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}PostCategory WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Posts WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Posts WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}RightRoles WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}RightRoles WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Profiles WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Profiles WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}UserRoles WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}UserRoles WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Roles WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Roles WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Rights WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Rights WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Users WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Users WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Pages WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Pages WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}StopWords WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}StopWords WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Settings WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Settings WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Referrers WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Referrers WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}PingService WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}PingService WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}DataStoreSettings WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}DataStoreSettings WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}BlogRollItems WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}BlogRollItems WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Categories WHERE BlogId = {1}BlogId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Categories WHERE BlogId = {parmPrefix}BlogId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("BlogId"), blog.Id.ToString())); @@ -707,7 +707,7 @@ public override bool SetupNewBlog(Blog newBlog, string userName, string email, s { if (conn.HasConnection) { - Blog existingBlog = Blog.Blogs.Where(b => b.Name == "Template").FirstOrDefault(); + Blog existingBlog = Blog.Blogs.FirstOrDefault(b => b.Name == "Template"); if (existingBlog == null) existingBlog = Blog.Blogs[0]; @@ -749,7 +749,7 @@ public override bool SetupNewBlog(Blog newBlog, string userName, string email, s } // be_Settings - using (var cmd = conn.CreateTextCommand(string.Format("DELETE FROM {0}Settings WHERE BlogId = {1}blogid", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"DELETE FROM {tablePrefix}Settings WHERE BlogId = {parmPrefix}blogid")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), newBlog.Id.ToString())); cmd.ExecuteNonQuery(); @@ -889,7 +889,7 @@ public override List FillPosts() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT PostID FROM {0}Posts WHERE BlogID = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT PostID FROM {tablePrefix}Posts WHERE BlogID = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -1264,7 +1264,7 @@ public override void DeletePost(Post post) cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Posts WHERE BlogID = @blogid AND PostID = {1}id", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Posts WHERE BlogID = @blogid AND PostID = {parmPrefix}id"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { @@ -1295,7 +1295,7 @@ public override List FillPages() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT PageID FROM {0}Pages WHERE BlogID = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT PageID FROM {tablePrefix}Pages WHERE BlogID = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -1523,7 +1523,7 @@ public override List FillBlogRoll() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT BlogRollId, Title, Description, BlogUrl, FeedUrl, Xfn, SortIndex FROM {0}BlogRollItems WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT BlogRollId, Title, Description, BlogUrl, FeedUrl, Xfn, SortIndex FROM {tablePrefix}BlogRollItems WHERE BlogId = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -1668,7 +1668,7 @@ public override List FillCategories(Blog blog) { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT CategoryID, CategoryName, description, ParentID FROM {0}Categories WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT CategoryID, CategoryName, description, ParentID FROM {tablePrefix}Categories WHERE BlogId = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), blog.Id.ToString())); @@ -1840,7 +1840,7 @@ public override List FillReferrers() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT ReferrerId, ReferralDay, ReferrerUrl, ReferralCount, Url, IsSpam FROM {0}Referrers WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT ReferrerId, ReferralDay, ReferrerUrl, ReferralCount, Url, IsSpam FROM {tablePrefix}Referrers WHERE BlogId = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -1958,7 +1958,7 @@ public override StringCollection LoadPingServices() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT Link FROM {0}PingService WHERE BlogID = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT Link FROM {tablePrefix}PingService WHERE BlogID = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -1989,7 +1989,7 @@ public override void SavePingServices(StringCollection services) { if (services == null) { - throw new ArgumentNullException("services"); + throw new ArgumentNullException(nameof(services)); } using (var conn = this.CreateConnection()) @@ -1997,7 +1997,7 @@ public override void SavePingServices(StringCollection services) if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("DELETE FROM {0}PingService WHERE BlogID = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"DELETE FROM {tablePrefix}PingService WHERE BlogID = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); cmd.ExecuteNonQuery(); @@ -2075,7 +2075,7 @@ public override void SaveToDataStore(ExtensionType extensionType, string extensi { if (settings == null) { - throw new ArgumentNullException("settings"); + throw new ArgumentNullException(nameof(settings)); } // Save @@ -2164,7 +2164,7 @@ public override StringDictionary LoadSettings(Blog blog) { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT SettingName, SettingValue FROM {0}Settings WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT SettingName, SettingValue FROM {tablePrefix}Settings WHERE BlogId = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), blog.Id.ToString())); @@ -2195,14 +2195,14 @@ public override void SaveSettings(StringDictionary settings) { if (settings == null) { - throw new ArgumentNullException("settings"); + throw new ArgumentNullException(nameof(settings)); } using (var conn = this.CreateConnection()) { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("DELETE FROM {0}Settings WHERE BlogId = {1}blogid", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"DELETE FROM {tablePrefix}Settings WHERE BlogId = {parmPrefix}blogid")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); cmd.ExecuteNonQuery(); @@ -2239,7 +2239,7 @@ public override IDictionary> FillRights() { if (conn.HasConnection) { - var sqlQuery = string.Format("SELECT RightName FROM {0}Rights WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix); + var sqlQuery = $"SELECT RightName FROM {tablePrefix}Rights WHERE BlogId = {parmPrefix}blogid "; using (var cmd = conn.CreateTextCommand(sqlQuery)) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -2253,7 +2253,7 @@ public override IDictionary> FillRights() } // Get Right Roles. - cmd.CommandText = string.Format("SELECT RightName, Role FROM {0}RightRoles WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix); + cmd.CommandText = $"SELECT RightName, Role FROM {tablePrefix}RightRoles WHERE BlogId = {parmPrefix}blogid "; // don't need to add "blogid" parameter again since the same cmd is being used. using (var rdr = cmd.ExecuteReader()) @@ -2288,19 +2288,19 @@ public override void SaveRights(IEnumerable rights) { if (rights == null) { - throw new ArgumentNullException("rights"); + throw new ArgumentNullException(nameof(rights)); } using (var conn = this.CreateConnection()) { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("DELETE FROM {0}Rights WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"DELETE FROM {tablePrefix}Rights WHERE BlogId = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); cmd.ExecuteNonQuery(); - cmd.CommandText = string.Format("DELETE FROM {0}RightRoles WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix); + cmd.CommandText = $"DELETE FROM {tablePrefix}RightRoles WHERE BlogId = {parmPrefix}blogid "; cmd.ExecuteNonQuery(); foreach (var right in rights) @@ -2351,7 +2351,7 @@ public override List FillProfiles() { if (Blog.CurrentInstance.IsSiteAggregation) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT UserName FROM {0}Profiles GROUP BY UserName", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT UserName FROM {tablePrefix}Profiles GROUP BY UserName")) { using (var rdr = cmd.ExecuteReader()) { @@ -2364,7 +2364,7 @@ public override List FillProfiles() } else { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT UserName FROM {0}Profiles WHERE BlogID = {1}blogid GROUP BY UserName", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT UserName FROM {tablePrefix}Profiles WHERE BlogID = {parmPrefix}blogid GROUP BY UserName")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -2401,7 +2401,7 @@ public override AuthorProfile SelectProfile(string id) { if (Blog.CurrentInstance.IsSiteAggregation) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT SettingName, SettingValue FROM {0}Profiles WHERE UserName = {1}name", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT SettingName, SettingValue FROM {tablePrefix}Profiles WHERE UserName = {parmPrefix}name")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("name"), id)); @@ -2732,7 +2732,7 @@ public override List FillPackageFiles(string packageId) { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT PackageId, FileOrder, FilePath, IsDirectory FROM {0}PackageFiles ", this.tablePrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT PackageId, FileOrder, FilePath, IsDirectory FROM {tablePrefix}PackageFiles ")) { using (var rdr = cmd.ExecuteReader()) { @@ -2770,7 +2770,7 @@ public override List FillPackages() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT PackageId, Version FROM {0}Packages ", tablePrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT PackageId, Version FROM {tablePrefix}Packages ")) { using (var rdr = cmd.ExecuteReader()) { @@ -2801,7 +2801,7 @@ public override void DeletePackage(string packageId) { if (conn.HasConnection) { - var sqlQuery = string.Format("DELETE FROM {0}PackageFiles WHERE PackageId = {1}PackageId", this.tablePrefix, this.parmPrefix); + var sqlQuery = $"DELETE FROM {tablePrefix}PackageFiles WHERE PackageId = {parmPrefix}PackageId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { @@ -2809,7 +2809,7 @@ public override void DeletePackage(string packageId) cmd.ExecuteNonQuery(); } - sqlQuery = string.Format("DELETE FROM {0}Packages WHERE PackageId = {1}PackageId", this.tablePrefix, this.parmPrefix); + sqlQuery = $"DELETE FROM {tablePrefix}Packages WHERE PackageId = {parmPrefix}PackageId"; using (var cmd = conn.CreateTextCommand(sqlQuery)) { @@ -2992,7 +2992,7 @@ public override StringCollection LoadStopWords() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT StopWord FROM {0}StopWords WHERE BlogId = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT StopWord FROM {tablePrefix}StopWords WHERE BlogId = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -3035,7 +3035,7 @@ private DbConnectionHelper CreateConnection() /// private string FormatParamName(string parameterName) { - return String.Format("{0}{1}", this.parmPrefix, parameterName); + return $"{parmPrefix}{parameterName}"; } /// diff --git a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbConnectionHelper.cs b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbConnectionHelper.cs index 33c6f66e3..cdc042c42 100644 --- a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbConnectionHelper.cs +++ b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbConnectionHelper.cs @@ -1,11 +1,7 @@ using System; -using System.Collections.Generic; using System.Configuration; -using System.Configuration.Provider; using System.Data; using System.Data.Common; -using System.Linq; -using System.Text; namespace BlogEngine.Core.Providers { diff --git a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbMembershipProvider.cs b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbMembershipProvider.cs index f10a50e90..0851d2d03 100644 --- a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbMembershipProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbMembershipProvider.cs @@ -4,8 +4,6 @@ using System.Collections.Specialized; using System.Configuration; using System.Configuration.Provider; - using System.Data; - using System.Data.Common; using System.Web.Security; /// @@ -397,7 +395,7 @@ public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize { if (Blog.CurrentInstance.IsSiteAggregation) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT username, EmailAddress, lastLoginTime FROM {0}Users ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT username, EmailAddress, lastLoginTime FROM {tablePrefix}Users ")) { using (var rdr = cmd.ExecuteReader()) { @@ -410,7 +408,7 @@ public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize } else { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT username, EmailAddress, lastLoginTime FROM {0}Users WHERE BlogID = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT username, EmailAddress, lastLoginTime FROM {tablePrefix}Users WHERE BlogID = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -511,7 +509,7 @@ public override string GetUserNameByEmail(string email) { if (email == null) { - throw new ArgumentNullException("email"); + throw new ArgumentNullException(nameof(email)); } string userName = null; @@ -552,7 +550,7 @@ public override void Initialize(string name, NameValueCollection config) { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (string.IsNullOrEmpty(name)) @@ -638,7 +636,7 @@ public override void Initialize(string name, NameValueCollection config) var attr = config.GetKey(0); if (!string.IsNullOrEmpty(attr)) { - throw new ProviderException(string.Format("Unrecognized attribute: {0}", attr)); + throw new ProviderException($"Unrecognized attribute: {attr}"); } } } @@ -803,7 +801,7 @@ private DbConnectionHelper CreateConnection() /// private string FormatParamName(string parameterName) { - return string.Format("{0}{1}", this.parmPrefix, parameterName); + return $"{parmPrefix}{parameterName}"; } /// diff --git a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbRoleProvider.cs b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbRoleProvider.cs index 1ea254eb6..d44d396b9 100644 --- a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbRoleProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbRoleProvider.cs @@ -6,7 +6,6 @@ using System.Configuration; using System.Configuration.Provider; using System.Data; - using System.Data.Common; using System.Web.Security; /// @@ -205,7 +204,7 @@ public override string[] FindUsersInRole(string roleName, string usernameToMatch var parms = cmd.Parameters; parms.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); parms.Add(conn.CreateParameter(FormatParamName("role"), roleName)); - parms.Add(conn.CreateParameter(FormatParamName("name"), string.Format("{0}%", usernameToMatch))); + parms.Add(conn.CreateParameter(FormatParamName("name"), $"{usernameToMatch}%")); using (var rdr = cmd.ExecuteReader()) { @@ -238,7 +237,7 @@ public override string[] GetAllRoles() { if (conn.HasConnection) { - using (var cmd = conn.CreateTextCommand(string.Format("SELECT role FROM {0}Roles WHERE BlogID = {1}blogid ", this.tablePrefix, this.parmPrefix))) + using (var cmd = conn.CreateTextCommand($"SELECT role FROM {tablePrefix}Roles WHERE BlogID = {parmPrefix}blogid ")) { cmd.Parameters.Add(conn.CreateParameter(FormatParamName("blogid"), Blog.CurrentInstance.Id.ToString())); @@ -358,7 +357,7 @@ public override void Initialize(string name, NameValueCollection config) { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (String.IsNullOrEmpty(name)) @@ -416,7 +415,7 @@ public override void Initialize(string name, NameValueCollection config) var attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) { - throw new ProviderException(string.Format("Unrecognized attribute: {0}", attr)); + throw new ProviderException($"Unrecognized attribute: {attr}"); } } } @@ -577,7 +576,7 @@ private DbConnectionHelper CreateConnection() /// private string FormatParamName(string parameterName) { - return String.Format("{0}{1}", this.parmPrefix, parameterName); + return $"{parmPrefix}{parameterName}"; } #endregion diff --git a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/BlogFileSystemProviderCollection.cs b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/BlogFileSystemProviderCollection.cs index f908f8cef..d7b6addf9 100644 --- a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/BlogFileSystemProviderCollection.cs +++ b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/BlogFileSystemProviderCollection.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Configuration.Provider; namespace BlogEngine.Core.Providers @@ -39,12 +36,12 @@ public override void Add(ProviderBase provider) { if (provider == null) { - throw new ArgumentNullException("provider"); + throw new ArgumentNullException(nameof(provider)); } if (!(provider is BlogFileSystemProvider)) { - throw new ArgumentException("Invalid provider type", "provider"); + throw new ArgumentException("Invalid provider type", nameof(provider)); } base.Add(provider); diff --git a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/DbFileSystemProvider.cs b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/DbFileSystemProvider.cs index 597467628..3cffdf621 100644 --- a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/DbFileSystemProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/DbFileSystemProvider.cs @@ -38,7 +38,7 @@ public override void Initialize(string name, NameValueCollection config) { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (String.IsNullOrEmpty(name)) @@ -87,7 +87,7 @@ public override void Initialize(string name, NameValueCollection config) var attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) { - throw new ProviderException(string.Format("Unrecognized attribute: {0}", attr)); + throw new ProviderException($"Unrecognized attribute: {attr}"); } } } @@ -189,7 +189,7 @@ public override void DeleteDirectory(string VirtualPath) public override bool DirectoryExists(string VirtualPath) { VirtualPath = VirtualPath.VirtualPathToDbPath(); - return new FileSystem.FileStoreDb(this.connectionString).FileStoreDirectories.Where(x => x.FullPath.ToLower() == VirtualPath.ToLower() && x.BlogID == Blog.CurrentInstance.Id).Count() > 0; + return new FileSystem.FileStoreDb(this.connectionString).FileStoreDirectories.Any(x => x.FullPath.ToLower() == VirtualPath.ToLower() && x.BlogID == Blog.CurrentInstance.Id); } /// @@ -233,7 +233,7 @@ public override FileSystem.Directory GetDirectory(string VirtualPath, bool Creat var cPath = string.Empty; foreach (var pieces in newDirectoryPieces) { - cPath = string.Format("{0}/{1}", cPath, pieces); + cPath = $"{cPath}/{pieces}"; if (!DirectoryExists(cPath)) CreateDirectory(cPath); } diff --git a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/UNCFileSystemProvider.cs b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/UNCFileSystemProvider.cs index f9a4637a4..6f1dea0bb 100644 --- a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/UNCFileSystemProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/UNCFileSystemProvider.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Web.Hosting; using System.IO; @@ -28,7 +27,7 @@ public override void Initialize(string name, System.Collections.Specialized.Name { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (String.IsNullOrEmpty(name)) @@ -206,7 +205,7 @@ public override FileSystem.Directory GetDirectory(FileSystem.Directory BaseDirec { var aPath = VirtualPathToUNCPath(BaseDirectory.FullPath); var sysDirectory = new System.IO.DirectoryInfo(aPath); - return sysDirectory.GetDirectories().Select(x => GetDirectory(string.Format("{0}/{1}", BaseDirectory.FullPath, x.Name))); + return sysDirectory.GetDirectories().Select(x => GetDirectory($"{BaseDirectory.FullPath}/{x.Name}")); } @@ -220,7 +219,7 @@ public override FileSystem.Directory GetDirectory(FileSystem.Directory BaseDirec var aPath = VirtualPathToUNCPath(BaseDirectory.FullPath); var sysDirectory = new DirectoryInfo(aPath); - return sysDirectory.GetFiles().Where(x => x.Name.ToLower() != "thumbs.db").Select(x => GetFile(string.Format("{0}/{1}", BaseDirectory.FullPath, x.Name))); + return sysDirectory.GetFiles().Where(x => x.Name.ToLower() != "thumbs.db").Select(x => GetFile($"{BaseDirectory.FullPath}/{x.Name}")); } /// @@ -299,7 +298,7 @@ public override FileSystem.File UploadFile(byte[] FileBinary, string FileName, F /// the new file object public override FileSystem.File UploadFile(byte[] FileBinary, string FileName, FileSystem.Directory BaseDirectory, bool Overwrite) { - var virtualPath = string.Format("{0}/{1}", BaseDirectory.FullPath, FileName); + var virtualPath = $"{BaseDirectory.FullPath}/{FileName}"; if (FileExists(virtualPath)) if (Overwrite) DeleteFile(virtualPath); diff --git a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/XmlFileSystemProvider.cs b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/XmlFileSystemProvider.cs index cfed7a8f0..0c6b263ed 100644 --- a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/XmlFileSystemProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/XmlFileSystemProvider.cs @@ -28,7 +28,7 @@ private static string BlogAbsolutePath(string VirtualPath) private static string RelativeFilePath(string VirtualPath) { VirtualPath = VirtualPath.Replace("//","/").Trim(); - if (VirtualPath.ToLower().Contains(FileContainerRoot.ToLower())) + if (VirtualPath.ToLower().Contains(FileContainerRoot.ToLower()+"/") || VirtualPath.ToLower() == FileContainerRoot.ToLower()) return VirtualPath; // ex: Oct 18 2012, added this to handle the case on the File Manager where if @@ -180,7 +180,7 @@ public override FileSystem.Directory GetDirectory(FileSystem.Directory BaseDirec { var aPath = BlogAbsolutePath(BaseDirectory.FullPath); var sysDirectory = new DirectoryInfo(aPath); - return sysDirectory.GetDirectories().Select(x => GetDirectory(string.Format("{0}/{1}", BaseDirectory.FullPath, x.Name))); + return sysDirectory.GetDirectories().Select(x => GetDirectory($"{BaseDirectory.FullPath}/{x.Name}")); } @@ -193,7 +193,7 @@ public override FileSystem.Directory GetDirectory(FileSystem.Directory BaseDirec { var aPath = BlogAbsolutePath(BaseDirectory.FullPath); var sysDirectory = new DirectoryInfo(aPath); - return sysDirectory.GetFiles().Select(x => GetFile(string.Format("{0}/{1}", BaseDirectory.FullPath, x.Name))); + return sysDirectory.GetFiles().Select(x => GetFile($"{BaseDirectory.FullPath}/{x.Name}")); } /// @@ -272,7 +272,7 @@ public override FileSystem.File UploadFile(byte[] FileBinary, string FileName, F /// the new file object public override FileSystem.File UploadFile(byte[] FileBinary, string FileName, FileSystem.Directory BaseDirectory, bool Overwrite) { - var virtualPath = RelativeFilePath(string.Format("{0}/{1}", BaseDirectory.FullPath, FileName)); + var virtualPath = RelativeFilePath($"{BaseDirectory.FullPath}/{FileName}"); if (FileExists(virtualPath)) if (Overwrite) DeleteFile(virtualPath); diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Blogs.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Blogs.cs index 6fecfaadc..2f45e6a03 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Blogs.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Blogs.cs @@ -3,10 +3,7 @@ using System.Linq; using System.Text; using System.IO; -using System.Web; using System.Xml; -using System.Web.Hosting; -using System.Globalization; namespace BlogEngine.Core.Providers { diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Categories.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Categories.cs index bb8d644fb..3636fe70a 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Categories.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Categories.cs @@ -151,7 +151,7 @@ public override void UpdateCategory(Category category) private void WriteToFile() { var categories = Category.Categories; - var fileName = string.Format("{0}categories.xml", this.Folder); + var fileName = $"{Folder}categories.xml"; using (var writer = new XmlTextWriter(fileName, Encoding.UTF8)) { diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/CustomFields.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/CustomFields.cs index f5cd16ff3..1dc81b107 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/CustomFields.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/CustomFields.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; using System.Text; diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/DataStore.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/DataStore.cs index 090699d5a..f46bffe0a 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/DataStore.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/DataStore.cs @@ -12,7 +12,6 @@ namespace BlogEngine.Core.Providers { using System; using System.IO; - using System.Linq; using System.Web.Hosting; using System.Xml.Serialization; @@ -129,7 +128,7 @@ private static string StorageLocation(ExtensionType extensionType) result = Path.Combine(Blog.CurrentInstance.StorageLocation, "datastore", "themes"); break; default: - throw new NotSupportedException(string.Format("Unknown extension type: {0}", extensionType)); + throw new NotSupportedException($"Unknown extension type: {extensionType}"); } string mappedResult = HostingEnvironment.MapPath(result); @@ -142,7 +141,7 @@ private static string StorageLocation(ExtensionType extensionType) if (string.IsNullOrEmpty(mappedResult)) { - throw new InvalidOperationException(string.Format("Could not map folder {0} for extension type {1}", result, extensionType)); + throw new InvalidOperationException($"Could not map folder {result} for extension type {extensionType}"); } return mappedResult; @@ -160,7 +159,7 @@ private static string StorageLocation(ExtensionType extensionType) /// private static string ExtensionLocation(ExtensionType extensionType, string extensionId) { - return Path.Combine(StorageLocation(extensionType), string.Format("{0}.xml", extensionId)); + return Path.Combine(StorageLocation(extensionType), $"{extensionId}.xml"); } #endregion diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Packaging.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Packaging.cs index ccd5c279f..d953a7c82 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Packaging.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Packaging.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Pages.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Pages.cs index e7eb26a8b..2c6e8e6c6 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Pages.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Pages.cs @@ -24,7 +24,7 @@ public partial class XmlBlogProvider : BlogProvider /// The page to delete. public override void DeletePage(Page page) { - var fileName = string.Format("{0}pages{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, page.Id); + var fileName = $"{Folder}pages{Path.DirectorySeparatorChar}{page.Id}.xml"; if (File.Exists(fileName)) { File.Delete(fileName); @@ -44,7 +44,7 @@ public override void DeletePage(Page page) /// public override List FillPages() { - var folder = string.Format("{0}pages{1}", this.Folder, Path.DirectorySeparatorChar); + var folder = $"{Folder}pages{Path.DirectorySeparatorChar}"; if (Directory.Exists(folder)) { return (from file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly) @@ -64,12 +64,12 @@ select info.Name.Replace(".xml", string.Empty) into id /// The page to insert. public override void InsertPage(Page page) { - if (!Directory.Exists(string.Format("{0}pages", this.Folder))) + if (!Directory.Exists($"{Folder}pages")) { - Directory.CreateDirectory(string.Format("{0}pages", this.Folder)); + Directory.CreateDirectory($"{Folder}pages"); } - var fileName = string.Format("{0}pages{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, page.Id); + var fileName = $"{Folder}pages{Path.DirectorySeparatorChar}{page.Id}.xml"; var settings = new XmlWriterSettings { Indent = true }; using (var writer = XmlWriter.Create(fileName, settings)) @@ -106,7 +106,7 @@ public override void InsertPage(Page page) /// The Page object. public override Page SelectPage(Guid id) { - var fileName = string.Format("{0}pages{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, id); + var fileName = $"{Folder}pages{Path.DirectorySeparatorChar}{id}.xml"; var doc = new XmlDocument(); doc.Load(fileName); diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/PingServices.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/PingServices.cs index f9d9cdcb8..a181f86d8 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/PingServices.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/PingServices.cs @@ -53,7 +53,7 @@ public override void SavePingServices(StringCollection services) { if (services == null) { - throw new ArgumentNullException("services"); + throw new ArgumentNullException(nameof(services)); } var fileName = this.Folder + "pingservices.xml"; diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Posts.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Posts.cs index 32183bc39..df6aa982e 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Posts.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Posts.cs @@ -54,7 +54,7 @@ internal string GetFolder(Blog blog) /// public override void DeletePost(Post post) { - var fileName = string.Format("{0}posts{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, post.Id); + var fileName = $"{Folder}posts{Path.DirectorySeparatorChar}{post.Id}.xml"; if (File.Exists(fileName)) { File.Delete(fileName); @@ -94,10 +94,10 @@ into id /// public override void InsertPost(Post post) { - if (!Directory.Exists(string.Format("{0}posts", this.Folder))) - Directory.CreateDirectory(string.Format("{0}posts", this.Folder)); + if (!Directory.Exists($"{Folder}posts")) + Directory.CreateDirectory($"{Folder}posts"); - var fileName = string.Format("{0}posts{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, post.Id); + var fileName = $"{Folder}posts{Path.DirectorySeparatorChar}{post.Id}.xml"; var settings = new XmlWriterSettings { Indent = true }; var ms = new MemoryStream(); @@ -215,7 +215,7 @@ public override void InsertPost(Post post) /// public override Post SelectPost(Guid id) { - var fileName = string.Format("{0}posts{1}{2}.xml", this.Folder, Path.DirectorySeparatorChar, id); + var fileName = $"{Folder}posts{Path.DirectorySeparatorChar}{id}.xml"; var post = new Post(); var doc = new XmlDocument(); doc.Load(fileName); diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Profiles.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Profiles.cs index 722aee98e..a9fdfd85f 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Profiles.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Profiles.cs @@ -21,7 +21,7 @@ public partial class XmlBlogProvider : BlogProvider /// public override void DeleteProfile(AuthorProfile profile) { - var fileName = string.Format("{0}profiles{1}{2}.xml", GetFolder(profile.Blog), Path.DirectorySeparatorChar, profile.Id); + var fileName = $"{GetFolder(profile.Blog)}profiles{Path.DirectorySeparatorChar}{profile.Id}.xml"; if (File.Exists(fileName)) { File.Delete(fileName); @@ -63,7 +63,7 @@ public override List FillProfiles() foreach (Blog blog in blogs) { - var folder = string.Format("{0}profiles{1}", GetFolder(blog), Path.DirectorySeparatorChar); + var folder = $"{GetFolder(blog)}profiles{Path.DirectorySeparatorChar}"; if (!Directory.Exists(folder)) continue; @@ -87,12 +87,12 @@ into username /// public override void InsertProfile(AuthorProfile profile) { - if (!Directory.Exists(string.Format("{0}profiles", GetFolder(profile.Blog)))) + if (!Directory.Exists($"{GetFolder(profile.Blog)}profiles")) { - Directory.CreateDirectory(string.Format("{0}profiles", GetFolder(profile.Blog))); + Directory.CreateDirectory($"{GetFolder(profile.Blog)}profiles"); } - var fileName = string.Format("{0}profiles{1}{2}.xml", GetFolder(profile.Blog), Path.DirectorySeparatorChar, profile.Id); + var fileName = $"{GetFolder(profile.Blog)}profiles{Path.DirectorySeparatorChar}{profile.Id}.xml"; var settings = new XmlWriterSettings { Indent = true }; using (var writer = XmlWriter.Create(fileName, settings)) @@ -170,7 +170,7 @@ public override void UpdateProfile(AuthorProfile profile) AuthorProfile SelectProfile(string id, Blog blog) { - var fileName = string.Format("{0}profiles{1}{2}.xml", GetFolder(blog), Path.DirectorySeparatorChar, id); + var fileName = $"{GetFolder(blog)}profiles{Path.DirectorySeparatorChar}{id}.xml"; if (blog.IsSiteAggregation && !blog.IsPrimary) fileName = Path.Combine(BlogConfig.StorageLocation, "blogs", blog.Name, "profiles", id + ".xml"); @@ -179,7 +179,7 @@ AuthorProfile SelectProfile(string id, Blog blog) if (!File.Exists(fileName)) { - Utils.Log(string.Format("XmlBlogProvider: can not load profile from \"{0}\"", fileName)); + Utils.Log($"XmlBlogProvider: can not load profile from \"{fileName}\""); return null; } diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Referrers.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Referrers.cs index 2a96a638d..5bc180d93 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Referrers.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Referrers.cs @@ -163,7 +163,7 @@ private static IEnumerable GetReferrersFromFile(FileInfo file, DateTim private void WriteReferrerFile(List referrers, DateTime day) { var folder = Path.Combine(this.Folder, "log"); - var fileName = Path.Combine(folder, string.Format("{0}.xml", day.ToString("yyyy.MM.dd"))); + var fileName = Path.Combine(folder, $"{day.ToString("yyyy.MM.dd")}.xml"); var dirInfo = new DirectoryInfo(folder); if (!dirInfo.Exists) { diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Rights.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Rights.cs index 26ada4828..5080f9550 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Rights.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Rights.cs @@ -3,13 +3,8 @@ using System; using System.Collections.Generic; using System.IO; - using System.Linq; - using System.Text; using System.Xml; using System.Security.Permissions; - using System.Web; - using System.Web.Hosting; - using System.Web.Security; /// /// A storage provider for BlogEngine that uses XML files. @@ -26,7 +21,7 @@ public partial class XmlBlogProvider : BlogProvider /// public override IDictionary> FillRights() { - var fullyQualifiedPath = string.Format("{0}rights.xml", this.Folder); + var fullyQualifiedPath = $"{Folder}rights.xml"; //var fullyQualifiedPath = // VirtualPathUtility.Combine( @@ -78,7 +73,7 @@ public override IDictionary> FillRights() /// public override void SaveRights(IEnumerable rights) { - var fileName = string.Format("{0}rights.xml", this.Folder); + var fileName = $"{Folder}rights.xml"; var settings = new XmlWriterSettings { Indent = true }; diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Settings.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Settings.cs index 854650611..e97535726 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Settings.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Settings.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Specialized; using System.Web; - using System.Web.Configuration; using System.Xml; /// @@ -23,7 +22,7 @@ public partial class XmlBlogProvider : BlogProvider /// A StringDictionary. public override StringDictionary LoadSettings(Blog blog) { - var filename = HttpContext.Current.Server.MapPath(string.Format("{0}settings.xml", blog.StorageLocation)); + var filename = HttpContext.Current.Server.MapPath($"{blog.StorageLocation}settings.xml"); var dic = new StringDictionary(); var doc = new XmlDocument(); @@ -54,10 +53,10 @@ public override void SaveSettings(StringDictionary settings) { if (settings == null) { - throw new ArgumentNullException("settings"); + throw new ArgumentNullException(nameof(settings)); } - var filename = string.Format("{0}settings.xml", this.Folder); + var filename = $"{Folder}settings.xml"; var writerSettings = new XmlWriterSettings { Indent = true }; // ------------------------------------------------------------ diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/StopWords.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/StopWords.cs index 47173b01f..9742992cf 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/StopWords.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/StopWords.cs @@ -23,7 +23,7 @@ public partial class XmlBlogProvider : BlogProvider /// public override StringCollection LoadStopWords() { - var fileName = string.Format("{0}stopwords.txt", this.Folder); + var fileName = $"{Folder}stopwords.txt"; if (!File.Exists(fileName)) { return new StringCollection(); diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlMembershipProvider.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlMembershipProvider.cs index dc37351c4..8d93fb2b4 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlMembershipProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlMembershipProvider.cs @@ -10,7 +10,6 @@ using System.Web; using System.Web.Hosting; using System.Web.Security; - using System.Web.Configuration; using System.Xml; using System.IO; @@ -538,7 +537,7 @@ public override MembershipUser GetUser(object providerUserKey, bool userIsOnline { if (providerUserKey == null) { - throw new ArgumentNullException("providerUserKey"); + throw new ArgumentNullException(nameof(providerUserKey)); } var doc = new XmlDocument(); @@ -566,7 +565,7 @@ public override string GetUserNameByEmail(string email) { if (email == null) { - throw new ArgumentNullException("email"); + throw new ArgumentNullException(nameof(email)); } var doc = new XmlDocument(); @@ -595,7 +594,7 @@ public override void Initialize(string name, NameValueCollection config) { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (string.IsNullOrEmpty(name)) @@ -658,7 +657,7 @@ public override void Initialize(string name, NameValueCollection config) var attr = config.GetKey(0); if (!string.IsNullOrEmpty(attr)) { - throw new ProviderException(string.Format("Unrecognized attribute: {0}", attr)); + throw new ProviderException($"Unrecognized attribute: {attr}"); } } } @@ -852,7 +851,7 @@ private void ReadMembershipDataStore() if (!File.Exists(path)) { - Utils.Log(string.Format("XmlMembershipProvider: can not read users from file \"{0}\"", path)); + Utils.Log($"XmlMembershipProvider: can not read users from file \"{path}\""); } ReadFromFile(path, b.Id); diff --git a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlRoleProvider.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlRoleProvider.cs index 94a2caac0..9a3f37592 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlRoleProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlRoleProvider.cs @@ -12,7 +12,6 @@ using System.Web; using System.Web.Hosting; using System.Web.Security; - using System.Web.Configuration; using System.Xml; @@ -273,7 +272,7 @@ public override void Initialize(string name, NameValueCollection config) { if (config == null) { - throw new ArgumentNullException("config"); + throw new ArgumentNullException(nameof(config)); } if (string.IsNullOrEmpty(name)) @@ -328,7 +327,7 @@ public override void Initialize(string name, NameValueCollection config) var attr = config.GetKey(0); if (!string.IsNullOrEmpty(attr)) { - throw new ProviderException(string.Format("Unrecognized attribute: {0}", attr)); + throw new ProviderException($"Unrecognized attribute: {attr}"); } } } @@ -412,9 +411,9 @@ public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames /// public override bool RoleExists(string roleName) { - if (Utils.StringIsNullOrWhitespace(roleName)) + if (String.IsNullOrWhiteSpace(roleName)) { - throw new ArgumentNullException("roleName"); + throw new ArgumentNullException(nameof(roleName)); } else { diff --git a/BlogEngine/BlogEngine.Core/Referrer.cs b/BlogEngine/BlogEngine.Core/Referrer.cs index 0b9a8562f..70f732707 100644 --- a/BlogEngine/BlogEngine.Core/Referrer.cs +++ b/BlogEngine/BlogEngine.Core/Referrer.cs @@ -264,8 +264,8 @@ public override string ToString() /// public int CompareTo(Referrer other) { - var compareThis = string.Format("{0} {1}", this.ReferrerUrl, this.Url); - var compareOther = string.Format("{0} {1}", other.ReferrerUrl, other.Url); + var compareThis = $"{ReferrerUrl} {Url}"; + var compareOther = $"{other.ReferrerUrl} {other.Url}"; return compareThis.CompareTo(compareOther); } diff --git a/BlogEngine/BlogEngine.Core/RemoteFile.cs b/BlogEngine/BlogEngine.Core/RemoteFile.cs index e960569e2..a03ae30df 100644 --- a/BlogEngine/BlogEngine.Core/RemoteFile.cs +++ b/BlogEngine/BlogEngine.Core/RemoteFile.cs @@ -38,7 +38,7 @@ internal RemoteFile(Uri filePath, bool ignoreRemoteDownloadSettings) { if (filePath == null) { - throw new ArgumentNullException("filePath"); + throw new ArgumentNullException(nameof(filePath)); } this.url = filePath; diff --git a/BlogEngine/BlogEngine.Core/Role.cs b/BlogEngine/BlogEngine.Core/Role.cs index 159f657bd..31c571e05 100644 --- a/BlogEngine/BlogEngine.Core/Role.cs +++ b/BlogEngine/BlogEngine.Core/Role.cs @@ -1,8 +1,6 @@ namespace BlogEngine.Core { using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Linq; /// /// The role class. @@ -47,7 +45,7 @@ public Role(string name, List userNames) { if (userNames == null) { - throw new System.ArgumentNullException("userNames"); + throw new System.ArgumentNullException(nameof(userNames)); } else { diff --git a/BlogEngine/BlogEngine.Core/Services/Compilation/BaseServerObjectExpressionBuilder.cs b/BlogEngine/BlogEngine.Core/Services/Compilation/BaseServerObjectExpressionBuilder.cs index f18a05899..8c8e811d6 100644 --- a/BlogEngine/BlogEngine.Core/Services/Compilation/BaseServerObjectExpressionBuilder.cs +++ b/BlogEngine/BlogEngine.Core/Services/Compilation/BaseServerObjectExpressionBuilder.cs @@ -127,7 +127,7 @@ public object GetRequestedValue(string key, Type targetType, string propertyName if (value == null) { throw new InvalidOperationException( - string.Format("{0} field '{1}' not found.", this.SourceObjectName, key)); + $"{SourceObjectName} field '{key}' not found."); } // If the value is being assigned to a control property we may need to convert it @@ -141,11 +141,7 @@ public object GetRequestedValue(string key, Type targetType, string propertyName if (propDesc.Converter.CanConvertFrom(value.GetType()) == false) { throw new InvalidOperationException( - string.Format( - "{0} value '{1}' cannot be converted to type {2}.", - this.SourceObjectName, - key, - propDesc.PropertyType)); + $"{SourceObjectName} value '{key}' cannot be converted to type {propDesc.PropertyType}."); } return propDesc.Converter.ConvertFrom(value); diff --git a/BlogEngine/BlogEngine.Core/Services/Compilation/LinqLengthExpressionBuilder.cs b/BlogEngine/BlogEngine.Core/Services/Compilation/LinqLengthExpressionBuilder.cs index 245b8cb38..401ae7d97 100644 --- a/BlogEngine/BlogEngine.Core/Services/Compilation/LinqLengthExpressionBuilder.cs +++ b/BlogEngine/BlogEngine.Core/Services/Compilation/LinqLengthExpressionBuilder.cs @@ -72,7 +72,7 @@ private static string AfterLast(string value, string last) { if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } return value.Substring(value.LastIndexOf(last) + last.Length); @@ -94,12 +94,12 @@ private static string BeforeLast(string value, string last) { if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if (last == null) { - throw new ArgumentNullException("last"); + throw new ArgumentNullException(nameof(last)); } return value.Substring(0, value.LastIndexOf(last)); @@ -124,7 +124,7 @@ private static string BetweenFirst(string value, string startText, string endTex { if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } var start = value.IndexOf(startText, StringComparison.OrdinalIgnoreCase) + startText.Length; diff --git a/BlogEngine/BlogEngine.Core/Services/Compilation/ReflectExpressionBuilder.cs b/BlogEngine/BlogEngine.Core/Services/Compilation/ReflectExpressionBuilder.cs index d15c212f7..ad2597746 100644 --- a/BlogEngine/BlogEngine.Core/Services/Compilation/ReflectExpressionBuilder.cs +++ b/BlogEngine/BlogEngine.Core/Services/Compilation/ReflectExpressionBuilder.cs @@ -148,7 +148,7 @@ public override object ParseExpression(string expression, Type propertyType, Exp if (!parsed) { - throw new HttpException(String.Format("Invalid Reflect expression - '{0}'.", expression)); + throw new HttpException($"Invalid Reflect expression - '{expression}'."); } // now validate the expression fields @@ -188,9 +188,7 @@ private static string ValidateExpression(string typeName, string memberName) // if type was not resolved then raise error if (resolvedType == null) { - var message = - String.Format( - "Reflect Expression: Type '{0}' could not be resolved in the current context.", typeName); + var message = $"Reflect Expression: Type '{typeName}' could not be resolved in the current context."; throw new HttpCompileException(message); } @@ -201,8 +199,7 @@ private static string ValidateExpression(string typeName, string memberName) bindingValue = memberName; if (!resolvedType.GetMember(memberName).Any()) { - var message = String.Format( - "Reflect Expression: Member '{0}' for type '{1}' does not exist.", memberName, typeName); + var message = $"Reflect Expression: Member '{memberName}' for type '{typeName}' does not exist."; throw new HttpCompileException(message); } } diff --git a/BlogEngine/BlogEngine.Core/Services/FileSystem/File.cs b/BlogEngine/BlogEngine.Core/Services/FileSystem/File.cs index f3d8e1804..e7efc8444 100644 --- a/BlogEngine/BlogEngine.Core/Services/FileSystem/File.cs +++ b/BlogEngine/BlogEngine.Core/Services/FileSystem/File.cs @@ -206,7 +206,7 @@ public string FileDescription { get { - return string.Format("{0} ({1})", this.Name, SizeFormat(this.FileSize, "N")); + return $"{Name} ({SizeFormat(FileSize, "N")})"; } } @@ -218,7 +218,7 @@ public string FileDownloadPath { get { - return string.Format("{0}file.axd?file={1}", Utils.RelativeWebRoot, this.SafeFilePath); + return $"{Utils.RelativeWebRoot}file.axd?file={SafeFilePath}"; } } diff --git a/BlogEngine/BlogEngine.Core/Services/FileSystem/FileStoreDb.cs b/BlogEngine/BlogEngine.Core/Services/FileSystem/FileStoreDb.cs index 6876724d3..e36b0b223 100644 --- a/BlogEngine/BlogEngine.Core/Services/FileSystem/FileStoreDb.cs +++ b/BlogEngine/BlogEngine.Core/Services/FileSystem/FileStoreDb.cs @@ -13,11 +13,6 @@ namespace BlogEngine.Core.FileSystem { using System.Data.Linq; using System.Data.Linq.Mapping; - using System.Data; - using System.Collections.Generic; - using System.Reflection; - using System.Linq; - using System.Linq.Expressions; using System.ComponentModel; using System; diff --git a/BlogEngine/BlogEngine.Core/Services/FileSystem/Image.cs b/BlogEngine/BlogEngine.Core/Services/FileSystem/Image.cs index b40945823..991a0458c 100644 --- a/BlogEngine/BlogEngine.Core/Services/FileSystem/Image.cs +++ b/BlogEngine/BlogEngine.Core/Services/FileSystem/Image.cs @@ -100,7 +100,7 @@ public string ImageUrl { get { - return string.Format("{0}image.axd?picture={1}", Utils.RelativeWebRoot, this.SafeFilePath); + return $"{Utils.RelativeWebRoot}image.axd?picture={SafeFilePath}"; } } diff --git a/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/Trackback.cs b/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/Trackback.cs index b3ed06f74..2162ddf9a 100644 --- a/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/Trackback.cs +++ b/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/Trackback.cs @@ -42,7 +42,7 @@ public static bool Send(TrackbackMessage message) if (message == null) { - throw new ArgumentNullException("message"); + throw new ArgumentNullException(nameof(message)); } OnSending(message.UrlToNotifyTrackback); diff --git a/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/TrackbackMessage.cs b/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/TrackbackMessage.cs index 1955b2680..8281229e0 100644 --- a/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/TrackbackMessage.cs +++ b/BlogEngine/BlogEngine.Core/Services/Messaging/Ping/TrackbackMessage.cs @@ -26,7 +26,7 @@ public TrackbackMessage(IPublishable item, Uri urlToNotifyTrackback, Uri itemUrl { if (item == null) { - throw new ArgumentNullException("item"); + throw new ArgumentNullException(nameof(item)); } this.Title = item.Title; diff --git a/BlogEngine/BlogEngine.Core/Services/Messaging/Protection/CommentHandlers.cs b/BlogEngine/BlogEngine.Core/Services/Messaging/Protection/CommentHandlers.cs index 064806b67..cd8bcfbe3 100644 --- a/BlogEngine/BlogEngine.Core/Services/Messaging/Protection/CommentHandlers.cs +++ b/BlogEngine/BlogEngine.Core/Services/Messaging/Protection/CommentHandlers.cs @@ -6,7 +6,6 @@ using System.Globalization; using System.Linq; using System.Reflection; - using System.Threading; using BlogEngine.Core.Web.Extensions; @@ -75,7 +74,7 @@ public static void AddItemToFilter(string subject, string value, bool isspam) // remove old filter foreach (var par in filters.Parameters) { - log += string.Format(":{0}", par.Values[indx]); + log += $":{par.Values[indx]}"; par.DeleteValue(indx); } @@ -92,7 +91,7 @@ public static void AddItemToFilter(string subject, string value, bool isspam) filters.AddValues(f); ExtensionManager.SaveSettings("MetaExtension", filters); - Utils.Log(string.Format("{0} added to {1} list: {2}", subject, blackWhiteList, value)); + Utils.Log($"{subject} added to {blackWhiteList} list: {value}"); } /// @@ -539,8 +538,7 @@ private static void RunCustomModerators(Comment comment) comment.IsApproved = false; comment.ModeratedBy = filterName; - Utils.Log( - string.Format("Custom filter [{0}] - found spam; comment id: {1}", filterName, comment.Id)); + Utils.Log($"Custom filter [{filterName}] - found spam; comment id: {comment.Id}"); UpdateCustomFilter(filterName, false); break; diff --git a/BlogEngine/BlogEngine.Core/Services/Packaging/FileSystem.cs b/BlogEngine/BlogEngine.Core/Services/Packaging/FileSystem.cs index 68058e4ee..9408d6605 100644 --- a/BlogEngine/BlogEngine.Core/Services/Packaging/FileSystem.cs +++ b/BlogEngine/BlogEngine.Core/Services/Packaging/FileSystem.cs @@ -8,7 +8,6 @@ using System.Text; using System.Text.RegularExpressions; using System.Web; -using System.Web.Hosting; using System.Xml; namespace BlogEngine.Core.Packaging @@ -80,7 +79,7 @@ public static List LoadExtensions() LocalVersion = x.Version, OnlineVersion = onlineVersion, Authors = x.Author, - IconUrl = string.Format("{0}Content/images/blog/ext.png", Utils.ApplicationRelativeWebRoot), + IconUrl = $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/ext.png", Enabled = x.Enabled, Priority = x.Priority, SettingsUrl = x.Settings.Count > 0 ? adminPage : "" @@ -105,11 +104,9 @@ public static List InstallPackage(NuGet.IPackage package) { var packageFiles = new List(); - var content = HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot + - string.Format("App_Data/packages/{0}.{1}/content", package.Id, package.Version)); + var content = HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot + $"App_Data/packages/{package.Id}.{package.Version}/content"); - var lib = HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot + - string.Format("App_Data/packages/{0}.{1}/lib", package.Id, package.Version)); + var lib = HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot + $"App_Data/packages/{package.Id}.{package.Version}/lib"); var root = HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot); var bin = HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot + "bin"); @@ -156,7 +153,7 @@ public static void UninstallPackage(string pkgId) if (installedFiles.Count == 0) { - Utils.Log(string.Format("Can not find any files installed for package: {0}", pkgId)); + Utils.Log($"Can not find any files installed for package: {pkgId}"); throw new ApplicationException("No files to uninstall"); } @@ -200,10 +197,10 @@ public static void UninstallPackage(string pkgId) if (pkg != null && !string.IsNullOrWhiteSpace(pkg.OnlineVersion)) { - var pkgDir = string.Format("{0}.{1}", pkgId, pkg.OnlineVersion); + var pkgDir = $"{pkgId}.{pkg.OnlineVersion}"; // clean up removing installed version - pkgDir = HttpContext.Current.Server.MapPath(string.Format("{0}App_Data/packages/{1}", Utils.ApplicationRelativeWebRoot, pkgDir)); + pkgDir = HttpContext.Current.Server.MapPath($"{Utils.ApplicationRelativeWebRoot}App_Data/packages/{pkgDir}"); if (Directory.Exists(pkgDir)) { ForceDeleteDirectory(pkgDir); @@ -216,7 +213,7 @@ public static void UninstallPackage(string pkgId) static List GetThemes() { var installedThemes = new List(); - var path = HttpContext.Current.Server.MapPath(string.Format("{0}Custom/Themes/", Utils.ApplicationRelativeWebRoot)); + var path = HttpContext.Current.Server.MapPath($"{Utils.ApplicationRelativeWebRoot}Custom/Themes/"); foreach (var p in from d in Directory.GetDirectories(path) let index = d.LastIndexOf(Path.DirectorySeparatorChar) + 1 @@ -251,7 +248,7 @@ into themeId select GetPackageManifest(themeId, Constants.Theme) ?? static List GetWidgets() { var installedWidgets = new List(); - var path = HttpContext.Current.Server.MapPath(string.Format("{0}Custom/Widgets/", Utils.ApplicationRelativeWebRoot)); + var path = HttpContext.Current.Server.MapPath($"{Utils.ApplicationRelativeWebRoot}Custom/Widgets/"); foreach (var p in from d in Directory.GetDirectories(path) let index = d.LastIndexOf(Path.DirectorySeparatorChar) + 1 @@ -394,8 +391,7 @@ static string DefaultIconUrl(Package pkg) foreach (var img in validImages) { - var url = string.Format("{0}{1}/{2}/{3}", - Utils.ApplicationRelativeWebRoot, pkgDir, pkg.Id, img); + var url = $"{Utils.ApplicationRelativeWebRoot}{pkgDir}/{pkg.Id}/{img}"; url = url.Replace("/themes", "/Custom/Themes"); url = url.Replace("/widgets", "/Custom/Widgets"); @@ -423,7 +419,7 @@ static void ReplaceInFile(string filePath, string searchText, string replaceText if (cnt > 0 && cnt != content.Length) { - Utils.Log(string.Format("Package Installer: replacing in {0} from {1} to {2}", filePath, searchText, replaceText)); + Utils.Log($"Package Installer: replacing in {filePath} from {searchText} to {replaceText}"); } StreamWriter writer = new StreamWriter(filePath); @@ -452,7 +448,7 @@ static string PackageType(List files) /// Version number public static string GetInstalledVersion(string pkgId) { - var pkg = BlogService.InstalledFromGalleryPackages().Where(p => p.PackageId == pkgId).FirstOrDefault(); + var pkg = BlogService.InstalledFromGalleryPackages().FirstOrDefault(p => p.PackageId == pkgId); return pkg == null ? "" : pkg.Version; } @@ -461,8 +457,8 @@ static Package GetPackageManifest(string id, string pkgType) var jp = new Package { Id = id, PackageType = pkgType }; var pkgUrl = pkgType == "Theme" ? - string.Format("{0}Custom/Themes/{1}/theme.xml", Utils.ApplicationRelativeWebRoot, id) : - string.Format("{0}Custom/Widgets/{1}/widget.xml", Utils.ApplicationRelativeWebRoot, id); + $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{id}/theme.xml" + : $"{Utils.ApplicationRelativeWebRoot}Custom/Widgets/{id}/widget.xml"; var pkgPath = HttpContext.Current.Server.MapPath(pkgUrl); try @@ -515,10 +511,10 @@ public static void CreateManifestIfNotExists(NuGet.IPackage package, List packages) if (string.IsNullOrEmpty(jp.IconUrl)) jp.IconUrl = DefaultThumbnail(""); - if (extras != null && extras.Count() > 0) + if (extras != null && extras.Any()) { - var extra = extras.Where(e => e.Id.ToLower() == pkg.Id.ToLower() + "." + pkg.Version).FirstOrDefault(); + var extra = extras.FirstOrDefault(e => e.Id.ToLower() == pkg.Id.ToLower() + "." + pkg.Version); if (extra != null) { @@ -155,13 +155,13 @@ static string DefaultThumbnail(string packageType) switch (packageType) { case "Theme": - return string.Format("{0}Content/images/blog/Theme.png", Utils.ApplicationRelativeWebRoot); + return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/Theme.png"; case "Extension": - return string.Format("{0}Content/images/blog/ext.png", Utils.ApplicationRelativeWebRoot); + return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/ext.png"; case "Widget": - return string.Format("{0}Content/images/blog/Widget.png", Utils.ApplicationRelativeWebRoot); + return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/Widget.png"; } - return string.Format("{0}Content/images/blog/pkg.png", Utils.ApplicationRelativeWebRoot); + return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/pkg.png"; } #endregion diff --git a/BlogEngine/BlogEngine.Core/Services/Packaging/InstalledPackage.cs b/BlogEngine/BlogEngine.Core/Services/Packaging/InstalledPackage.cs index 7c42fcd83..e67cfd8f4 100644 --- a/BlogEngine/BlogEngine.Core/Services/Packaging/InstalledPackage.cs +++ b/BlogEngine/BlogEngine.Core/Services/Packaging/InstalledPackage.cs @@ -1,6 +1,4 @@ -using System; - -namespace BlogEngine.Core.Packaging +namespace BlogEngine.Core.Packaging { /// /// Locally installed gallery package diff --git a/BlogEngine/BlogEngine.Core/Services/Packaging/Installer.cs b/BlogEngine/BlogEngine.Core/Services/Packaging/Installer.cs index fc0b9f1f7..ee8174ac7 100644 --- a/BlogEngine/BlogEngine.Core/Services/Packaging/Installer.cs +++ b/BlogEngine/BlogEngine.Core/Services/Packaging/Installer.cs @@ -56,7 +56,7 @@ public static bool InstallPackage(string pkgId) CustomFieldsParser.ClearCache(); - Utils.Log(string.Format("Installed package {0} by {1}", pkgId, Security.CurrentUser.Identity.Name)); + Utils.Log($"Installed package {pkgId} by {Security.CurrentUser.Identity.Name}"); } catch (Exception ex) { @@ -90,11 +90,11 @@ public static bool UninstallPackage(string pkgId) // reset cache Blog.CurrentInstance.Cache.Remove(Constants.CacheKey); - Utils.Log(string.Format("Uninstalled package {0} by {1}", pkgId, Security.CurrentUser.Identity.Name)); + Utils.Log($"Uninstalled package {pkgId} by {Security.CurrentUser.Identity.Name}"); } catch (Exception ex) { - Utils.Log(string.Format("Error unistalling package {0}: {1}"), pkgId, ex.Message); + Utils.Log($"Error unistalling package {pkgId}: {ex.Message}"); throw; } diff --git a/BlogEngine/BlogEngine.Core/Services/Packaging/Pager.cs b/BlogEngine/BlogEngine.Core/Services/Packaging/Pager.cs index 82b6347b2..4df4d8561 100644 --- a/BlogEngine/BlogEngine.Core/Services/Packaging/Pager.cs +++ b/BlogEngine/BlogEngine.Core/Services/Packaging/Pager.cs @@ -83,7 +83,7 @@ public PagerItem(int pageNumber, bool current, string pkgType = "") /// public string PageLink { - get { return string.Format("GalleryGetPackages({0},'{1}'); return false;", PageNumber, _pkgType); } + get { return $"GalleryGetPackages({PageNumber},'{_pkgType}'); return false;"; } } } } diff --git a/BlogEngine/BlogEngine.Core/Services/Search/Search.cs b/BlogEngine/BlogEngine.Core/Services/Search/Search.cs index 6434618b9..ca3ef2a68 100644 --- a/BlogEngine/BlogEngine.Core/Services/Search/Search.cs +++ b/BlogEngine/BlogEngine.Core/Services/Search/Search.cs @@ -2,7 +2,6 @@ { using System; using System.Collections.Generic; - using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Globalization; using System.Linq; diff --git a/BlogEngine/BlogEngine.Core/Services/Security/CustomIdentity.cs b/BlogEngine/BlogEngine.Core/Services/Security/CustomIdentity.cs index ac094491a..4e9a429c5 100644 --- a/BlogEngine/BlogEngine.Core/Services/Security/CustomIdentity.cs +++ b/BlogEngine/BlogEngine.Core/Services/Security/CustomIdentity.cs @@ -1,14 +1,8 @@ namespace BlogEngine.Core { using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; using System.Web.Security; using System.Security.Principal; - using System.Runtime.Serialization; - using System.Reflection; - using System.Security; /// /// IIdentity class used for authentication. @@ -64,11 +58,11 @@ public CustomIdentity(string username, bool isAuthenticated) /// The user's password. public CustomIdentity(string username, string password) { - if (Utils.StringIsNullOrWhitespace(username)) - throw new ArgumentNullException("username"); + if (String.IsNullOrWhiteSpace(username)) + throw new ArgumentNullException(nameof(username)); - if (Utils.StringIsNullOrWhitespace(password)) - throw new ArgumentNullException("password"); + if (String.IsNullOrWhiteSpace(password)) + throw new ArgumentNullException(nameof(password)); if (!Membership.ValidateUser(username, password)) { return; } diff --git a/BlogEngine/BlogEngine.Core/Services/Security/CustomPrincipal.cs b/BlogEngine/BlogEngine.Core/Services/Security/CustomPrincipal.cs index 989a5fd7d..1151555b1 100644 --- a/BlogEngine/BlogEngine.Core/Services/Security/CustomPrincipal.cs +++ b/BlogEngine/BlogEngine.Core/Services/Security/CustomPrincipal.cs @@ -1,9 +1,5 @@ namespace BlogEngine.Core { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; using System.Security.Principal; using System.Web.Security; diff --git a/BlogEngine/BlogEngine.Core/Services/Security/Right.cs b/BlogEngine/BlogEngine.Core/Services/Security/Right.cs index ec9aa47da..7d4ed00b1 100644 --- a/BlogEngine/BlogEngine.Core/Services/Security/Right.cs +++ b/BlogEngine/BlogEngine.Core/Services/Security/Right.cs @@ -347,9 +347,9 @@ public static void OnRoleDeleting(string roleName) /// private static string PrepareRoleName(string roleName) { - if (Utils.StringIsNullOrWhitespace(roleName)) + if (String.IsNullOrWhiteSpace(roleName)) { - throw new ArgumentNullException("roleName"); + throw new ArgumentNullException(nameof(roleName)); } else { @@ -373,9 +373,9 @@ public static IEnumerable GetAllRights() /// public static Right GetRightByName(string rightName) { - if (Utils.StringIsNullOrWhitespace(rightName)) + if (String.IsNullOrWhiteSpace(rightName)) { - throw new ArgumentNullException("rightName"); + throw new ArgumentNullException(nameof(rightName)); } else { @@ -439,7 +439,7 @@ public static IEnumerable GetRights(IEnumerable roles) { if (roles == null) { - throw new ArgumentNullException("roles"); + throw new ArgumentNullException(nameof(roles)); } else if (!roles.Any()) { @@ -473,7 +473,7 @@ public static bool HasRight(Rights right, IEnumerable roles) { if (roles == null) { - throw new ArgumentNullException("roles"); + throw new ArgumentNullException(nameof(roles)); } else if (!roles.Any()) { diff --git a/BlogEngine/BlogEngine.Core/Services/Security/Rights.cs b/BlogEngine/BlogEngine.Core/Services/Security/Rights.cs index 78ba9cb55..fa63b8e14 100644 --- a/BlogEngine/BlogEngine.Core/Services/Security/Rights.cs +++ b/BlogEngine/BlogEngine.Core/Services/Security/Rights.cs @@ -1,13 +1,4 @@ using System; -using System.Collections.ObjectModel; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Web; -using System.Web.Security; -using System.Diagnostics; -using System.Security; namespace BlogEngine.Core { diff --git a/BlogEngine/BlogEngine.Core/Services/Security/Security.cs b/BlogEngine/BlogEngine.Core/Services/Security/Security.cs index ad158760f..1b1e4a120 100644 --- a/BlogEngine/BlogEngine.Core/Services/Security/Security.cs +++ b/BlogEngine/BlogEngine.Core/Services/Security/Security.cs @@ -1,14 +1,9 @@ using System; -using System.Collections.ObjectModel; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading; using System.Web; using System.Web.Security; -using System.Diagnostics; using System.Security; -using System.Security.Principal; namespace BlogEngine.Core { @@ -173,7 +168,7 @@ public static bool AuthenticateUser(string username, string password, bool remem DateTime.Now, expirationDate, rememberMe, - string.Format("{0}{1}{2}", SecurityValidationKey, AUTH_TKT_USERDATA_DELIMITER, Blog.CurrentInstance.Id), + $"{SecurityValidationKey}{AUTH_TKT_USERDATA_DELIMITER}{Blog.CurrentInstance.Id}", FormsAuthentication.FormsCookiePath ); @@ -190,10 +185,7 @@ public static bool AuthenticateUser(string username, string password, bool remem string returnUrl = context.Request.QueryString["returnUrl"]; // ignore Return URLs not beginning with a forward slash, such as remote sites. - if (string.IsNullOrWhiteSpace(returnUrl) || !returnUrl.StartsWith("/")) - returnUrl = null; - - if (!string.IsNullOrWhiteSpace(returnUrl)) + if (Security.IsLocalUrl(returnUrl)) { context.Response.Redirect(returnUrl); } @@ -209,6 +201,19 @@ public static bool AuthenticateUser(string username, string password, bool remem return false; } + private static bool IsLocalUrl(string url) + { + if (string.IsNullOrWhiteSpace(url)) + { + return false; + } + else + { + return ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || // "/" or "/foo" but not "//" or "/\" + (url.Length > 1 && url[0] == '~' && url[1] == '/')); // "~/" or "~/foo" + } + } + private const string AUTH_TKT_USERDATA_DELIMITER = "-|-"; private static string SecurityValidationKey @@ -371,7 +376,7 @@ public static bool IsAuthorizedTo(Rights right) /// public static bool IsAuthorizedTo(AuthorizationCheck authCheck, IEnumerable rights) { - if (rights.Count() == 0) + if (!rights.Any()) { // Always return false for this. If there's a mistake where authorization // is being checked for on an empty collection, we don't want to return diff --git a/BlogEngine/BlogEngine.Core/Services/Security/SecuritySiteMapProvider.cs b/BlogEngine/BlogEngine.Core/Services/Security/SecuritySiteMapProvider.cs index 9e07c15c5..140ec4ff4 100644 --- a/BlogEngine/BlogEngine.Core/Services/Security/SecuritySiteMapProvider.cs +++ b/BlogEngine/BlogEngine.Core/Services/Security/SecuritySiteMapProvider.cs @@ -2,8 +2,6 @@ { using System; using System.Collections.Generic; - using System.Linq; - using System.Text; using System.Web; /// @@ -33,14 +31,14 @@ public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node) } } - if (!Utils.StringIsNullOrWhitespace(node["rights"])) + if (!String.IsNullOrWhiteSpace(node["rights"])) { // By default, all specified Rights must exist. // We allow this to be overridden via the "rightsAuthorizationCheck" // attribute. AuthorizationCheck authCheck = AuthorizationCheck.HasAll; - if (!Utils.StringIsNullOrWhitespace(node["rightsAuthorizationCheck"])) + if (!String.IsNullOrWhiteSpace(node["rightsAuthorizationCheck"])) { authCheck = Utils.ParseEnum(node["rightsAuthorizationCheck"], AuthorizationCheck.HasAll); } diff --git a/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogImporter.cs b/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogImporter.cs index 72e86fc91..1d4b2bf6a 100644 --- a/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogImporter.cs +++ b/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogImporter.cs @@ -104,7 +104,7 @@ static string PostUrl(string slug, DateTime dateCreated) Utils.RelativeWebRoot, dateCreated.ToString("yyyy/MM/dd/", CultureInfo.InvariantCulture), theslug) - : string.Format("{0}post/{1}", Utils.RelativeWebRoot, theslug); + : $"{Utils.RelativeWebRoot}post/{theslug}"; } #endregion diff --git a/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogReader.cs b/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogReader.cs index 2bbd2e750..0ed4b4b58 100644 --- a/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogReader.cs +++ b/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogReader.cs @@ -53,13 +53,15 @@ public string XmlData /// /// Gets an XmlReader that converts BlogML data saved as string into XML stream /// - private XmlTextReader XmlReader + private XmlReader XmlReader { get { var byteArray = Encoding.UTF8.GetBytes(this.xmlData); var stream = new MemoryStream(byteArray); - return new XmlTextReader(stream); + XmlReaderSettings settings = new XmlReaderSettings(); + settings.XmlResolver = null; + return XmlReader.Create(stream, settings); } } @@ -83,7 +85,7 @@ public override bool Import() } catch (Exception ex) { - Message = string.Format("BlogReader.Import: BlogML could not load with 2.0 specs. {0}", ex.Message); + Message = $"BlogReader.Import: BlogML could not load with 2.0 specs. {ex.Message}"; Utils.Log(Message); return false; } @@ -98,11 +100,11 @@ public override bool Import() LoadBlogPosts(); - Message = string.Format("Imported {0} new posts", PostCount); + Message = $"Imported {PostCount} new posts"; } catch (Exception ex) { - Message = string.Format("BlogReader.Import: {0}", ex.Message); + Message = $"BlogReader.Import: {ex.Message}"; Utils.Log(Message); return false; } @@ -121,7 +123,7 @@ private Guid GetGuid(string type, string value) // Value might be a GUID, or it could be a simple integer. - if (!Utils.StringIsNullOrWhitespace(value) && + if (!String.IsNullOrWhiteSpace(value) && value.Length == 36) { return new Guid(value); @@ -160,7 +162,7 @@ private DateTime GetDate(XmlAttribute attr) DateTime defaultDate = DateTime.Now; DateTime dt = defaultDate; - if (!Utils.StringIsNullOrWhitespace(value)) + if (!String.IsNullOrWhiteSpace(value)) { if (!DateTime.TryParseExact(value, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) dt = defaultDate; @@ -344,7 +346,7 @@ private void LoadBlogExtendedPosts(BlogMLBlog blog) if (post.PostType == BlogPostTypes.Normal) { BlogMLPost p = post; - blogsExtended.Where(b => b.PostUrl == p.PostUrl).FirstOrDefault().BlogPost = post; + blogsExtended.FirstOrDefault(b => b.PostUrl == p.PostUrl).BlogPost = post; } } } @@ -398,7 +400,7 @@ private void LoadBlogPosts() } } bi.ForceReload(); - Utils.Log(string.Format("BlogReader.LoadBlogPosts: Completed importing {0} posts", PostCount)); + Utils.Log($"BlogReader.LoadBlogPosts: Completed importing {PostCount} posts"); } #endregion diff --git a/BlogEngine/BlogEngine.Core/Services/Syndication/SyndicationGenerator.cs b/BlogEngine/BlogEngine.Core/Services/Syndication/SyndicationGenerator.cs index f5436ce81..fda9d5bf7 100644 --- a/BlogEngine/BlogEngine.Core/Services/Syndication/SyndicationGenerator.cs +++ b/BlogEngine/BlogEngine.Core/Services/Syndication/SyndicationGenerator.cs @@ -35,7 +35,7 @@ public class SyndicationGenerator /// /// Private member to hold the URI of the syndication generation utility. /// - private static readonly Uri GeneratorUri = new Uri("http://dotnetblogengine.net/"); + private static readonly Uri GeneratorUri = new Uri("https://blogengine.io/"); /// /// Private member to hold the version of the syndication generation utility. @@ -84,12 +84,12 @@ public SyndicationGenerator(BlogSettings settings, List categories) { if (settings == null) { - throw new ArgumentNullException("settings"); + throw new ArgumentNullException(nameof(settings)); } if (categories == null) { - throw new ArgumentNullException("categories"); + throw new ArgumentNullException(nameof(categories)); } // ------------------------------------------------------------ @@ -135,7 +135,7 @@ public static Dictionary SupportedNamespaces { "wfw", "http://wellformedweb.org/CommentAPI/" }, { "slash", "http://purl.org/rss/1.0/modules/slash/" }, { "geo", "http://www.w3.org/2003/01/geo/wgs84_pos#" }, - { "betag", "http://dotnetblogengine.net/schemas/tags"} + { "betag", "https://blogengine.io/schemas/tags"} }); } } @@ -168,7 +168,7 @@ protected set { if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } this.blogSettings = value; @@ -243,12 +243,12 @@ public void WriteFeed(SyndicationFormat format, Stream stream, List publishables, writer.WriteStartElement("link"); writer.WriteAttributeString("rel", "self"); - writer.WriteAttributeString("href", string.Format("{0}syndication.axd?format=atom", Utils.AbsoluteWebRoot)); + writer.WriteAttributeString("href", $"{Utils.AbsoluteWebRoot}syndication.axd?format=atom"); writer.WriteEndElement(); // writer.WriteStartElement("link"); @@ -1060,7 +1060,7 @@ private void WriteRssChannelCommonElements(XmlWriter writer) // url = HttpContext.Current.Request.Url.ToString(); // } writer.WriteElementString("docs", "http://www.rssboard.org/rss-specification"); - writer.WriteElementString("generator", string.Format("BlogEngine.NET {0}", BlogSettings.Instance.Version())); + writer.WriteElementString("generator", $"BlogEngine.NET {BlogSettings.Instance.Version()}"); // writer.WriteRaw("\n"); if (!String.IsNullOrEmpty(this.Settings.Language)) diff --git a/BlogEngine/BlogEngine.Core/Web/BlogCulture.cs b/BlogEngine/BlogEngine.Core/Web/BlogCulture.cs index 79555c0a5..eaf7147fa 100644 --- a/BlogEngine/BlogEngine.Core/Web/BlogCulture.cs +++ b/BlogEngine/BlogEngine.Core/Web/BlogCulture.cs @@ -32,7 +32,7 @@ public BlogCulture(CultureInfo cultureInfo, ResourceType resourceType) { if (cultureInfo == null) { - throw new ArgumentNullException("cultureInfo"); + throw new ArgumentNullException(nameof(cultureInfo)); } this.cultureInfo = cultureInfo; diff --git a/BlogEngine/BlogEngine.Core/Web/Controls/BlogBasePage.cs b/BlogEngine/BlogEngine.Core/Web/Controls/BlogBasePage.cs index 0c474e64c..e2732b182 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/BlogBasePage.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/BlogBasePage.cs @@ -1,4 +1,6 @@ -namespace BlogEngine.Core.Web.Controls +using System.IO; + +namespace BlogEngine.Core.Web.Controls { using System; using System.Web; @@ -76,9 +78,7 @@ protected virtual void AddMetaContentType() var meta = new HtmlMeta { HttpEquiv = "content-type", - Content = - string.Format( - "{0}; charset={1}", Response.ContentType, Response.ContentEncoding.HeaderName) + Content = $"{Response.ContentType}; charset={Response.ContentEncoding.HeaderName}" }; Page.Header.Controls.AddAt(0, meta); } @@ -123,7 +123,7 @@ protected override void OnError(EventArgs e) if (exception != null && exception.Message.Contains("site.master")) { ctx.Server.ClearError(); - this.MasterPageFile = string.Format("{0}Custom/Themes/RazorHost/site.master", Utils.ApplicationRelativeWebRoot); + this.MasterPageFile = $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/RazorHost/site.master"; base.OnInit(EventArgs.Empty); } @@ -149,17 +149,17 @@ protected override void OnLoad(EventArgs e) AddDefaultLanguages(); - header.AddLink("", "contents", "Archive", string.Format("{0}archive{1}", relativeWebRoot, BlogConfig.FileExtension)); + header.AddLink("", "contents", "Archive", $"{relativeWebRoot}archive{BlogConfig.FileExtension}"); header.AddLink("", "start", instanceName, relativeWebRoot); - header.AddLink("application/rsd+xml", "edituri", "RSD", string.Format("{0}rsd.axd", absoluteWebRoot)); - header.AddLink("application/rdf+xml", "meta", "SIOC", string.Format("{0}sioc.axd", absoluteWebRoot)); - header.AddLink("application/apml+xml", "meta", "APML", string.Format("{0}apml.axd", absoluteWebRoot)); - header.AddLink("application/rdf+xml", "meta", "FOAF", string.Format("{0}foaf.axd", absoluteWebRoot)); + header.AddLink("application/rsd+xml", "edituri", "RSD", $"{absoluteWebRoot}rsd.axd"); + header.AddLink("application/rdf+xml", "meta", "SIOC", $"{absoluteWebRoot}sioc.axd"); + header.AddLink("application/apml+xml", "meta", "APML", $"{absoluteWebRoot}apml.axd"); + header.AddLink("application/rdf+xml", "meta", "FOAF", $"{absoluteWebRoot}foaf.axd"); if (string.IsNullOrEmpty(BlogSettings.Instance.AlternateFeedUrl)) { - header.AddLink("application/rss+xml", "alternate", string.Format("{0} (RSS)", instanceName), string.Format("{0}", Utils.FeedUrl)); - header.AddLink("application/atom+xml", "alternate", string.Format("{0} (ATOM)", instanceName), string.Format("{0}?format=atom", Utils.FeedUrl)); + header.AddLink("application/rss+xml", "alternate", $"{instanceName} (RSS)", $"{Utils.FeedUrl}"); + header.AddLink("application/atom+xml", "alternate", $"{instanceName} (ATOM)", $"{Utils.FeedUrl}?format=atom"); } else { @@ -167,7 +167,7 @@ protected override void OnLoad(EventArgs e) } if (BlogSettings.Instance.EnableOpenSearch) { - header.AddLink("application/opensearchdescription+xml", "search", instanceName, string.Format("{0}opensearch.axd", absoluteWebRoot)); + header.AddLink("application/opensearchdescription+xml", "search", instanceName, $"{absoluteWebRoot}opensearch.axd"); } header.Render(this); @@ -204,7 +204,7 @@ protected override void OnPreInit(EventArgs e) allowViewing = true; if (!allowViewing) - Response.Redirect(string.Format("{0}Account/login.aspx", Utils.RelativeWebRoot)); + Response.Redirect($"{Utils.RelativeWebRoot}Account/login.aspx"); MasterPageFile = GetSiteMaster(); @@ -234,7 +234,7 @@ protected override void OnPreRenderComplete(EventArgs e) base.OnPreRenderComplete(e); if (BlogSettings.Instance.UseBlogNameInPageTitles) { - Page.Title = string.Format("{0} | {1}", BlogSettings.Instance.Name, Page.Title); + Page.Title = $"{BlogSettings.Instance.Name} | {Page.Title}"; } } @@ -258,35 +258,39 @@ protected override void Render(HtmlTextWriter writer) /// Path to the master page string GetSiteMaster() { - if (Request.FilePath.Contains("post.aspx", StringComparison.InvariantCultureIgnoreCase)) + if(FilePathContains("post.aspx")) { - string path = string.Format("{0}Custom/Themes/{1}/post.master", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.Theme); - if (System.IO.File.Exists(Server.MapPath(path))) + string path = $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{BlogSettings.Instance.Theme}/post.master"; + if (File.Exists(Server.MapPath(path))) return path; } // if page.master exists, use it for all common pages // and site.master only for post list - if (Request.FilePath.Contains("page.aspx", StringComparison.InvariantCultureIgnoreCase) || - Request.FilePath.Contains("archive.aspx", StringComparison.InvariantCultureIgnoreCase) || - Request.FilePath.Contains("contact.aspx", StringComparison.InvariantCultureIgnoreCase) || - Request.FilePath.Contains("error.aspx", StringComparison.InvariantCultureIgnoreCase) || - Request.FilePath.Contains("error404.aspx", StringComparison.InvariantCultureIgnoreCase) || - Request.FilePath.Contains("search.aspx", StringComparison.InvariantCultureIgnoreCase)) + if (PageMasterExists) { - string path = string.Format("{0}Custom/Themes/{1}/page.master", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.Theme); - if (System.IO.File.Exists(Server.MapPath(path))) + string path = $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{BlogSettings.Instance.Theme}/page.master"; + if (File.Exists(Server.MapPath(path))) return path; } - var siteMaster = string.Format("{0}Custom/Themes/{1}/site.master", Utils.ApplicationRelativeWebRoot, - BlogSettings.Instance.GetThemeWithAdjustments(null)); + var siteMaster = $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{BlogSettings.Instance.GetThemeWithAdjustments(null)}/site.master"; + + return File.Exists(Server.MapPath(siteMaster)) + ? siteMaster + : $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/Standard/site.master"; + } - if (System.IO.File.Exists(Server.MapPath(siteMaster))) - return siteMaster; - else - return string.Format("{0}Custom/Themes/Standard/site.master", Utils.ApplicationRelativeWebRoot); + private bool PageMasterExists => FilePathContains("page.aspx") || + FilePathContains("archive.aspx") || + FilePathContains("contact.aspx") || + FilePathContains("error.aspx") || + FilePathContains("error404.aspx") || + FilePathContains("search.aspx"); + private bool FilePathContains(string path) + { + return Request.FilePath.Contains(path, StringComparison.InvariantCultureIgnoreCase); } } } \ No newline at end of file diff --git a/BlogEngine/BlogEngine.Core/Web/Controls/CommentFormBase.cs b/BlogEngine/BlogEngine.Core/Web/Controls/CommentFormBase.cs index c13463534..17d8c71f3 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/CommentFormBase.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/CommentFormBase.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Web.Caching; -using System.Web.UI; +using System.Web.UI; namespace BlogEngine.Core.Web.Controls { @@ -14,7 +11,5 @@ public class CommentFormBase : UserControl /// Current post /// public IPublishable PostItem { get; set; } - - } } diff --git a/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs b/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs index ee0c418b5..767cdf486 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs @@ -4,7 +4,6 @@ using System.Globalization; using System.Linq; using System.Text; - using System.Web.Security; using System.Web.UI; /// @@ -180,11 +179,8 @@ public string ReplyToLink this.Post.HasCommentsEnabled) && this.Comment.IsApproved) && (BlogSettings.Instance.DaysCommentsAreEnabled <= 0 || this.Post.DateCreated.AddDays(BlogSettings.Instance.DaysCommentsAreEnabled) >= DateTime.Now.Date) - ? string.Format( - "{1}", - this.Comment.Id, - Utils.Translate("replyToThis")) - : string.Empty; + ? $"{Utils.Translate("replyToThis")}" + : string.Empty; } } @@ -216,7 +212,7 @@ public string Gravatar(int size) { var website = this.Comment.Website == null ? "" : this.Comment.Website.ToString(); var src = BlogEngine.Core.Data.Services.Avatar.GetSrc(this.Comment.Email, website); - return string.Format("", src, size); + return $""; } /// diff --git a/BlogEngine/BlogEngine.Core/Web/Controls/PageMenu.cs b/BlogEngine/BlogEngine.Core/Web/Controls/PageMenu.cs index 5be4e7b31..b73ef4f4a 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/PageMenu.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/PageMenu.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using System.Web.UI.HtmlControls; using System.Linq; using System.Web; using System.Web.UI; -using BlogEngine.Core; namespace BlogEngine.Core.Web.Controls { diff --git a/BlogEngine/BlogEngine.Core/Web/Controls/PostViewBase.cs b/BlogEngine/BlogEngine.Core/Web/Controls/PostViewBase.cs index a053ee0ae..8df7721f1 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/PostViewBase.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/PostViewBase.cs @@ -48,7 +48,7 @@ public string Body if (ShowExcerpt) { - var link = string.Format(" [{1}]", post.RelativeLink, Utils.Translate("more")); + var link = $" [{Utils.Translate("more")}]"; if (!string.IsNullOrEmpty(post.Description)) { @@ -59,7 +59,7 @@ public string Body body = Utils.StripHtml(body); if (body.Length > DescriptionCharacters && DescriptionCharacters > 0) { - body = string.Format("{0}...{1}", body.Substring(0, DescriptionCharacters), link); + body = $"{body.Substring(0, DescriptionCharacters)}...{link}"; } } } diff --git a/BlogEngine/BlogEngine.Core/Web/Controls/RelatedPostsBase.cs b/BlogEngine/BlogEngine.Core/Web/Controls/RelatedPostsBase.cs index 9a9807dd9..33c1b830f 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/RelatedPostsBase.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/RelatedPostsBase.cs @@ -91,14 +91,14 @@ string GetDescription(IPublishable post) var description = Utils.StripHtml(post.Description); if (description != null && description.Length > this.DescriptionMaxLength) { - description = string.Format("{0}...", description.Substring(0, this.DescriptionMaxLength)); + description = $"{description.Substring(0, DescriptionMaxLength)}..."; } if (String.IsNullOrEmpty(description)) { var content = Utils.StripHtml(post.Content); description = content.Length > this.DescriptionMaxLength - ? string.Format("{0}...", content.Substring(0, this.DescriptionMaxLength)) + ? $"{content.Substring(0, DescriptionMaxLength)}..." : content; } return description; diff --git a/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionManager.cs b/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionManager.cs index fc220cc9e..63c3ead94 100644 --- a/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionManager.cs +++ b/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionManager.cs @@ -7,7 +7,6 @@ using System.Linq; using System.Reflection; using System.Web; - using System.Web.Hosting; using System.Xml.Serialization; using BlogEngine.Core.Web.Controls; @@ -168,17 +167,15 @@ public static ExtensionSettings GetSettings(string extensionName, string setting if (!Blog.CurrentInstance.IsPrimary && extension.SubBlogEnabled) { - return extension.Settings.Where( - setting => setting != null + return extension.Settings.FirstOrDefault(setting => setting != null && setting.Name == settingName - && setting.BlogId == Blog.CurrentInstance.Id).FirstOrDefault(); + && setting.BlogId == Blog.CurrentInstance.Id); } var primId = Blog.Blogs.FirstOrDefault(b => b.IsPrimary).BlogId; - return extension.Settings.Where( - setting => setting != null + return extension.Settings.FirstOrDefault(setting => setting != null && setting.Name == settingName - && (setting.BlogId == primId || setting.BlogId == null)).FirstOrDefault(); + && (setting.BlogId == primId || setting.BlogId == null)); } /// @@ -510,7 +507,7 @@ private static void LoadExtensions() } catch (Exception e) { - Utils.Log(string.Format("Can not load {0}: {1}", type.Name, e.Message)); + Utils.Log($"Can not load {type.Name}: {e.Message}"); } } } diff --git a/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionSettings.cs b/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionSettings.cs index 4713e5933..847029a22 100644 --- a/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionSettings.cs +++ b/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionSettings.cs @@ -415,7 +415,7 @@ public void AddValues(string[] values) { if (this.Parameters[i].KeyField && IsKeyValueExists(values[i])) { - string err = string.Format("Dupliate value of '{0}' not allowed for parameter '{1}'", values[i], this.Parameters[i].Label); + string err = $"Dupliate value of '{values[i]}' not allowed for parameter '{Parameters[i].Label}'"; Utils.Log(err); throw new ApplicationException(err); @@ -441,7 +441,7 @@ public void AddValues(StringCollection values) { if (IsKeyValueExists(values[i])) { - string err = string.Format("Dupliate value of '{0}' not allowed for parameter '{1}'", values[i], this.Parameters[i].Label); + string err = $"Dupliate value of '{values[i]}' not allowed for parameter '{Parameters[i].Label}'"; Utils.Log(err); throw new ApplicationException(err); diff --git a/BlogEngine/BlogEngine.Core/Web/Extensions/ManagedExtension.cs b/BlogEngine/BlogEngine.Core/Web/Extensions/ManagedExtension.cs index 0d6fc8495..496638989 100644 --- a/BlogEngine/BlogEngine.Core/Web/Extensions/ManagedExtension.cs +++ b/BlogEngine/BlogEngine.Core/Web/Extensions/ManagedExtension.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; - using System.Reflection; - using System.Web.Hosting; using System.IO; using System.Runtime.Serialization.Formatters.Binary; @@ -121,7 +119,7 @@ public List Settings { if (!Blog.CurrentInstance.IsPrimary && SubBlogEnabled) { - if (!settings.Any(xset => xset.BlogId == Blog.CurrentInstance.Id)) + if (settings.All(xset => xset.BlogId != Blog.CurrentInstance.Id)) { var primId = Blog.Blogs.FirstOrDefault(b => b.IsPrimary).BlogId; @@ -155,7 +153,7 @@ public List BlogSettings if (!Blog.CurrentInstance.IsPrimary && SubBlogEnabled) { - if (!settings.Any(xset => xset.BlogId == Blog.CurrentInstance.Id)) + if (settings.All(xset => xset.BlogId != Blog.CurrentInstance.Id)) { List newSets = GenericHelper>.Copy( settings.Where(setItem => setItem.BlogId == primId || setItem.BlogId == null).ToList()); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/BlogMLExportHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/BlogMLExportHandler.cs index 73f4e0752..a857d6a41 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/BlogMLExportHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/BlogMLExportHandler.cs @@ -4,7 +4,6 @@ using System.Globalization; using System.Linq; using System.Text; - using System.Threading; using System.Web; using System.Web.Security; using System.Xml; diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/FileHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/FileHandler.cs index ea1b74acd..44f479adc 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/FileHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/FileHandler.cs @@ -1,7 +1,6 @@ namespace BlogEngine.Core.Web.HttpHandlers { using System; - using System.IO; using System.Web; using BlogEngine.Core.Providers; @@ -75,18 +74,18 @@ public void ProcessRequest(HttpContext context) if (fileName.Contains("..")) { OnBadRequest(fileName); - context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot)); + context.Response.Redirect($"{Utils.AbsoluteWebRoot}error404.aspx"); } OnServing(fileName); - fileName = !fileName.StartsWith("/") ? string.Format("/{0}", fileName) : fileName; + fileName = !fileName.StartsWith("/") ? $"/{fileName}" : fileName; try { - var file = BlogService.GetFile(string.Format("{0}files{1}",Blog.CurrentInstance.StorageLocation, fileName)); + var file = BlogService.GetFile($"{Blog.CurrentInstance.StorageLocation}files{fileName}"); if (file != null) { - context.Response.AppendHeader("Content-Disposition", string.Format("inline; filename=\"{0}\"", file.Name)); + context.Response.AppendHeader("Content-Disposition", $"inline; filename=\"{file.Name}\""); SetContentType(context, file.Name); if (Utils.SetConditionalGetHeaders(file.DateCreated.ToUniversalTime())) return; @@ -97,13 +96,13 @@ public void ProcessRequest(HttpContext context) else { OnBadRequest(fileName); - context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot)); + context.Response.Redirect($"{Utils.AbsoluteWebRoot}error404.aspx"); } } catch (Exception) { OnBadRequest(fileName); - context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot)); + context.Response.Redirect($"{Utils.AbsoluteWebRoot}error404.aspx"); } } } diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Foaf.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Foaf.cs index 354b25366..6b0cf447f 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Foaf.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Foaf.cs @@ -216,24 +216,24 @@ private void WriteFoaf(HttpContext context, string name) var foaf = new FoafPerson(title) { Name = title, Blog = url }; - if (Blog.CurrentInstance.Cache[string.Format("foaf:{0}", title)] == null) + if (Blog.CurrentInstance.Cache[$"foaf:{title}"] == null) { var docs = Utils.FindSemanticDocuments(new Uri(url), "foaf"); if (docs.Count > 0) { foreach (var key in docs.Keys) { - Blog.CurrentInstance.Cache.Insert(string.Format("foaf:{0}", title), key.ToString()); + Blog.CurrentInstance.Cache.Insert($"foaf:{title}", key.ToString()); break; } } else { - Blog.CurrentInstance.Cache.Insert(string.Format("foaf:{0}", title), "0"); + Blog.CurrentInstance.Cache.Insert($"foaf:{title}", "0"); } } - var seeAlso = (string)Blog.CurrentInstance.Cache[string.Format("foaf:{0}", title)]; + var seeAlso = (string)Blog.CurrentInstance.Cache[$"foaf:{title}"]; if (seeAlso != null && seeAlso.Contains("://")) { foaf.Rdf = seeAlso; @@ -389,7 +389,7 @@ public FoafPerson(string id, AuthorProfile ap) // no homepage // this website = blog this.Blog = Utils.AbsoluteWebRoot.ToString(); - this.Rdf = string.Format("{0}foaf_{1}.axd", Utils.AbsoluteWebRoot, ap.UserName); + this.Rdf = $"{Utils.AbsoluteWebRoot}foaf_{ap.UserName}.axd"; this.Firstname = ap.FirstName; this.Lastname = ap.LastName; this.Image = ap.PhotoUrl; diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ImageHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ImageHandler.cs index a732d3f33..bdc858d7d 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ImageHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ImageHandler.cs @@ -1,7 +1,6 @@ namespace BlogEngine.Core.Web.HttpHandlers { using System; - using System.IO; using System.Web; using BlogEngine.Core.Providers; @@ -73,16 +72,16 @@ public void ProcessRequest(HttpContext context) OnServing(fileName); try { - fileName = !fileName.StartsWith("/") ? string.Format("/{0}", fileName) : fileName; + fileName = !fileName.StartsWith("/") ? $"/{fileName}" : fileName; // prevent directory traversal if (fileName.Contains("..")) { OnBadRequest(fileName); - context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot)); + context.Response.Redirect($"{Utils.AbsoluteWebRoot}error404.aspx"); } - var file = BlogService.GetFile(string.Format("{0}files{1}", Blog.CurrentInstance.StorageLocation, fileName)); + var file = BlogService.GetFile($"{Blog.CurrentInstance.StorageLocation}files{fileName}"); if (file != null) { context.Response.Cache.SetCacheability(HttpCacheability.Public); @@ -93,7 +92,7 @@ public void ProcessRequest(HttpContext context) var index = fileName.LastIndexOf(".") + 1; var extension = fileName.Substring(index).ToUpperInvariant(); - context.Response.ContentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension); + context.Response.ContentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : $"image/{extension}"; context.Response.BinaryWrite(file.FileContents); OnServed(fileName); @@ -101,13 +100,13 @@ public void ProcessRequest(HttpContext context) else { OnBadRequest(fileName); - context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot)); + context.Response.Redirect($"{Utils.AbsoluteWebRoot}error404.aspx"); } } catch (Exception ex) { OnBadRequest(ex.Message); - context.Response.Redirect(string.Format("{0}error404.aspx", Utils.AbsoluteWebRoot)); + context.Response.Redirect($"{Utils.AbsoluteWebRoot}error404.aspx"); } } } diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/JavaScriptHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/JavaScriptHandler.cs index 570fb8656..d4900582c 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/JavaScriptHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/JavaScriptHandler.cs @@ -93,7 +93,7 @@ private static void SetHeaders(int hash, HttpContext context) cache.SetMaxAge(new TimeSpan(30, 0, 0, 0)); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); - var etag = string.Format("\"{0}\"", hash); + var etag = $"\"{hash}\""; var incomingEtag = context.Request.Headers["If-None-Match"]; //cache.SetETag(etag); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/OpenSearchHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/OpenSearchHandler.cs index ed09c5eaf..2c023f31c 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/OpenSearchHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/OpenSearchHandler.cs @@ -60,17 +60,17 @@ public void ProcessRequest(HttpContext context) writer.WriteAttributeString("height", "16"); writer.WriteAttributeString("width", "16"); writer.WriteAttributeString("type", "image/vnd.microsoft.icon"); - writer.WriteValue(string.Format("{0}Content/images/blog/favicon.ico", Utils.AbsoluteWebRoot)); + writer.WriteValue($"{Utils.AbsoluteWebRoot}Content/images/blog/favicon.ico"); writer.WriteEndElement(); writer.WriteStartElement("Url"); writer.WriteAttributeString("type", "text/html"); - writer.WriteAttributeString("template", string.Format("{0}search{1}?q={{searchTerms}}", Utils.AbsoluteWebRoot, BlogConfig.FileExtension)); + writer.WriteAttributeString("template", $"{Utils.AbsoluteWebRoot}search{BlogConfig.FileExtension}?q={{searchTerms}}"); writer.WriteEndElement(); writer.WriteStartElement("Url"); writer.WriteAttributeString("type", "application/rss+xml"); - writer.WriteAttributeString("template", string.Format("{0}syndication.axd?q={{searchTerms}}", Utils.AbsoluteWebRoot)); + writer.WriteAttributeString("template", $"{Utils.AbsoluteWebRoot}syndication.axd?q={{searchTerms}}"); writer.WriteEndElement(); writer.WriteEndElement(); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/PingbackHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/PingbackHandler.cs index cde7e80d2..b4839d8b0 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/PingbackHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/PingbackHandler.cs @@ -337,7 +337,7 @@ private static XmlDocument RetrieveXmlDocument(HttpContext context) context.Response.End(); } - var doc = new XmlDocument(); + var doc = new XmlDocument() { XmlResolver = null }; doc.LoadXml(xml); return doc; } @@ -395,7 +395,7 @@ private void AddComment(string sourceUrl, Post post) Author = GetDomain(sourceUrl), Website = new Uri(sourceUrl) }; - comment.Content = string.Format("Pingback from {0}{1}{2}{3}", comment.Author, Environment.NewLine, Environment.NewLine, this.title); + comment.Content = $"Pingback from {comment.Author}{Environment.NewLine}{Environment.NewLine}{title}"; comment.DateCreated = DateTime.Now; comment.Email = "pingback"; comment.IP = Utils.GetClientIP(); @@ -432,4 +432,4 @@ private void ExamineSourcePage(string sourceUrl, string targetUrl) #endregion } -} \ No newline at end of file +} diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RatingHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RatingHandler.cs index 05b4c8341..69b76ce8c 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RatingHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RatingHandler.cs @@ -58,7 +58,7 @@ public void ProcessRequest(HttpContext context) { if (HasRated(id)) { - context.Response.Write(string.Format("{0}HASRATED", rate)); + context.Response.Write($"{rate}HASRATED"); context.Response.End(); } else @@ -67,7 +67,7 @@ public void ProcessRequest(HttpContext context) post.Rate(rate); SetCookie(id, context); - context.Response.Write(string.Format("{0}OK", rate)); + context.Response.Write($"{rate}OK"); context.Response.End(); } diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ResourceHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ResourceHandler.cs index f20f411fb..c3cf97fb1 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ResourceHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ResourceHandler.cs @@ -8,7 +8,6 @@ namespace BlogEngine.Core.Web.HttpHandlers using System.Web; using System.Web.Caching; using HttpModules; - using System.Linq; /// /// Removes whitespace in all stylesheets added to the @@ -160,7 +159,7 @@ public void ProcessRequest(HttpContext context) /// public static string GetScriptPath(System.Globalization.CultureInfo cultureInfo) { - return String.Format("{0}{1}.res.axd", Utils.RelativeWebRoot, cultureInfo.Name.ToLowerInvariant()); + return $"{Utils.RelativeWebRoot}{cultureInfo.Name.ToLowerInvariant()}.res.axd"; } /// @@ -184,7 +183,7 @@ private static void SetHeaders(int hash, HttpContext context) cache.SetMaxAge(new TimeSpan(30, 0, 0, 0)); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); - var etag = string.Format("\"{0}\"", hash); + var etag = $"\"{hash}\""; var incomingEtag = context.Request.Headers["If-None-Match"]; cache.SetETag(etag); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RsdHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RsdHandler.cs index 41a41a0ab..b2bd648f1 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RsdHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RsdHandler.cs @@ -50,8 +50,8 @@ public void ProcessRequest(HttpContext context) // Service rsd.WriteStartElement("service"); - rsd.WriteElementString("engineName", string.Format("BlogEngine.NET {0}", BlogSettings.Instance.Version())); - rsd.WriteElementString("engineLink", "http://dotnetblogengine.com"); + rsd.WriteElementString("engineName", $"BlogEngine.NET {BlogSettings.Instance.Version()}"); + rsd.WriteElementString("engineLink", "https://blogengine.io"); rsd.WriteElementString("homePageLink", Utils.AbsoluteWebRoot.ToString()); // APIs @@ -63,7 +63,7 @@ public void ProcessRequest(HttpContext context) rsd.WriteAttributeString("preferred", "true"); var prefix = BlogSettings.Instance.RequireSslMetaWeblogApi ? "https://" : "http://"; rsd.WriteAttributeString( - "apiLink", string.Format("{0}{1}{2}metaweblog.axd", prefix, context.Request.Url.Authority, Utils.RelativeWebRoot)); + "apiLink", $"{prefix}{context.Request.Url.Authority}{Utils.RelativeWebRoot}metaweblog.axd"); rsd.WriteAttributeString("blogID", Utils.AbsoluteWebRoot.ToString()); rsd.WriteEndElement(); @@ -71,7 +71,7 @@ public void ProcessRequest(HttpContext context) rsd.WriteStartElement("api"); rsd.WriteAttributeString("name", "BlogML"); rsd.WriteAttributeString("preferred", "false"); - rsd.WriteAttributeString("apiLink", string.Format("{0}api/BlogImporter.asmx", Utils.AbsoluteWebRoot)); + rsd.WriteAttributeString("apiLink", $"{Utils.AbsoluteWebRoot}api/BlogImporter.asmx"); rsd.WriteAttributeString("blogID", Utils.AbsoluteWebRoot.ToString()); rsd.WriteEndElement(); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Sioc.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Sioc.cs index 493f1c075..1464e4a83 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Sioc.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/Sioc.cs @@ -198,7 +198,7 @@ private static IPublishable ConvertToIPublishable(IPublishable item) /// private static string GetBlogAuthorUrl(string username) { - return string.Format("{0}author/{1}{2}", Utils.AbsoluteWebRoot, HttpUtility.UrlEncode(username), BlogConfig.FileExtension); + return $"{Utils.AbsoluteWebRoot}author/{HttpUtility.UrlEncode(username)}{BlogConfig.FileExtension}"; } /// @@ -227,8 +227,7 @@ private static Comment GetComment(Guid commentId) /// private static string GetSiocAuthorUrl(string username) { - return string.Format( - "{0}sioc.axd?sioc_type=user&sioc_id={1}", Utils.AbsoluteWebRoot, HttpUtility.UrlEncode(username)); + return $"{Utils.AbsoluteWebRoot}sioc.axd?sioc_type=user&sioc_id={HttpUtility.UrlEncode(username)}"; } /// @@ -239,7 +238,7 @@ private static string GetSiocAuthorUrl(string username) /// private static string GetSiocAuthorsUrl() { - return string.Format("{0}sioc.axd?sioc_type=site#authors", Utils.AbsoluteWebRoot); + return $"{Utils.AbsoluteWebRoot}sioc.axd?sioc_type=site#authors"; } /// @@ -250,7 +249,7 @@ private static string GetSiocAuthorsUrl() /// private static string GetSiocBlogUrl() { - return string.Format("{0}sioc.axd?sioc_type=site#webblog", Utils.AbsoluteWebRoot); + return $"{Utils.AbsoluteWebRoot}sioc.axd?sioc_type=site#webblog"; } /// @@ -264,7 +263,7 @@ private static string GetSiocBlogUrl() /// private static string GetSiocCommentUrl(string id) { - return string.Format("{0}sioc.axd?sioc_type=comment&sioc_id={1}", Utils.AbsoluteWebRoot, id); + return $"{Utils.AbsoluteWebRoot}sioc.axd?sioc_type=comment&sioc_id={id}"; } /// @@ -278,7 +277,7 @@ private static string GetSiocCommentUrl(string id) /// private static string GetSiocPostUrl(string id) { - return string.Format("{0}sioc.axd?sioc_type=post&sioc_id={1}", Utils.AbsoluteWebRoot, id); + return $"{Utils.AbsoluteWebRoot}sioc.axd?sioc_type=post&sioc_id={id}"; } /* @@ -391,7 +390,7 @@ private static void WriteAuthor(Stream stream, string authorName) /// private static void WriteFoafDocument(XmlWriter xmlWriter, string siocType, string url) { - var title = string.Format("SIOC {0} profile for \"{1}\"", siocType, BlogSettings.Instance.Name); + var title = $"SIOC {siocType} profile for \"{BlogSettings.Instance.Name}\""; const string Description = "A SIOC profile describes the structure and contents of a weblog in a machine readable form. For more information please refer to http://sioc-project.org/."; @@ -402,7 +401,7 @@ private static void WriteFoafDocument(XmlWriter xmlWriter, string siocType, stri xmlWriter.WriteElementString("dc", "description", null, Description); xmlWriter.WriteElementString("foaf", "primaryTopic", null, url); xmlWriter.WriteElementString( - "admin", "generatorAgent", null, string.Format("BlogEngine.NET{0}", BlogSettings.Instance.Version())); + "admin", "generatorAgent", null, $"BlogEngine.NET{BlogSettings.Instance.Version()}"); xmlWriter.WriteEndElement(); // foaf:Document } diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SiteMap.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SiteMap.cs index 236486ecb..4d4678b37 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SiteMap.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SiteMap.cs @@ -80,7 +80,7 @@ public void ProcessRequest(HttpContext context) // Contact writer.WriteStartElement("url"); - writer.WriteElementString("loc", string.Format("{0}contact.aspx", Utils.AbsoluteWebRoot)); + writer.WriteElementString("loc", $"{Utils.AbsoluteWebRoot}contact.aspx"); writer.WriteElementString("lastmod", DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); writer.WriteElementString("changefreq", "monthly"); writer.WriteEndElement(); @@ -89,7 +89,7 @@ public void ProcessRequest(HttpContext context) if (Page.GetFrontPage() != null) { writer.WriteStartElement("url"); - writer.WriteElementString("loc", string.Format("{0}blog.aspx", Utils.AbsoluteWebRoot)); + writer.WriteElementString("loc", $"{Utils.AbsoluteWebRoot}blog.aspx"); writer.WriteElementString( "lastmod", DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); writer.WriteElementString("changefreq", "daily"); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SyndicationHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SyndicationHandler.cs index 59bda9a9b..b4cd1c2ef 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SyndicationHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SyndicationHandler.cs @@ -185,7 +185,7 @@ private static List GenerateItemList(HttpContext context) client.Encoding = Encoding.Default; using (var stream = client.OpenRead(context.Request.QueryString["apml"])) { - var doc = new XmlDocument(); + var doc = new XmlDocument() { XmlResolver = null }; if (stream != null) { doc.Load(stream); @@ -330,7 +330,7 @@ private static string RetrieveTitle(HttpContext context) if (subTitle != null) { - return string.Format("{0} - {1}", title, subTitle); + return $"{title} - {subTitle}"; } return title; @@ -397,4 +397,4 @@ private static void StopServing(HttpContext context) #endregion } -} \ No newline at end of file +} diff --git a/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs b/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs index 9f0a27cd0..138d9d7f8 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs @@ -1,15 +1,10 @@ namespace BlogEngine.Core.Web.HttpModules { using System; - using System.IO; using System.IO.Compression; - using System.Text; - using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using System.Net; - using System.Net.Sockets; - using Microsoft.Ajax.Utilities; using BlogEngine.Core.Web.Scripting; /// @@ -207,7 +202,7 @@ private static void SetHeaders(HttpContext context) cache.SetMaxAge(new TimeSpan(365, 0, 0, 0)); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); - var etag = string.Format("\"{0}\"", context.Request.Path.GetHashCode()); + var etag = $"\"{context.Request.Path.GetHashCode()}\""; var incomingEtag = context.Request.Headers["If-None-Match"]; cache.SetETag(etag); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpModules/ReferrerModule.cs b/BlogEngine/BlogEngine.Core/Web/HttpModules/ReferrerModule.cs index aa7b90b18..5bf2f9ff0 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpModules/ReferrerModule.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpModules/ReferrerModule.cs @@ -132,7 +132,7 @@ private static bool IsSpam(Uri referrer, Uri url) if (subdomain != null) { - host = host.Replace(string.Format("{0}.", subdomain.ToUpperInvariant()), string.Empty); + host = host.Replace($"{subdomain.ToUpperInvariant()}.", string.Empty); } return !html.Contains(host); diff --git a/BlogEngine/BlogEngine.Core/Web/HttpModules/UrlRewrite.cs b/BlogEngine/BlogEngine.Core/Web/HttpModules/UrlRewrite.cs index 4d6b7d2ad..59bc4797e 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpModules/UrlRewrite.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpModules/UrlRewrite.cs @@ -55,7 +55,7 @@ private static void ContextBeginRequest(object sender, EventArgs e) url = url.Replace(".ASPX.CS", string.Empty); // skip url rewrite for web api calls - if (url.ToLower().StartsWith(string.Format("{0}api/", Utils.ApplicationRelativeWebRoot))) + if (url.ToLower().StartsWith($"{Utils.ApplicationRelativeWebRoot}api/")) { context.RewritePath(UrlRules.GetUrlWithQueryString(context)); return; diff --git a/BlogEngine/BlogEngine.Core/Web/Scripting/Helpers.cs b/BlogEngine/BlogEngine.Core/Web/Scripting/Helpers.cs index 2de3a8c67..71a14cf21 100644 --- a/BlogEngine/BlogEngine.Core/Web/Scripting/Helpers.cs +++ b/BlogEngine/BlogEngine.Core/Web/Scripting/Helpers.cs @@ -2,9 +2,6 @@ using System.Text; using System.Globalization; using System.Web.UI; -using System.Web.UI.HtmlControls; -using System.Collections.Generic; -using System.IO; namespace BlogEngine.Core.Web.Scripting { @@ -22,11 +19,9 @@ public static void AddStyle(System.Web.UI.Page page, string lnk) { // global styles on top, before theme specific styles if(lnk.Contains("Global.css") || lnk.Contains("Styles/css")) - page.Header.Controls.AddAt(0, new LiteralControl( - string.Format("\n", lnk))); + page.Header.Controls.AddAt(0, new LiteralControl($"\n")); else - page.Header.Controls.Add(new LiteralControl( - string.Format("\n", lnk))); + page.Header.Controls.Add(new LiteralControl($"\n")); } /// /// Add generic lit to the page @@ -38,7 +33,7 @@ public static void AddStyle(System.Web.UI.Page page, string lnk) /// Url public static void AddGenericLink(System.Web.UI.Page page, string type, string relation, string title, string href) { - var tp = string.IsNullOrEmpty(type) ? "" : string.Format("type=\"{0}\" ", type); + var tp = string.IsNullOrEmpty(type) ? "" : $"type=\"{type}\" "; const string tag = "\n"; page.Header.Controls.Add(new LiteralControl(string.Format(tag, tp, relation, title, href))); } @@ -141,7 +136,7 @@ public static void AddTrackingScript(System.Web.UI.Page page) var s = sb.ToString(); if (!string.IsNullOrEmpty(s)) { - page.ClientScript.RegisterStartupScript(page.GetType(), "tracking", string.Format("\n{0}", s), false); + page.ClientScript.RegisterStartupScript(page.GetType(), "tracking", $"\n{s}", false); } } diff --git a/BlogEngine/BlogEngine.Core/Web/Scripting/JavascriptMinifier.cs b/BlogEngine/BlogEngine.Core/Web/Scripting/JavascriptMinifier.cs index 91b317556..408e29227 100644 --- a/BlogEngine/BlogEngine.Core/Web/Scripting/JavascriptMinifier.cs +++ b/BlogEngine/BlogEngine.Core/Web/Scripting/JavascriptMinifier.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using Microsoft.Ajax.Utilities; namespace BlogEngine.Core.Web.Scripting diff --git a/BlogEngine/BlogEngine.Core/Web/Scripting/PageHeader.cs b/BlogEngine/BlogEngine.Core/Web/Scripting/PageHeader.cs index 5a167267c..11a7044bb 100644 --- a/BlogEngine/BlogEngine.Core/Web/Scripting/PageHeader.cs +++ b/BlogEngine/BlogEngine.Core/Web/Scripting/PageHeader.cs @@ -74,9 +74,9 @@ List GetStyles() var headerStyles = new List(); var tmpl = "\n\t"; - foreach (var f in GetFiles(string.Format("{0}Content/Auto", Utils.ApplicationRelativeWebRoot))) + foreach (var f in GetFiles($"{Utils.ApplicationRelativeWebRoot}Content/Auto")) { - var href = string.Format("{0}Content/Auto/{1}", Utils.ApplicationRelativeWebRoot, f); + var href = $"{Utils.ApplicationRelativeWebRoot}Content/Auto/{f}"; headerStyles.Add(new LiteralControl(string.Format(tmpl, href))); } return headerStyles; @@ -95,9 +95,9 @@ List GetScripts() var rsrc = HttpHandlers.ResourceHandler.GetScriptPath(new CultureInfo(lang)); headerScripts.Add(new LiteralControl(string.Format(tmpl, rsrc))); - foreach (var f in GetFiles(string.Format("{0}Scripts/Auto", Utils.ApplicationRelativeWebRoot))) + foreach (var f in GetFiles($"{Utils.ApplicationRelativeWebRoot}Scripts/Auto")) { - var href = string.Format("{0}Scripts/Auto/{1}", Utils.ApplicationRelativeWebRoot, f); + var href = $"{Utils.ApplicationRelativeWebRoot}Scripts/Auto/{f}"; headerScripts.Add(new LiteralControl(string.Format(tmpl, href))); } return headerScripts; diff --git a/BlogEngine/BlogEngine.Core/Web/Scripting/WebResourceFilter.cs b/BlogEngine/BlogEngine.Core/Web/Scripting/WebResourceFilter.cs index d40d002be..de21a49f5 100644 --- a/BlogEngine/BlogEngine.Core/Web/Scripting/WebResourceFilter.cs +++ b/BlogEngine/BlogEngine.Core/Web/Scripting/WebResourceFilter.cs @@ -1,10 +1,8 @@ using System; using System.IO; -using System.IO.Compression; using System.Text; using System.Text.RegularExpressions; using System.Web; -using System.Web.UI; using System.Net.Sockets; using System.Collections.Generic; using BlogEngine.Core.Data.Services; @@ -147,8 +145,7 @@ public override void Close() if (HtmlOut.Contains("", StringComparison.OrdinalIgnoreCase)) { HtmlOut = HtmlOut.Insert(idx, - string.Format("\n", - Utils.RelativeWebRoot, resKey.GetHashCode())); + $"\n"); } } } @@ -176,7 +173,7 @@ public string Evaluator(Match match) var relative = match.Groups[1].Value; var absolute = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); return match.Value.Replace( - relative, string.Format("{0}js.axd?path={1}", Utils.ApplicationRelativeWebRoot, HttpUtility.UrlEncode(absolute + relative))); + relative, $"{Utils.ApplicationRelativeWebRoot}js.axd?path={HttpUtility.UrlEncode(absolute + relative)}"); } /// diff --git a/BlogEngine/BlogEngine.Core/Web/UrlRules.cs b/BlogEngine/BlogEngine.Core/Web/UrlRules.cs index 49cd47300..87af2ac20 100644 --- a/BlogEngine/BlogEngine.Core/Web/UrlRules.cs +++ b/BlogEngine/BlogEngine.Core/Web/UrlRules.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Text.RegularExpressions; using System.Web; -using System.IO; namespace BlogEngine.Core.Web { @@ -67,13 +66,13 @@ public static void RewritePost(HttpContext context, string url) var q = GetQueryString(context); if (q.Contains("id=" + post.Id, StringComparison.OrdinalIgnoreCase)) - q = string.Format("{0}post.aspx?{1}", Utils.ApplicationRelativeWebRoot, q); + q = $"{Utils.ApplicationRelativeWebRoot}post.aspx?{q}"; else - q = string.Format("{0}post.aspx?id={1}{2}", Utils.ApplicationRelativeWebRoot, post.Id, q); + q = $"{Utils.ApplicationRelativeWebRoot}post.aspx?id={post.Id}{q}"; context.RewritePath( url.Contains("/FEED/") - ? string.Format("syndication.axd?post={0}{1}", post.Id, GetQueryString(context)) + ? $"syndication.axd?post={post.Id}{GetQueryString(context)}" : q, false); } @@ -92,7 +91,7 @@ public static void RewritePage(HttpContext context, string url) if (page != null) { - context.RewritePath(string.Format("{0}page.aspx?id={1}{2}", Utils.ApplicationRelativeWebRoot, page.Id, GetQueryString(context)), false); + context.RewritePath($"{Utils.ApplicationRelativeWebRoot}page.aspx?id={page.Id}{GetQueryString(context)}", false); } } @@ -139,7 +138,7 @@ private static void RewritePhysicalPageGeneric(HttpContext context, string url, { query = "?" + query.Substring(1); } - context.RewritePath(string.Format("{0}{1}{2}", Utils.ApplicationRelativeWebRoot, relativePath, query), false); + context.RewritePath($"{Utils.ApplicationRelativeWebRoot}{relativePath}{query}", false); } /// @@ -157,12 +156,12 @@ where title.Equals(legalTitle, StringComparison.OrdinalIgnoreCase) { if (url.Contains("/FEED/")) { - context.RewritePath(string.Format("syndication.axd?category={0}{1}", cat.Id, GetQueryString(context)), false); + context.RewritePath($"syndication.axd?category={cat.Id}{GetQueryString(context)}", false); } else { context.RewritePath( - string.Format("{0}default.aspx?id={1}{2}", Utils.ApplicationRelativeWebRoot, cat.Id, GetQueryString(context)), false); + $"{Utils.ApplicationRelativeWebRoot}default.aspx?id={cat.Id}{GetQueryString(context)}", false); break; } } @@ -179,11 +178,11 @@ public static void RewriteTag(HttpContext context, string url) if (url.Contains("/FEED/")) { - tag = string.Format("syndication.axd?tag={0}{1}", tag, GetQueryString(context)); + tag = $"syndication.axd?tag={tag}{GetQueryString(context)}"; } else { - tag = string.Format("{0}default.aspx?tag=/{1}{2}", Utils.ApplicationRelativeWebRoot, tag, GetQueryString(context)); + tag = $"{Utils.ApplicationRelativeWebRoot}default.aspx?tag=/{tag}{GetQueryString(context)}"; } context.RewritePath(tag, false); } @@ -210,7 +209,7 @@ public static void RewriteCalendar(HttpContext context, string url) if(url.Contains("default.aspx") && !url.Contains("calendar/default.aspx")) throw new HttpException(404, "File not found"); - context.RewritePath(string.Format("{0}default.aspx?calendar=show", Utils.ApplicationRelativeWebRoot), false); + context.RewritePath($"{Utils.ApplicationRelativeWebRoot}default.aspx?calendar=show", false); } /// @@ -222,10 +221,7 @@ public static void RewriteAuthor(HttpContext context, string url) { var author = UrlRules.ExtractTitle(context, url); - var path = string.Format("{0}default.aspx?name={1}{2}", - Utils.ApplicationRelativeWebRoot, - author, - GetQueryString(context)); + var path = $"{Utils.ApplicationRelativeWebRoot}default.aspx?name={author}{GetQueryString(context)}"; context.RewritePath(path, false); } @@ -237,9 +233,7 @@ public static void RewriteAuthor(HttpContext context, string url) /// The URL string. public static void RewriteBlog(HttpContext context, string url) { - var path = string.Format("{0}default.aspx?blog=true{1}", - Utils.ApplicationRelativeWebRoot, - GetQueryString(context)); + var path = $"{Utils.ApplicationRelativeWebRoot}default.aspx?blog=true{GetQueryString(context)}"; context.RewritePath(path, false); } @@ -254,7 +248,7 @@ public static void RewriteFilePath(HttpContext context, string url) var wr = url.Substring(0, url.IndexOf("/FILES/") + 6); url = url.Replace(wr, ""); url = url.Substring(0, url.LastIndexOf(System.IO.Path.GetExtension(url))); - var npath = string.Format("{0}file.axd?file={1}", Utils.ApplicationRelativeWebRoot, url); + var npath = $"{Utils.ApplicationRelativeWebRoot}file.axd?file={url}"; context.RewritePath(npath); } @@ -268,7 +262,7 @@ public static void RewriteImagePath(HttpContext context, string url) var wr = url.Substring(0, url.IndexOf("/IMAGES/") + 7); url = url.Replace(wr, ""); url = url.Substring(0, url.LastIndexOf(System.IO.Path.GetExtension(url))); - var npath = string.Format("{0}image.axd?picture={1}", Utils.ApplicationRelativeWebRoot, url); + var npath = $"{Utils.ApplicationRelativeWebRoot}image.axd?picture={url}"; context.RewritePath(npath); } @@ -281,7 +275,7 @@ public static void RewriteImagePath(HttpContext context, string url) public static void RewriteDefault(HttpContext context) { var url = GetUrlWithQueryString(context); - var page = string.Format("&page={0}", context.Request.QueryString["page"]); + var page = $"&page={context.Request.QueryString["page"]}"; if (string.IsNullOrEmpty(context.Request.QueryString["page"])) { @@ -294,22 +288,22 @@ public static void RewriteDefault(HttpContext context) var year = match.Groups[1].Value; var month = match.Groups[2].Value; var day = match.Groups[3].Value; - var date = string.Format("{0}-{1}-{2}", year, month, day); - url = string.Format("{0}default.aspx?date={1}{2}", Utils.ApplicationRelativeWebRoot, date, page); + var date = $"{year}-{month}-{day}"; + url = $"{Utils.ApplicationRelativeWebRoot}default.aspx?date={date}{page}"; } else if (YearMonthRegex.IsMatch(url)) { var match = YearMonthRegex.Match(url); var year = match.Groups[1].Value; var month = match.Groups[2].Value; - var path = string.Format("default.aspx?year={0}&month={1}", year, month); + var path = $"default.aspx?year={year}&month={month}"; url = Utils.ApplicationRelativeWebRoot + path + page; } else if (YearRegex.IsMatch(url)) { var match = YearRegex.Match(url); var year = match.Groups[1].Value; - var path = string.Format("default.aspx?year={0}", year); + var path = $"default.aspx?year={year}"; url = Utils.ApplicationRelativeWebRoot + path + page; } else @@ -337,7 +331,7 @@ public static void RewriteDefault(HttpContext context) public static bool DefaultPageRequested(HttpContext context) { var url = context.Request.Url.ToString(); - var match = string.Format("{0}DEFAULT{1}", Utils.AbsoluteWebRoot, BlogConfig.FileExtension); + var match = $"{Utils.AbsoluteWebRoot}DEFAULT{BlogConfig.FileExtension}"; var u = GetUrlWithQueryString(context); var m = YearMonthDayRegex.Match(u); @@ -470,7 +464,7 @@ public static string ExtractTitle(HttpContext context, string url) public static string GetQueryString(HttpContext context) { var query = context.Request.QueryString.ToString(); - return !string.IsNullOrEmpty(query) ? string.Format("&{0}", query) : string.Empty; + return !string.IsNullOrEmpty(query) ? $"&{query}" : string.Empty; } /// @@ -480,8 +474,7 @@ public static string GetQueryString(HttpContext context) /// Query string public static string GetUrlWithQueryString(HttpContext context) { - return string.Format( - "{0}?{1}", context.Request.Path, context.Request.QueryString.ToString()); + return $"{context.Request.Path}?{context.Request.QueryString}"; } #endregion diff --git a/BlogEngine/BlogEngine.NET/Account/account.master b/BlogEngine/BlogEngine.NET/Account/account.master index 8a44ec735..d68c57d68 100644 --- a/BlogEngine/BlogEngine.NET/Account/account.master +++ b/BlogEngine/BlogEngine.NET/Account/account.master @@ -6,7 +6,7 @@ Account Login - + @@ -22,7 +22,7 @@
'; + if (adminNav.length && adminAlert.length && (location.pathname == '/' || location.pathname == '/default.aspx')) { + adminAlert.prepend(adminAlertHtml); + } + + // + $(".blog-nav li a, [data-toggle=tooltip]").tooltip(); + +}); diff --git a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard-2017/theme.png b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard-2017/theme.png new file mode 100644 index 000000000..d80ea1d2a Binary files /dev/null and b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard-2017/theme.png differ diff --git a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard-2017/theme.xml b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard-2017/theme.xml new file mode 100644 index 000000000..b4086619c --- /dev/null +++ b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard-2017/theme.xml @@ -0,0 +1,9 @@ + + + Standard + This is the default theme for BlogEngine. + Francis Bio + http://francis.bio/ + 1.2 + + diff --git a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/CommentForm.ascx b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/CommentForm.ascx index 584f1617c..e39b510bf 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/CommentForm.ascx +++ b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/CommentForm.ascx @@ -7,7 +7,6 @@
-
<% if (BlogSettings.Instance.EnableWebsiteInComments) { %> @@ -18,21 +17,8 @@
- <% if (BlogSettings.Instance.ShowLivePreview) - { %> -
- -
- Loading -
-
- <% } %> +
-
- -
+ diff --git a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/Gruntfile.js b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/Gruntfile.js deleted file mode 100644 index c0ed21840..000000000 --- a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/Gruntfile.js +++ /dev/null @@ -1,25 +0,0 @@ -module.exports = function (grunt) { - grunt.initConfig({ - sass: { - dist: { - options: { - style: 'compressed', - noCache: true, - sourcemap: 'none' - }, - files: { - 'src/css/styles.min.css': 'src/scss/styles.scss', - } - } - }, - watch: { - src: { - files: ['src/scss/**/*.scss'], - tasks: ['sass'] - } - } - }); - grunt.loadNpmTasks('grunt-contrib-sass'); - grunt.loadNpmTasks('grunt-contrib-watch'); - grunt.registerTask('default', ['watch']); -}; diff --git a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/PostNavigation.ascx b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/PostNavigation.ascx index 1081e7343..cc29e107f 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/PostNavigation.ascx +++ b/BlogEngine/BlogEngine.NET/Custom/Themes/Standard/PostNavigation.ascx @@ -1,15 +1,15 @@ <%@ Control Language="C#" AutoEventWireup="true" EnableViewState="false" Inherits="BlogEngine.Core.Web.Controls.PostNavigationBase" %> -