From a7902cd80a21482999b9bc87d2a0073f5ca98a56 Mon Sep 17 00:00:00 2001 From: ThisWillDoIt Date: Mon, 3 Oct 2016 17:02:03 +0200 Subject: [PATCH] introduced string interpolation where it could simplify the code --- .../API/MetaWeblog/MetaWeblogHandler.cs | 8 +- .../API/MetaWeblog/XMLRPCRequest.cs | 4 +- BlogEngine/BlogEngine.Core/AuthorProfile.cs | 4 +- BlogEngine/BlogEngine.Core/Blog.cs | 10 +- BlogEngine/BlogEngine.Core/BlogSettings.cs | 4 +- BlogEngine/BlogEngine.Core/Category.cs | 2 +- BlogEngine/BlogEngine.Core/Comment.cs | 6 +- .../Data/CategoryRepository.cs | 4 +- .../Data/CustomFilterRepository.cs | 4 +- .../BlogEngine.Core/Data/LookupsRepository.cs | 2 +- .../BlogEngine.Core/Data/PackageRepository.cs | 2 +- .../BlogEngine.Core/Data/PageRepository.cs | 2 +- .../BlogEngine.Core/Data/PostRepository.cs | 2 +- .../BlogEngine.Core/Data/Services/Avatar.cs | 12 +-- .../Data/Services/CustomFieldsParser.cs | 2 +- .../BlogEngine.Core/Data/Services/TagCloud.cs | 4 +- .../BlogEngine.Core/Data/TagRepository.cs | 4 +- .../BlogEngine.Core/Helpers/BlogGenerator.cs | 6 +- BlogEngine/BlogEngine.Core/Helpers/Pager.cs | 2 +- BlogEngine/BlogEngine.Core/Helpers/Utils.cs | 26 +++--- .../Helpers/XmlSafeResolver.cs | 4 +- BlogEngine/BlogEngine.Core/Page.cs | 2 +- BlogEngine/BlogEngine.Core/Post.cs | 8 +- .../Providers/DbProvider/DbBlogProvider.cs | 92 +++++++++---------- .../DbProvider/DbMembershipProvider.cs | 8 +- .../Providers/DbProvider/DbRoleProvider.cs | 8 +- .../DbFileSystemProvider.cs | 4 +- .../UNCFileSystemProvider.cs | 6 +- .../XmlFileSystemProvider.cs | 6 +- .../Providers/XmlProvider/Categories.cs | 2 +- .../Providers/XmlProvider/DataStore.cs | 6 +- .../Providers/XmlProvider/Pages.cs | 12 +-- .../Providers/XmlProvider/Posts.cs | 10 +- .../Providers/XmlProvider/Profiles.cs | 14 +-- .../Providers/XmlProvider/Referrers.cs | 2 +- .../Providers/XmlProvider/Rights.cs | 4 +- .../Providers/XmlProvider/Settings.cs | 4 +- .../Providers/XmlProvider/StopWords.cs | 2 +- .../XmlProvider/XmlMembershipProvider.cs | 4 +- .../Providers/XmlProvider/XmlRoleProvider.cs | 2 +- BlogEngine/BlogEngine.Core/Referrer.cs | 4 +- .../BaseServerObjectExpressionBuilder.cs | 8 +- .../Compilation/ReflectExpressionBuilder.cs | 9 +- .../Services/FileSystem/File.cs | 4 +- .../Services/FileSystem/Image.cs | 2 +- .../Messaging/Protection/CommentHandlers.cs | 7 +- .../Services/Packaging/FileSystem.cs | 31 +++---- .../Services/Packaging/Gallery.cs | 8 +- .../Services/Packaging/Installer.cs | 6 +- .../Services/Packaging/Pager.cs | 2 +- .../Services/Security/Security.cs | 2 +- .../Syndication/BlogML/BlogImporter.cs | 2 +- .../Services/Syndication/BlogML/BlogReader.cs | 8 +- .../Syndication/SyndicationGenerator.cs | 4 +- .../Web/Controls/BlogBasePage.cs | 35 ++++--- .../Web/Controls/CommentViewBase.cs | 9 +- .../Web/Controls/PostViewBase.cs | 4 +- .../Web/Controls/RelatedPostsBase.cs | 4 +- .../Web/Extensions/ExtensionManager.cs | 2 +- .../Web/Extensions/ExtensionSettings.cs | 4 +- .../Web/HttpHandlers/FileHandler.cs | 12 +-- .../BlogEngine.Core/Web/HttpHandlers/Foaf.cs | 10 +- .../Web/HttpHandlers/ImageHandler.cs | 12 +-- .../Web/HttpHandlers/JavaScriptHandler.cs | 2 +- .../Web/HttpHandlers/OpenSearchHandler.cs | 6 +- .../Web/HttpHandlers/PingbackHandler.cs | 2 +- .../Web/HttpHandlers/RatingHandler.cs | 4 +- .../Web/HttpHandlers/ResourceHandler.cs | 4 +- .../Web/HttpHandlers/RsdHandler.cs | 6 +- .../BlogEngine.Core/Web/HttpHandlers/Sioc.cs | 17 ++-- .../Web/HttpHandlers/SiteMap.cs | 4 +- .../Web/HttpHandlers/SyndicationHandler.cs | 2 +- .../Web/HttpModules/CompressionModule.cs | 2 +- .../Web/HttpModules/ReferrerModule.cs | 2 +- .../Web/HttpModules/UrlRewrite.cs | 2 +- .../BlogEngine.Core/Web/Scripting/Helpers.cs | 10 +- .../Web/Scripting/PageHeader.cs | 8 +- .../Web/Scripting/WebResourceFilter.cs | 5 +- BlogEngine/BlogEngine.Core/Web/UrlRules.cs | 50 +++++----- .../AppCode/Api/SettingsController.cs | 2 +- .../AppCode/Api/ToolsController.cs | 2 +- .../AppCode/Controls/PostCalendar.cs | 4 +- .../AppCode/Controls/PostPager.cs | 8 +- .../AppCode/Controls/RelatedPosts.cs | 6 +- .../AppCode/Controls/WidgetBase.cs | 2 +- .../AppCode/Controls/WidgetContainer.cs | 4 +- .../BlogEngine.NET/AppCode/RazorHelpers.cs | 24 ++--- .../Custom/Controls/CommentList.ascx.cs | 8 +- .../Custom/Controls/PostList.ascx.cs | 4 +- .../Custom/Extensions/AkismetFilter.cs | 10 +- .../Custom/Extensions/BBCode.cs | 10 +- .../Custom/Extensions/BreakPost.cs | 2 +- .../Custom/Extensions/Recaptcha/Recaptcha.cs | 4 +- .../Extensions/Recaptcha/RecaptchaControl.cs | 54 +++++------ .../Recaptcha/RecaptchaValidator.cs | 2 +- .../Custom/Extensions/ResolveLinks.cs | 2 +- .../Custom/Extensions/SendCommentMail.cs | 6 +- .../Custom/Extensions/StopForumSpam.cs | 4 +- .../BlogEngine.NET/Custom/Widgets/Common.cs | 4 +- .../Custom/Widgets/LinkList/LinkList.cs | 6 +- .../Custom/Widgets/Newsletter/Newsletter.cs | 6 +- BlogEngine/BlogEngine.NET/archive.aspx.cs | 4 +- BlogEngine/BlogEngine.NET/error404.aspx.cs | 2 +- BlogEngine/BlogEngine.NET/page.aspx.cs | 4 +- BlogEngine/BlogEngine.NET/post.aspx.cs | 3 +- 105 files changed, 391 insertions(+), 421 deletions(-) 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..601da394d 100644 --- a/BlogEngine/BlogEngine.Core/API/MetaWeblog/XMLRPCRequest.cs +++ b/BlogEngine/BlogEngine.Core/API/MetaWeblog/XMLRPCRequest.cs @@ -339,7 +339,7 @@ private void LoadXmlRequest(string xml) } catch (Exception ex) { - throw new MetaWeblogException("01", string.Format("Invalid XMLRPC Request. ({0})", ex.Message)); + throw new MetaWeblogException("01", $"Invalid XMLRPC Request. ({ex.Message})"); } // Method name is always first @@ -449,7 +449,7 @@ private void LoadXmlRequest(string xml) this.PageID = this.inputParams[3].InnerText; break; default: - throw new MetaWeblogException("02", string.Format("Unknown Method. ({0})", this.MethodName)); + throw new MetaWeblogException("02", $"Unknown Method. ({MethodName})"); } } diff --git a/BlogEngine/BlogEngine.Core/AuthorProfile.cs b/BlogEngine/BlogEngine.Core/AuthorProfile.cs index a69c6c02f..141a3f3d8 100644 --- a/BlogEngine/BlogEngine.Core/AuthorProfile.cs +++ b/BlogEngine/BlogEngine.Core/AuthorProfile.cs @@ -300,7 +300,7 @@ public string FullName { get { - return string.Format("{0} {1} {2}", this.FirstName, this.MiddleName, this.LastName).Replace(" ", " "); + return $"{FirstName} {MiddleName} {LastName}".Replace(" ", " "); } } @@ -439,7 +439,7 @@ public string RelativeLink { get { - return string.Format("{0}author/{1}{2}", Utils.RelativeWebRoot, this.Id, BlogConfig.FileExtension); + return $"{Utils.RelativeWebRoot}author/{Id}{BlogConfig.FileExtension}"; } } diff --git a/BlogEngine/BlogEngine.Core/Blog.cs b/BlogEngine/BlogEngine.Core/Blog.cs index 2c9c8fad7..44a0417d8 100644 --- a/BlogEngine/BlogEngine.Core/Blog.cs +++ b/BlogEngine/BlogEngine.Core/Blog.cs @@ -629,7 +629,7 @@ public string StorageLocation return BlogConfig.StorageLocation; } - return string.Format("{0}{1}/{2}/", BlogConfig.StorageLocation, BlogConfig.BlogInstancesFolderName, this.StorageContainerName); + return $"{BlogConfig.StorageLocation}{BlogConfig.BlogInstancesFolderName}/{StorageContainerName}/"; } } @@ -676,7 +676,7 @@ public Uri AbsoluteWebRoot { get { - string contextItemKey = string.Format("{0}-absolutewebroot", this.Id); + string contextItemKey = $"{Id}-absolutewebroot"; var context = HttpContext.Current; if (context == null) @@ -955,7 +955,7 @@ internal bool CopyExistingBlogFolderToNewBlogFolder(Blog existingBlog) existingBlogStoragePath = HostingEnvironment.MapPath(existingBlog.StorageLocation); if (!Directory.Exists(existingBlogStoragePath)) { - throw new Exception(string.Format("Storage folder for existing blog instance to copy from does not exist. Directory not found is: {0}", existingBlogStoragePath)); + throw new Exception($"Storage folder for existing blog instance to copy from does not exist. Directory not found is: {existingBlogStoragePath}"); } } catch (Exception ex) @@ -965,7 +965,7 @@ internal bool CopyExistingBlogFolderToNewBlogFolder(Blog existingBlog) } // Ensure "BlogInstancesFolderName" exists. - string blogInstancesFolder = HostingEnvironment.MapPath(string.Format("{0}{1}", BlogConfig.StorageLocation, BlogConfig.BlogInstancesFolderName)); + string blogInstancesFolder = HostingEnvironment.MapPath($"{BlogConfig.StorageLocation}{BlogConfig.BlogInstancesFolderName}"); if (!Utils.CreateDirectoryIfNotExists(blogInstancesFolder)) return false; @@ -976,7 +976,7 @@ internal bool CopyExistingBlogFolderToNewBlogFolder(Blog existingBlog) { if (Directory.Exists(newBlogStoragePath)) { - throw new Exception(string.Format("Blog destination folder already exists. {0}", newBlogStoragePath)); + throw new Exception($"Blog destination folder already exists. {newBlogStoragePath}"); } } catch (Exception ex) diff --git a/BlogEngine/BlogEngine.Core/BlogSettings.cs b/BlogEngine/BlogEngine.Core/BlogSettings.cs index 046519796..9baada616 100644 --- a/BlogEngine/BlogEngine.Core/BlogSettings.cs +++ b/BlogEngine/BlogEngine.Core/BlogSettings.cs @@ -149,7 +149,7 @@ public bool IsRazorTheme /// 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); } @@ -1312,7 +1312,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/Category.cs b/BlogEngine/BlogEngine.Core/Category.cs index 03c1ba36c..75c52320c 100644 --- a/BlogEngine/BlogEngine.Core/Category.cs +++ b/BlogEngine/BlogEngine.Core/Category.cs @@ -366,7 +366,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/CategoryRepository.cs b/BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs index a81bd871d..199cb1b07 100644 --- a/BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/CategoryRepository.cs @@ -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/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/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/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..f9ba9a24d 100644 --- a/BlogEngine/BlogEngine.Core/Data/PageRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/PageRepository.cs @@ -182,7 +182,7 @@ static string GetUniqueSlug(string slug) if (IsUniqueSlug(s)) break; - s = string.Format("{0}{1}", slug, i); + s = $"{slug}{i}"; } return s; } diff --git a/BlogEngine/BlogEngine.Core/Data/PostRepository.cs b/BlogEngine/BlogEngine.Core/Data/PostRepository.cs index e0f5e0be8..71939f525 100644 --- a/BlogEngine/BlogEngine.Core/Data/PostRepository.cs +++ b/BlogEngine/BlogEngine.Core/Data/PostRepository.cs @@ -226,7 +226,7 @@ static string GetUniqueSlug(string slug) if (IsUniqueSlug(s)) break; - s = string.Format("{0}{1}", slug, i); + s = $"{slug}{i}"; } return s; } diff --git a/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs b/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs index 0052850c8..d1066683e 100644 --- a/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs +++ b/BlogEngine/BlogEngine.Core/Data/Services/Avatar.cs @@ -10,8 +10,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 +43,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 +65,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..f92f8e838 100644 --- a/BlogEngine/BlogEngine.Core/Data/Services/CustomFieldsParser.cs +++ b/BlogEngine/BlogEngine.Core/Data/Services/CustomFieldsParser.cs @@ -159,7 +159,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/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/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/Helpers/BlogGenerator.cs b/BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs index a4520b763..d17ef1838 100644 --- a/BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs +++ b/BlogEngine/BlogEngine.Core/Helpers/BlogGenerator.cs @@ -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 104ece95f..0deb1fa08 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)); } } @@ -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; } @@ -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}"); } /// @@ -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; @@ -1303,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); } /// @@ -1320,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 { @@ -1542,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..338dc0253 100644 --- a/BlogEngine/BlogEngine.Core/Post.cs +++ b/BlogEngine/BlogEngine.Core/Post.cs @@ -478,7 +478,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 +659,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}"); } } @@ -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/Providers/DbProvider/DbBlogProvider.cs b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbBlogProvider.cs index aa562249d..6b45e81ca 100644 --- a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbBlogProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbBlogProvider.cs @@ -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())); @@ -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())); @@ -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(); @@ -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())); @@ -2202,7 +2202,7 @@ public override void SaveSettings(StringDictionary settings) { 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()) @@ -2295,12 +2295,12 @@ public override void SaveRights(IEnumerable rights) { 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/DbMembershipProvider.cs b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbMembershipProvider.cs index f10a50e90..7c91068f7 100644 --- a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbMembershipProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbMembershipProvider.cs @@ -397,7 +397,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 +410,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())); @@ -638,7 +638,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 +803,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..a046699ba 100644 --- a/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbRoleProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/DbProvider/DbRoleProvider.cs @@ -205,7 +205,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 +238,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())); @@ -416,7 +416,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 +577,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/DbFileSystemProvider.cs b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/DbFileSystemProvider.cs index 597467628..b6552a96e 100644 --- a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/DbFileSystemProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/DbFileSystemProvider.cs @@ -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}"); } } } @@ -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..c10e4b285 100644 --- a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/UNCFileSystemProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/UNCFileSystemProvider.cs @@ -206,7 +206,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 +220,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 +299,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..e45cb6c03 100644 --- a/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/XmlFileSystemProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/FileSystemProviders/XmlFileSystemProvider.cs @@ -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/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/DataStore.cs b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/DataStore.cs index 090699d5a..23ae37347 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/DataStore.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/DataStore.cs @@ -129,7 +129,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 +142,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 +160,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/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/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..7aef3ca07 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Rights.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Rights.cs @@ -26,7 +26,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 +78,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..6fb7c0001 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Settings.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/Settings.cs @@ -23,7 +23,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(); @@ -57,7 +57,7 @@ public override void SaveSettings(StringDictionary settings) throw new ArgumentNullException("settings"); } - var filename = string.Format("{0}settings.xml", this.Folder); + var filename = string.Format("{0}settings.xml", Folder); 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..fe6aa731c 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlMembershipProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlMembershipProvider.cs @@ -658,7 +658,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 +852,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 efee86b05..ac7d2f5f2 100644 --- a/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlRoleProvider.cs +++ b/BlogEngine/BlogEngine.Core/Providers/XmlProvider/XmlRoleProvider.cs @@ -328,7 +328,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}"); } } } 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/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/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/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/Protection/CommentHandlers.cs b/BlogEngine/BlogEngine.Core/Services/Messaging/Protection/CommentHandlers.cs index 064806b67..ec0955a08 100644 --- a/BlogEngine/BlogEngine.Core/Services/Messaging/Protection/CommentHandlers.cs +++ b/BlogEngine/BlogEngine.Core/Services/Messaging/Protection/CommentHandlers.cs @@ -75,7 +75,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 +92,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 +539,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..4a86736f8 100644 --- a/BlogEngine/BlogEngine.Core/Services/Packaging/FileSystem.cs +++ b/BlogEngine/BlogEngine.Core/Services/Packaging/FileSystem.cs @@ -80,7 +80,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 +105,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 +154,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 +198,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 +214,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 +249,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 +392,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 +420,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); @@ -461,8 +458,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 +512,10 @@ public static void CreateManifestIfNotExists(NuGet.IPackage package, List 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/Security/Security.cs b/BlogEngine/BlogEngine.Core/Services/Security/Security.cs index ad158760f..46359c46c 100644 --- a/BlogEngine/BlogEngine.Core/Services/Security/Security.cs +++ b/BlogEngine/BlogEngine.Core/Services/Security/Security.cs @@ -173,7 +173,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 ); 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 69fecbee2..5357ed705 100644 --- a/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogReader.cs +++ b/BlogEngine/BlogEngine.Core/Services/Syndication/BlogML/BlogReader.cs @@ -83,7 +83,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 +98,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; } @@ -398,7 +398,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..047219ca8 100644 --- a/BlogEngine/BlogEngine.Core/Services/Syndication/SyndicationGenerator.cs +++ b/BlogEngine/BlogEngine.Core/Services/Syndication/SyndicationGenerator.cs @@ -845,7 +845,7 @@ private void WriteAtomContent(XmlWriter writer, 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/Controls/BlogBasePage.cs b/BlogEngine/BlogEngine.Core/Web/Controls/BlogBasePage.cs index 0c474e64c..3854eb632 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/BlogBasePage.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/BlogBasePage.cs @@ -76,9 +76,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 +121,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 +147,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 +165,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 +202,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 +232,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}"; } } @@ -260,7 +258,7 @@ string GetSiteMaster() { if (Request.FilePath.Contains("post.aspx", StringComparison.InvariantCultureIgnoreCase)) { - string path = string.Format("{0}Custom/Themes/{1}/post.master", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.Theme); + string path = $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{BlogSettings.Instance.Theme}/post.master"; if (System.IO.File.Exists(Server.MapPath(path))) return path; } @@ -274,18 +272,17 @@ string GetSiteMaster() Request.FilePath.Contains("error404.aspx", StringComparison.InvariantCultureIgnoreCase) || Request.FilePath.Contains("search.aspx", StringComparison.InvariantCultureIgnoreCase)) { - string path = string.Format("{0}Custom/Themes/{1}/page.master", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.Theme); + string path = $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{BlogSettings.Instance.Theme}/page.master"; if (System.IO.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"; if (System.IO.File.Exists(Server.MapPath(siteMaster))) return siteMaster; else - return string.Format("{0}Custom/Themes/Standard/site.master", Utils.ApplicationRelativeWebRoot); + return $"{Utils.ApplicationRelativeWebRoot}Custom/Themes/Standard/site.master"; } } diff --git a/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs b/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs index ee0c418b5..f892ea5a7 100644 --- a/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs +++ b/BlogEngine/BlogEngine.Core/Web/Controls/CommentViewBase.cs @@ -180,11 +180,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 +213,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/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..d89f5d54c 100644 --- a/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionManager.cs +++ b/BlogEngine/BlogEngine.Core/Web/Extensions/ExtensionManager.cs @@ -510,7 +510,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/HttpHandlers/FileHandler.cs b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/FileHandler.cs index ea1b74acd..24a706a1e 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/FileHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/FileHandler.cs @@ -75,18 +75,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 +97,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..0f90658a0 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ImageHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ImageHandler.cs @@ -73,16 +73,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 +93,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 +101,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..acbd78923 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/PingbackHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/PingbackHandler.cs @@ -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(); 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..a190d56e3 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ResourceHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/ResourceHandler.cs @@ -160,7 +160,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 +184,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..970eddff1 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RsdHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/RsdHandler.cs @@ -50,7 +50,7 @@ public void ProcessRequest(HttpContext context) // Service rsd.WriteStartElement("service"); - rsd.WriteElementString("engineName", string.Format("BlogEngine.NET {0}", BlogSettings.Instance.Version())); + rsd.WriteElementString("engineName", $"BlogEngine.NET {BlogSettings.Instance.Version()}"); rsd.WriteElementString("engineLink", "http://dotnetblogengine.com"); rsd.WriteElementString("homePageLink", Utils.AbsoluteWebRoot.ToString()); @@ -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..77e8afdbf 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SyndicationHandler.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpHandlers/SyndicationHandler.cs @@ -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; diff --git a/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs b/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs index 9f0a27cd0..b1f80faee 100644 --- a/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs +++ b/BlogEngine/BlogEngine.Core/Web/HttpModules/CompressionModule.cs @@ -207,7 +207,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..c19ace192 100644 --- a/BlogEngine/BlogEngine.Core/Web/Scripting/Helpers.cs +++ b/BlogEngine/BlogEngine.Core/Web/Scripting/Helpers.cs @@ -22,11 +22,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 +36,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 +139,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/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..ec3cfd371 100644 --- a/BlogEngine/BlogEngine.Core/Web/Scripting/WebResourceFilter.cs +++ b/BlogEngine/BlogEngine.Core/Web/Scripting/WebResourceFilter.cs @@ -147,8 +147,7 @@ public override void Close() if (HtmlOut.Contains("", StringComparison.OrdinalIgnoreCase)) { HtmlOut = HtmlOut.Insert(idx, - string.Format("\n", - Utils.RelativeWebRoot, resKey.GetHashCode())); + $"\n"); } } } @@ -176,7 +175,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..12c895ebb 100644 --- a/BlogEngine/BlogEngine.Core/Web/UrlRules.cs +++ b/BlogEngine/BlogEngine.Core/Web/UrlRules.cs @@ -67,13 +67,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 +92,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 +139,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 +157,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 +179,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 +210,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 +222,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 +234,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 +249,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 +263,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 +276,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 +289,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 +332,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 +465,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 +475,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/AppCode/Api/SettingsController.cs b/BlogEngine/BlogEngine.NET/AppCode/Api/SettingsController.cs index f0d733a80..7db28ffe7 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/Api/SettingsController.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/Api/SettingsController.cs @@ -61,7 +61,7 @@ string TestEmail(Settings settings) var mail = new MailMessage { From = new MailAddress(email, smtpUserName), - Subject = string.Format("Test mail from {0}", smtpUserName), + Subject = $"Test mail from {smtpUserName}", IsBodyHtml = true }; mail.To.Add(mail.From); diff --git a/BlogEngine/BlogEngine.NET/AppCode/Api/ToolsController.cs b/BlogEngine/BlogEngine.NET/AppCode/Api/ToolsController.cs index d286ea545..cd02fcf74 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/Api/ToolsController.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/Api/ToolsController.cs @@ -110,7 +110,7 @@ private static string GetFileName(string dir) if (dir == "data") return HostingEnvironment.MapPath("~/App_Data/tmp.txt"); - return HostingEnvironment.MapPath(string.Format("~/{0}/tmp.txt", dir)); + return HostingEnvironment.MapPath($"~/{dir}/tmp.txt"); } AspNetHostingPermissionLevel GetCurrentTrustLevel() diff --git a/BlogEngine/BlogEngine.NET/AppCode/Controls/PostCalendar.cs b/BlogEngine/BlogEngine.NET/AppCode/Controls/PostCalendar.cs index 9ee3d5a80..3a31892a1 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/Controls/PostCalendar.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/Controls/PostCalendar.cs @@ -112,7 +112,7 @@ protected override void OnDayRender(TableCell cell, CalendarDay day) { cell.Controls.Add(new LiteralControl(day.DayNumberText)); foreach (var a in - list.Where(post => post.IsVisible).Select(post => new HtmlAnchor { InnerHtml = string.Format("

{0}", post.Title), HRef = post.RelativeOrAbsoluteLink })) + list.Where(post => post.IsVisible).Select(post => new HtmlAnchor { InnerHtml = $"

{post.Title}", HRef = post.RelativeOrAbsoluteLink })) { cell.Controls.Add(a); } @@ -125,7 +125,7 @@ protected override void OnDayRender(TableCell cell, CalendarDay day) { InnerHtml = day.DayNumberText, HRef = - string.Format("{0}{1}/{2}/{3}/default{4}", Utils.RelativeOrAbsoluteWebRoot, date.Year, date.Month.ToString("00"), date.Day.ToString("00"), BlogConfig.FileExtension) + $"{Utils.RelativeOrAbsoluteWebRoot}{date.Year}/{date.Month.ToString("00")}/{date.Day.ToString("00")}/default{BlogConfig.FileExtension}" }; a.Attributes["class"] = "exist"; cell.Controls.Add(a); diff --git a/BlogEngine/BlogEngine.NET/AppCode/Controls/PostPager.cs b/BlogEngine/BlogEngine.NET/AppCode/Controls/PostPager.cs index 9f990a276..77046c16a 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/Controls/PostPager.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/Controls/PostPager.cs @@ -239,10 +239,10 @@ private string PagerTag() } var pageFirstUrl = PageFirstUrl(); var retValue = string.Empty; - var link = string.Format("
  • {{1}}
  • ", PageUrl()); - var linkNewerFirst = string.Format("
  • {{1}}
  • ", pageFirstUrl); + var link = $"
  • {{1}}
  • "; + var linkNewerFirst = $"
  • {{1}}
  • "; const string LinkCurrent = "
  • {0}
  • "; - var linkFirst = string.Format("
  • {{0}}
  • ", pageFirstUrl); + var linkFirst = $"
  • {{0}}
  • "; const string LinkDisabled = "
  • {0}
  • "; var currentPage = PageIndex(); @@ -258,7 +258,7 @@ private string PagerTag() } if (currentPage > pagesTotal) - return string.Format("

    {0}

    ", labels.noPostsMatchedYourCriteria); + return $"

    {labels.noPostsMatchedYourCriteria}

    "; if (postCnt > 0 && pagesTotal > 1) { diff --git a/BlogEngine/BlogEngine.NET/AppCode/Controls/RelatedPosts.cs b/BlogEngine/BlogEngine.NET/AppCode/Controls/RelatedPosts.cs index cbe87bf01..e9fc2561f 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/Controls/RelatedPosts.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/Controls/RelatedPosts.cs @@ -219,15 +219,15 @@ private void CreateList(IEnumerable relatedPosts) 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; + ? $"{content.Substring(0, DescriptionMaxLength)}..." + : content; } sb.Append(string.Format(DescriptionFormat, description)); diff --git a/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetBase.cs b/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetBase.cs index e7152fe71..06e3941f2 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetBase.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetBase.cs @@ -81,7 +81,7 @@ public virtual bool DisplayHeader /// public StringDictionary GetSettings() { - var cacheId = string.Format("be_widget_{0}", this.WidgetId); + var cacheId = $"be_widget_{WidgetId}"; if (Blog.CurrentInstance.Cache[cacheId] == null) { var ws = new WidgetSettings(this.WidgetId.ToString()); diff --git a/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetContainer.cs b/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetContainer.cs index 0761f9c80..f7a2457d5 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetContainer.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/Controls/WidgetContainer.cs @@ -143,14 +143,14 @@ public static string GetThemeWidgetContainerVirtualPath(bool existenceCheck) { // if it's a Razor theme, check if WidgetContainer.cshtml exists. string filename = BlogSettings.Instance.IsRazorTheme ? "WidgetContainer.cshtml" : "WidgetContainer.ascx"; - return string.Format("~/Custom/Themes/{0}/{1}", BlogSettings.Instance.Theme, filename); + return $"~/Custom/Themes/{BlogSettings.Instance.Theme}/{filename}"; } else { // when existenceCheck == false, the actual file that will be loaded needs to be // returned. if it's a Razor theme, we will load WidgetContainer.ascx in the // RazorHost folder. we assume that the RazorHost folder contains WidgetContainer.ascx. - return string.Format("~/Custom/Themes/{0}/WidgetContainer.ascx", BlogSettings.Instance.GetThemeWithAdjustments(null)); + return $"~/Custom/Themes/{BlogSettings.Instance.GetThemeWithAdjustments(null)}/WidgetContainer.ascx"; } } diff --git a/BlogEngine/BlogEngine.NET/AppCode/RazorHelpers.cs b/BlogEngine/BlogEngine.NET/AppCode/RazorHelpers.cs index f284bb56d..0d878db7d 100644 --- a/BlogEngine/BlogEngine.NET/AppCode/RazorHelpers.cs +++ b/BlogEngine/BlogEngine.NET/AppCode/RazorHelpers.cs @@ -43,25 +43,25 @@ public static string RenderControl(this HtmlHelper helper, string typeName, IEnu } else { - Utils.Log(string.Format("Unable to cast the instantiated object as a control: {0}", typeName)); + Utils.Log($"Unable to cast the instantiated object as a control: {typeName}"); } } else { - Utils.Log(string.Format("Unable to activate control: {0}", typeName)); + Utils.Log($"Unable to activate control: {typeName}"); } } else { - Utils.Log(string.Format("Unable to load control type: {0}", typeName)); + Utils.Log($"Unable to load control type: {typeName}"); } } catch (Exception ex) { - Utils.Log(string.Format("Unable to load control: {0}", typeName), ex); + Utils.Log($"Unable to load control: {typeName}", ex); } - return HttpUtility.HtmlEncode(string.Format("ERROR - UNABLE TO LOAD CONTROL : {0}", typeName)); + return HttpUtility.HtmlEncode($"ERROR - UNABLE TO LOAD CONTROL : {typeName}"); } /// @@ -79,15 +79,15 @@ public static string RenderUserControl(this HtmlHelper helper, string controlVir } else { - Utils.Log(string.Format("Page is null when trying to render control: {0}", controlVirtualPath)); + Utils.Log($"Page is null when trying to render control: {controlVirtualPath}"); } } catch (Exception ex) { - Utils.Log(string.Format("Unable to load control: {0}", controlVirtualPath), ex); + Utils.Log($"Unable to load control: {controlVirtualPath}", ex); } - return HttpUtility.HtmlEncode(string.Format("ERROR - UNABLE TO LOAD CONTROL : {0}", controlVirtualPath)); + return HttpUtility.HtmlEncode($"ERROR - UNABLE TO LOAD CONTROL : {controlVirtualPath}"); } /// @@ -99,7 +99,7 @@ public static string RenderControl(this HtmlHelper helper, Control control, IEnu { if (string.IsNullOrWhiteSpace(control.ID)) { - control.ID = string.Format("control_{0}", Guid.NewGuid()); + control.ID = $"control_{Guid.NewGuid()}"; } if (properties != null && properties.Count() > 0) @@ -144,10 +144,10 @@ public static string RenderControl(this HtmlHelper helper, Control control, IEnu } catch (Exception ex) { - Utils.Log(string.Format("Unable to load control: {0}", control.GetType().ToString()), ex); + Utils.Log($"Unable to load control: {control.GetType()}", ex); } - return HttpUtility.HtmlEncode(string.Format("ERROR - UNABLE TO LOAD CONTROL : {0}", control.GetType().ToString())); + return HttpUtility.HtmlEncode($"ERROR - UNABLE TO LOAD CONTROL : {control.GetType()}"); } public const string PAGE_BODY_MARKER = "-|-|-|-|-|-|- PAGE-BODY -|-|-|-|-|-|-"; @@ -194,7 +194,7 @@ public static string ParseRazor(string virtualPath, object model) } catch (Exception ex) { - Utils.Log(string.Format("RazorHelper, ParseRazor, VirtualPath: {0}", virtualPath), ex); + Utils.Log($"RazorHelper, ParseRazor, VirtualPath: {virtualPath}", ex); // return the error message since it will usually contain parsing // details when the Razor markup/syntax is invalid. this will help diff --git a/BlogEngine/BlogEngine.NET/Custom/Controls/CommentList.ascx.cs b/BlogEngine/BlogEngine.NET/Custom/Controls/CommentList.ascx.cs index ad1ad3f9a..e006472dc 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Controls/CommentList.ascx.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Controls/CommentList.ascx.cs @@ -342,7 +342,7 @@ public void RaiseCallbackEvent(string eventArgument) { if (!website.ToLowerInvariant().Contains("://")) { - website = string.Format("http://{0}", website); + website = $"http://{website}"; } Uri url; @@ -452,7 +452,7 @@ protected string BBCodes() foreach (DataRow row in table.Rows) { var code = (string)row["Code"]; - var title = string.Format("[{0}][/{1}]", code, code); + var title = $"[{code}][/{code}]"; sb.AppendFormat( "{2}", title, @@ -486,7 +486,7 @@ protected override void OnLoad(EventArgs e) return; } - NameInputId = string.Format("txtName{0}", DateTime.Now.Ticks); + NameInputId = $"txtName{DateTime.Now.Ticks}"; EnableCaptchas(); if (!Page.IsPostBack && !Page.IsCallback) @@ -973,7 +973,7 @@ protected string FlagUrl() //return !string.IsNullOrEmpty(ddlCountry.SelectedValue) // ? string.Format("{0}Content/images/blog/flags/{1}.png", Utils.RelativeWebRoot, ddlCountry.SelectedValue) // : string.Format("{0}Content/images/blog/pixel.png", Utils.RelativeWebRoot); - return string.Format("{0}Content/images/blog/pixel.png", Utils.RelativeWebRoot); + return $"{Utils.RelativeWebRoot}Content/images/blog/pixel.png"; } #endregion diff --git a/BlogEngine/BlogEngine.NET/Custom/Controls/PostList.ascx.cs b/BlogEngine/BlogEngine.NET/Custom/Controls/PostList.ascx.cs index 380c757bd..248bfec31 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Controls/PostList.ascx.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Controls/PostList.ascx.cs @@ -178,8 +178,8 @@ private void InitPaging() path = path.Contains("?") ? (path.Contains("page=") ? path.Substring(0, path.IndexOf("page=")) - : string.Format("{0}&", path)) - : string.Format("{0}?", path); + : $"{path}&") + : $"{path}?"; var page = this.GetPageIndex(); var url = string.Format("{0}page={{0}}", path); diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/AkismetFilter.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/AkismetFilter.cs index 97bb59582..4795abf02 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/AkismetFilter.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/AkismetFilter.cs @@ -146,7 +146,7 @@ public Akismet(string apiKey, string blog, string userAgent) this.apiKey = apiKey; if (userAgent != null) { - this.userAgent = string.Format("{0} | Akismet/1.11", userAgent); + this.userAgent = $"{userAgent} | Akismet/1.11"; } this.blog = blog; @@ -300,7 +300,7 @@ private string HttpPost(string url, string data, string charset) // Initialize Connection var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; - request.ContentType = string.Format("application/x-www-form-urlencoded; charset={0}", charset); + request.ContentType = $"application/x-www-form-urlencoded; charset={charset}"; request.UserAgent = this.userAgent; request.ContentLength = data.Length; @@ -523,7 +523,7 @@ public bool Initialize() Site = Settings.GetSingleValue("SiteURL"); Key = Settings.GetSingleValue("ApiKey"); - Api = new Akismet(Key, Site, string.Format("BlogEngine.NET {0}", BlogSettings.Instance.Version())); + Api = new Akismet(Key, Site, $"BlogEngine.NET {BlogSettings.Instance.Version()}"); return Api.VerifyKey(); } @@ -551,12 +551,12 @@ public void Report(Comment comment) if (comment.IsApproved) { Utils.Log( - string.Format("Akismet: Reporting NOT spam from \"{0}\" at \"{1}\"", comment.Author, comment.IP)); + $"Akismet: Reporting NOT spam from \"{comment.Author}\" at \"{comment.IP}\""); Api.SubmitHam(akismetComment); } else { - Utils.Log(string.Format("Akismet: Reporting SPAM from \"{0}\" at \"{1}\"", comment.Author, comment.IP)); + Utils.Log($"Akismet: Reporting SPAM from \"{comment.Author}\" at \"{comment.IP}\""); Api.SubmitSpam(akismetComment); } } diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/BBCode.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/BBCode.cs index 6268bfe69..8601d7c94 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/BBCode.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/BBCode.cs @@ -134,24 +134,24 @@ private static void Parse(ref string body, string code, string tag) /// private static void Parse(ref string body, string code, string startTag, string endTag) { - var start = body.IndexOf(string.Format("[{0}]", code)); + var start = body.IndexOf($"[{code}]"); if (start <= -1) { return; } - if (body.IndexOf(string.Format("[/{0}]", code), start) <= -1) + if (body.IndexOf($"[/{code}]", start) <= -1) { return; } body = body.Remove(start, code.Length + 2); - body = body.Insert(start, string.Format("<{0}>", startTag)); + body = body.Insert(start, $"<{startTag}>"); - var end = body.IndexOf(string.Format("[/{0}]", code), start); + var end = body.IndexOf($"[/{code}]", start); body = body.Remove(end, code.Length + 3); - body = body.Insert(end, string.Format("", endTag)); + body = body.Insert(end, $""); Parse(ref body, code, startTag); } diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/BreakPost.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/BreakPost.cs index a77243665..8c2582aa6 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/BreakPost.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/BreakPost.cs @@ -66,7 +66,7 @@ private static void AddMoreLink(object sender, ServingEventArgs e) { var post = (Post)sender; var index = e.Body.IndexOf("[more]"); - var link = string.Format("{1}...", post.RelativeLink, labels.more); + var link = $"{labels.more}..."; var newBody = e.Body.Substring(0, index); // Need to close any open HTML tags in NewBody where the matching close tags have been truncated. diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/Recaptcha.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/Recaptcha.cs index 054f4dd84..e33580c99 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/Recaptcha.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/Recaptcha.cs @@ -141,9 +141,7 @@ private static ExtensionSettings Settings settings.AddValue("Language", new[] { "en|English", "nl|Dutch", "fr|French", "de|German", "pt|Portuguese", "ru|Russian", "es|Spanish", "tr|Turkish" }, "en"); settings.Help = - string.Format( - "\n\nYou can create your own public key at http://www.Recaptcha.net. This is used for communication between your website and the recapcha server.

    Please rememeber you need to enable extension for reCaptcha to show up on the comments form.

    You can see some statistics on Captcha solving by storing successful attempts. If you're getting spam, this should also confirm that the spammers are at least solving the captcha.

    Click here to view the log", - JScript); + $"\n\nYou can create your own public key at http://www.Recaptcha.net. This is used for communication between your website and the recapcha server.

    Please rememeber you need to enable extension for reCaptcha to show up on the comments form.

    You can see some statistics on Captcha solving by storing successful attempts. If you're getting spam, this should also confirm that the spammers are at least solving the captcha.

    Click here to view the log"; blogsSettings[blogId] = ExtensionManager.InitSettings("Recaptcha", settings); diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaControl.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaControl.cs index b40fb9402..c65077f87 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaControl.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaControl.cs @@ -192,22 +192,22 @@ internal DateTime PageLoadTime { get { - return Blog.CurrentInstance.Cache[string.Format("{0}PageLoadTime", this.UserUniqueIdentifier)] != null + return Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}PageLoadTime"] != null ? Convert.ToDateTime( - Blog.CurrentInstance.Cache[string.Format("{0}PageLoadTime", this.UserUniqueIdentifier)]) + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}PageLoadTime"]) : DateTime.Now; } set { - if (Blog.CurrentInstance.Cache[string.Format("{0}PageLoadTime", this.UserUniqueIdentifier)] != null) + if (Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}PageLoadTime"] != null) { - Blog.CurrentInstance.Cache[string.Format("{0}PageLoadTime", this.UserUniqueIdentifier)] = value; + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}PageLoadTime"] = value; } else { Blog.CurrentInstance.Cache.Add( - string.Format("{0}PageLoadTime", this.UserUniqueIdentifier), + $"{UserUniqueIdentifier}PageLoadTime", value, null, Cache.NoAbsoluteExpiration, @@ -225,23 +225,23 @@ internal ushort RecaptchaAttempts { get { - return Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaAttempts", this.UserUniqueIdentifier)] != + return Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaAttempts"] != null ? Convert.ToUInt16( - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaAttempts", this.UserUniqueIdentifier)]) + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaAttempts"]) : (ushort)0; } set { - if (Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaAttempts", this.UserUniqueIdentifier)] != null) + if (Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaAttempts"] != null) { - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaAttempts", this.UserUniqueIdentifier)] = value; + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaAttempts"] = value; } else { Blog.CurrentInstance.Cache.Add( - string.Format("{0}RecaptchaAttempts", this.UserUniqueIdentifier), + $"{UserUniqueIdentifier}RecaptchaAttempts", value, null, Cache.NoAbsoluteExpiration, @@ -260,25 +260,25 @@ internal string RecaptchaChallengeValue get { return - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaChallengeValue", this.UserUniqueIdentifier)] != + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaChallengeValue"] != null ? Convert.ToString( - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaChallengeValue", this.UserUniqueIdentifier)]) + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaChallengeValue"]) : string.Empty; } set { - if (Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaChallengeValue", this.UserUniqueIdentifier)] != + if (Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaChallengeValue"] != null) { - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaChallengeValue", this.UserUniqueIdentifier)] = + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaChallengeValue"] = value; } else { Blog.CurrentInstance.Cache.Add( - string.Format("{0}RecaptchaChallengeValue", this.UserUniqueIdentifier), + $"{UserUniqueIdentifier}RecaptchaChallengeValue", value, null, Cache.NoAbsoluteExpiration, @@ -296,25 +296,25 @@ internal DateTime RecaptchaRenderTime { get { - return Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaRenderTime", this.UserUniqueIdentifier)] != + return Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaRenderTime"] != null ? Convert.ToDateTime( - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaRenderTime", this.UserUniqueIdentifier)]) + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaRenderTime"]) : DateTime.Now; } set { - if (Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaRenderTime", this.UserUniqueIdentifier)] != + if (Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaRenderTime"] != null) { - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaRenderTime", this.UserUniqueIdentifier)] = + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaRenderTime"] = value; } else { Blog.CurrentInstance.Cache.Add( - string.Format("{0}RecaptchaRenderTime", this.UserUniqueIdentifier), + $"{UserUniqueIdentifier}RecaptchaRenderTime", value, null, Cache.NoAbsoluteExpiration, @@ -333,25 +333,25 @@ internal string RecaptchaResponseValue get { return - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaResponseValue", this.UserUniqueIdentifier)] != + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaResponseValue"] != null ? Convert.ToString( - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaResponseValue", this.UserUniqueIdentifier)]) + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaResponseValue"]) : string.Empty; } set { - if (Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaResponseValue", this.UserUniqueIdentifier)] != + if (Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaResponseValue"] != null) { - Blog.CurrentInstance.Cache[string.Format("{0}RecaptchaResponseValue", this.UserUniqueIdentifier)] = + Blog.CurrentInstance.Cache[$"{UserUniqueIdentifier}RecaptchaResponseValue"] = value; } else { Blog.CurrentInstance.Cache.Add( - string.Format("{0}RecaptchaResponseValue", this.UserUniqueIdentifier), + $"{UserUniqueIdentifier}RecaptchaResponseValue", value, null, Cache.NoAbsoluteExpiration, @@ -403,8 +403,8 @@ public void UpdateLog(Comment comment) this.RecaptchaAttempts = 0; this.PageLoadTime = DateTime.Now; - Blog.CurrentInstance.Cache.Remove(string.Format("{0}RecaptchaChallengeValue", this.UserUniqueIdentifier)); - Blog.CurrentInstance.Cache.Remove(string.Format("{0}RecaptchaResponseValue", this.UserUniqueIdentifier)); + Blog.CurrentInstance.Cache.Remove($"{UserUniqueIdentifier}RecaptchaChallengeValue"); + Blog.CurrentInstance.Cache.Remove($"{UserUniqueIdentifier}RecaptchaResponseValue"); } /// diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaValidator.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaValidator.cs index 9562bcd2a..12f353916 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaValidator.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/Recaptcha/RecaptchaValidator.cs @@ -85,7 +85,7 @@ public string RemoteIP if (ip.AddressFamily != AddressFamily.InterNetwork && ip.AddressFamily != AddressFamily.InterNetworkV6) { - throw new ArgumentException(string.Format("Expecting an IP address, got {0}", ip)); + throw new ArgumentException($"Expecting an IP address, got {ip}"); } this.remoteIp = ip.ToString(); diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/ResolveLinks.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/ResolveLinks.cs index 2eaab13f8..99614c8f7 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/ResolveLinks.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/ResolveLinks.cs @@ -165,7 +165,7 @@ private static string ShortenUrl(string url, int max) var length = url.Length - max + 3; if (page.Length > length) { - url = url.Replace(page, string.Format("...{0}", page.Substring(length))); + url = url.Replace(page, $"...{page.Substring(length)}"); } } diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/SendCommentMail.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/SendCommentMail.cs index ff11dd257..e7341b04c 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/SendCommentMail.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/SendCommentMail.cs @@ -90,7 +90,7 @@ private static void PostCommentAdded(object sender, EventArgs e) Comment.OnServing(comment, args); var body = args.Body; body = body.Replace(Environment.NewLine, "
    "); - body = body.Replace(string.Format("{1}", deleteLink, Utils.Translate("delete", null, defaultCulture)); if (BlogSettings.Instance.EnableCommentsModeration) { - var approveLink = string.Format("{0}?approvecomment={1}", post.AbsoluteLink, comment.Id); + var approveLink = $"{post.AbsoluteLink}?approvecomment={comment.Id}"; sb.AppendFormat( " | {1}", approveLink, Utils.Translate("approve", null, defaultCulture)); } diff --git a/BlogEngine/BlogEngine.NET/Custom/Extensions/StopForumSpam.cs b/BlogEngine/BlogEngine.NET/Custom/Extensions/StopForumSpam.cs index 4a78c0edc..21958ad72 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Extensions/StopForumSpam.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Extensions/StopForumSpam.cs @@ -56,7 +56,7 @@ public bool Check(Comment comment) { try { - var url = string.Format("http://www.stopforumspam.com/api?ip={0}", comment.IP); + var url = $"http://www.stopforumspam.com/api?ip={comment.IP}"; var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); @@ -81,7 +81,7 @@ public bool Check(Comment comment) } catch (Exception e) { - Utils.Log(string.Format("Error checking stopforumspam.com: {0}", e.Message)); + Utils.Log($"Error checking stopforumspam.com: {e.Message}"); return false; } } diff --git a/BlogEngine/BlogEngine.NET/Custom/Widgets/Common.cs b/BlogEngine/BlogEngine.NET/Custom/Widgets/Common.cs index 337d88bd8..2a4d6713e 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Widgets/Common.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Widgets/Common.cs @@ -13,7 +13,7 @@ public class Common /// Settings object public static StringDictionary GetSettings(string id) { - var cacheId = string.Format("be_widget_{0}", id); + var cacheId = $"be_widget_{id}"; if (Blog.CurrentInstance.Cache[cacheId] == null) { var ws = new WidgetSettings(id); @@ -29,7 +29,7 @@ public static StringDictionary GetSettings(string id) /// Widget Id public static void SaveSettings(StringDictionary settings, string widgetId) { - var cacheId = string.Format("be_widget_{0}", widgetId); + var cacheId = $"be_widget_{widgetId}"; var ws = new WidgetSettings(widgetId); ws.SaveSettings(settings); diff --git a/BlogEngine/BlogEngine.NET/Custom/Widgets/LinkList/LinkList.cs b/BlogEngine/BlogEngine.NET/Custom/Widgets/LinkList/LinkList.cs index 7c14c6e04..5b074c2a4 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Widgets/LinkList/LinkList.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Widgets/LinkList/LinkList.cs @@ -22,7 +22,7 @@ public void SaveLink(string id, string title, string url, string target) doc.AppendChild(links); } - var node = doc.SelectSingleNode(string.Format("links/link[@id='{0}']", id)); + var node = doc.SelectSingleNode($"links/link[@id='{id}']"); if (node == null) { node = doc.CreateElement("link"); @@ -59,7 +59,7 @@ public void RemoveLink(string id) { return; } - var node = doc.SelectSingleNode(string.Format("links/link[@id='{0}']", id)); + var node = doc.SelectSingleNode($"links/link[@id='{id}']"); if (node != null) { links.RemoveChild(node); @@ -100,7 +100,7 @@ public LinkItem GetLinkById(string id) { return item; } - var node = doc.SelectSingleNode(string.Format("links/link[@id='{0}']", id)); + var node = doc.SelectSingleNode($"links/link[@id='{id}']"); if (node != null) { item.Id = node.Attributes["id"].Value; diff --git a/BlogEngine/BlogEngine.NET/Custom/Widgets/Newsletter/Newsletter.cs b/BlogEngine/BlogEngine.NET/Custom/Widgets/Newsletter/Newsletter.cs index 7c07d10d1..d1503fe56 100644 --- a/BlogEngine/BlogEngine.NET/Custom/Widgets/Newsletter/Newsletter.cs +++ b/BlogEngine/BlogEngine.NET/Custom/Widgets/Newsletter/Newsletter.cs @@ -23,7 +23,7 @@ public class Newsletter public static void AddEmail(string email) { var doc = GetXml(); - var node = doc.SelectSingleNode(string.Format("emails/email[text()='{0}']", email)); + var node = doc.SelectSingleNode($"emails/email[text()='{email}']"); if (node == null) { node = doc.CreateElement("email"); @@ -40,7 +40,7 @@ public static void AddEmail(string email) public static void RemoveEmail(string email) { var doc = GetXml(); - var node = doc.SelectSingleNode(string.Format("emails/email[text()='{0}']", email)); + var node = doc.SelectSingleNode($"emails/email[text()='{email}']"); if (node != null) { doc.FirstChild.RemoveChild(node); @@ -139,7 +139,7 @@ private static string FormatBodyMail(IPublishable publishable) var body = new StringBuilder(); var urlbase = Path.Combine( Path.Combine(Utils.AbsoluteWebRoot.AbsoluteUri, "themes"), BlogSettings.Instance.Theme); - var filePath = string.Format("~/Custom/Themes/{0}/newsletter.html", BlogSettings.Instance.Theme); + var filePath = $"~/Custom/Themes/{BlogSettings.Instance.Theme}/newsletter.html"; filePath = HostingEnvironment.MapPath(filePath); if (File.Exists(filePath)) { diff --git a/BlogEngine/BlogEngine.NET/archive.aspx.cs b/BlogEngine/BlogEngine.NET/archive.aspx.cs index 1bb1eae46..b35933034 100644 --- a/BlogEngine/BlogEngine.NET/archive.aspx.cs +++ b/BlogEngine/BlogEngine.NET/archive.aspx.cs @@ -156,7 +156,7 @@ private static void CreateTableRow(HtmlTable table, Post post) row.Cells.Add(date); HtmlTableCell title = new HtmlTableCell(); - title.InnerHtml = string.Format("{1}", post.RelativeLink, post.Title); + title.InnerHtml = $"{post.Title}"; title.Attributes.Add("class", "title"); row.Cells.Add(title); @@ -170,7 +170,7 @@ private static void CreateTableRow(HtmlTable table, Post post) } else { - comments.InnerHtml = string.Format("{1}", post.PermaLink, Resources.labels.comments); + comments.InnerHtml = $"{Resources.labels.comments}"; } comments.Attributes.Add("class", "comments"); row.Cells.Add(comments); diff --git a/BlogEngine/BlogEngine.NET/error404.aspx.cs b/BlogEngine/BlogEngine.NET/error404.aspx.cs index b95bc478b..2e77b40d0 100644 --- a/BlogEngine/BlogEngine.NET/error404.aspx.cs +++ b/BlogEngine/BlogEngine.NET/error404.aspx.cs @@ -56,7 +56,7 @@ private void DirectHitSearch() List items = Search.Hits(title, false); if (items.Count > 0) { - LiteralControl result = new LiteralControl(string.Format("
  • {1}
  • ", items[0].RelativeLink.ToString(), items[0].Title)); + LiteralControl result = new LiteralControl($"
  • {items[0].Title}
  • "); phSearchResult.Controls.Add(result); } } diff --git a/BlogEngine/BlogEngine.NET/page.aspx.cs b/BlogEngine/BlogEngine.NET/page.aspx.cs index 25757fea9..1cb978667 100644 --- a/BlogEngine/BlogEngine.NET/page.aspx.cs +++ b/BlogEngine/BlogEngine.NET/page.aspx.cs @@ -56,7 +56,7 @@ private void ServePage(Guid id) if (pg == null || (!pg.IsVisible)) { - this.Response.Redirect(string.Format("{0}error404.aspx", Utils.RelativeWebRoot), true); + this.Response.Redirect($"{Utils.RelativeWebRoot}error404.aspx", true); return; // WLF: ReSharper is stupid and doesn't know that redirect returns this method.... or does it not...? } @@ -199,7 +199,7 @@ public string PermaLink { get { - return string.Format("{0}page.aspx?id={1}", Utils.AbsoluteWebRoot, this.Page.Id); + return $"{Utils.AbsoluteWebRoot}page.aspx?id={Page.Id}"; } } } \ No newline at end of file diff --git a/BlogEngine/BlogEngine.NET/post.aspx.cs b/BlogEngine/BlogEngine.NET/post.aspx.cs index 546c538b0..ec8827dbf 100644 --- a/BlogEngine/BlogEngine.NET/post.aspx.cs +++ b/BlogEngine/BlogEngine.NET/post.aspx.cs @@ -195,8 +195,7 @@ private void InitNavigationLinks() // Try to load PostNavigation from theme folder var template = BlogSettings.Instance.IsRazorTheme ? "PostNavigation.cshtml" : "PostNavigation.ascx"; - var path = string.Format("{0}Custom/Themes/{1}/{2}", - Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.Theme, template); + var path =$"{Utils.ApplicationRelativeWebRoot}Custom/Themes/{BlogSettings.Instance.Theme}/{template}"; if (!System.IO.File.Exists(Server.MapPath(path))) path = Utils.ApplicationRelativeWebRoot + "Custom/Controls/Defaults/PostNavigation.ascx";