diff --git a/Sources/SrkToolkit.Domain.AspNetCore2/SrkToolkit.Domain.AspNetCore2.csproj b/Sources/SrkToolkit.Domain.AspNetCore2/SrkToolkit.Domain.AspNetCore2.csproj index e8d61d5..65ca043 100644 --- a/Sources/SrkToolkit.Domain.AspNetCore2/SrkToolkit.Domain.AspNetCore2.csproj +++ b/Sources/SrkToolkit.Domain.AspNetCore2/SrkToolkit.Domain.AspNetCore2.csproj @@ -1,9 +1,8 @@ - net7.0 - enable - enable + disable + disable SrkToolkit.Domain.AspNetCore2 true 2.0.147-preview2 @@ -19,6 +18,7 @@ true ..\SrkToolkit.snk SrkToolkit.Domain.md + net7.0;netstandard2.0 diff --git a/Sources/SrkToolkit.Web.AspNetCore2/Fakes/BasicHttpContext.cs b/Sources/SrkToolkit.Web.AspMvc5/Fakes/BasicHttpContext.cs similarity index 94% rename from Sources/SrkToolkit.Web.AspNetCore2/Fakes/BasicHttpContext.cs rename to Sources/SrkToolkit.Web.AspMvc5/Fakes/BasicHttpContext.cs index d49ecd1..f4d6944 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/Fakes/BasicHttpContext.cs +++ b/Sources/SrkToolkit.Web.AspMvc5/Fakes/BasicHttpContext.cs @@ -16,17 +16,17 @@ namespace SrkToolkit.Web.Fakes { - using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using System.Text; + using System.Web; /// /// Implementation of where the developer can set any property to any value. /// - public class BasicHttpContext : HttpContext + public class BasicHttpContext : HttpContextBase { private HttpSessionStateBase session; private IPrincipal user; diff --git a/Sources/SrkToolkit.Web.AspNetCore2/Fakes/BasicHttpRequest.cs b/Sources/SrkToolkit.Web.AspMvc5/Fakes/BasicHttpRequest.cs similarity index 100% rename from Sources/SrkToolkit.Web.AspNetCore2/Fakes/BasicHttpRequest.cs rename to Sources/SrkToolkit.Web.AspMvc5/Fakes/BasicHttpRequest.cs diff --git a/Sources/SrkToolkit.Web.AspNetCore2/Fakes/BasicHttpSessionState.cs b/Sources/SrkToolkit.Web.AspMvc5/Fakes/BasicHttpSessionState.cs similarity index 100% rename from Sources/SrkToolkit.Web.AspNetCore2/Fakes/BasicHttpSessionState.cs rename to Sources/SrkToolkit.Web.AspMvc5/Fakes/BasicHttpSessionState.cs diff --git a/Sources/SrkToolkit.Web.AspNetCore2/Filters/AuthorizeAttribute.cs b/Sources/SrkToolkit.Web.AspMvc5/Filters/AuthorizeAttribute.cs similarity index 100% rename from Sources/SrkToolkit.Web.AspNetCore2/Filters/AuthorizeAttribute.cs rename to Sources/SrkToolkit.Web.AspMvc5/Filters/AuthorizeAttribute.cs diff --git a/Sources/SrkToolkit.Web.AspNetCore2/HttpErrors/BasicHttpErrorResponse.cs b/Sources/SrkToolkit.Web.AspMvc5/HttpErrors/BasicHttpErrorResponse.cs similarity index 100% rename from Sources/SrkToolkit.Web.AspNetCore2/HttpErrors/BasicHttpErrorResponse.cs rename to Sources/SrkToolkit.Web.AspMvc5/HttpErrors/BasicHttpErrorResponse.cs diff --git a/Sources/SrkToolkit.Web.AspNetCore2/HttpErrors/ErrorControllerHandler.cs b/Sources/SrkToolkit.Web.AspMvc5/HttpErrors/ErrorControllerHandler.cs similarity index 100% rename from Sources/SrkToolkit.Web.AspNetCore2/HttpErrors/ErrorControllerHandler.cs rename to Sources/SrkToolkit.Web.AspMvc5/HttpErrors/ErrorControllerHandler.cs diff --git a/Sources/SrkToolkit.Web.AspNetCore2/HttpErrors/IErrorController.cs b/Sources/SrkToolkit.Web.AspMvc5/HttpErrors/IErrorController.cs similarity index 100% rename from Sources/SrkToolkit.Web.AspNetCore2/HttpErrors/IErrorController.cs rename to Sources/SrkToolkit.Web.AspMvc5/HttpErrors/IErrorController.cs diff --git a/Sources/SrkToolkit.Web.AspNetCore2/JsonNetResult.cs b/Sources/SrkToolkit.Web.AspMvc5/JsonNetResult.cs similarity index 94% rename from Sources/SrkToolkit.Web.AspNetCore2/JsonNetResult.cs rename to Sources/SrkToolkit.Web.AspMvc5/JsonNetResult.cs index 6c24f8c..fba92e6 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/JsonNetResult.cs +++ b/Sources/SrkToolkit.Web.AspMvc5/JsonNetResult.cs @@ -16,7 +16,6 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Mvc; using System; using System.Diagnostics; using System.Runtime.Serialization.Json; @@ -60,7 +59,7 @@ public JsonNetResult() /// /// The JSON serializer. /// - public static Action Serializer { get; set; } + public static Action Serializer { get; set; } /// /// Gets or sets the content encoding. diff --git a/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfo.cs b/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfo.cs index b8da317..691c66c 100644 --- a/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfo.cs +++ b/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfo.cs @@ -337,9 +337,13 @@ public override string ToString() /// /// A that represents this instance. /// - public string ToString(PageInfoObjectSection sections, bool indented) - { - var sb = new StringBuilder(); + public string ToString(PageInfoObjectSection sections, bool indented) + { +#if ASPMVCCORE + var sb = new StringWriter(); +#elif ASPMVC + var sb = new StringBuilder(); +#endif this.Write(sb, sections, indented); return sb.ToString(); } @@ -350,8 +354,14 @@ public string ToString(PageInfoObjectSection sections, bool indented) /// The sb. /// the desires sections /// if true the generated html will be indented - public void Write(StringBuilder sb, PageInfoObjectSection sections, bool indented) - { + public void Write( +#if ASPMVCCORE + StringWriter sb, +#elif ASPMVC + StringBuilder sb, +#endif + PageInfoObjectSection sections, bool indented) + { if (sb == null) throw new ArgumentNullException("sb"); diff --git a/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoItem.cs b/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoItem.cs index 87c5644..46fc380 100644 --- a/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoItem.cs +++ b/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoItem.cs @@ -114,7 +114,11 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() /// public override string ToString() { - var sb = new StringBuilder(); +#if ASPMVCCORE + var sb = new StringWriter(); +#elif ASPMVC + var sb = new StringBuilder(); +#endif this.ToString(sb, PageInfo.defaultSections, false); return sb.ToString(); } @@ -125,7 +129,13 @@ public override string ToString() /// The to write to. /// The sections to use. /// sb - public void ToString(StringBuilder sb, PageInfoObjectSection sections, bool indented) + public void ToString( +#if ASPMVCCORE + StringWriter sb, +#elif ASPMVC + StringBuilder sb, +#endif + PageInfoObjectSection sections, bool indented) { if (sb == null) throw new ArgumentNullException("sb"); @@ -135,10 +145,18 @@ public void ToString(StringBuilder sb, PageInfoObjectSection sections, bool inde if ((obj.Section & sections) != 0) { obj.SetValue(this.Value); - if (indented) - sb.AppendLine(obj.ToString()); - else - sb.Append(obj.ToString()); + +#if ASPMVCCORE + if (indented) + sb.WriteLine(obj.ToString()); + else + sb.Write(obj.ToString()); +#elif ASPMVC + if (indented) + sb.AppendLine(obj.ToString()); + else + sb.Append(obj.ToString()); +#endif } } } diff --git a/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoObject.cs b/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoObject.cs index 55e3452..524282a 100644 --- a/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoObject.cs +++ b/Sources/SrkToolkit.Web.AspMvc5/Open/PageInfoObject.cs @@ -16,17 +16,19 @@ namespace SrkToolkit.Web.Open { - using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Text; -#if ASPMVCCORE - -#else - using System.Web.Mvc; -#endif +#if ASPMVCCORE + using Microsoft.AspNetCore.Mvc.Rendering; + using System.Text.Encodings.Web; +#endif + +#if ASPMVC + using System.Web.Mvc; +#endif /// /// A HTML element that will represent a page information . @@ -80,9 +82,6 @@ public OpenGraphTag OpenGraphTag get { return this.openGraphTag; } } -#if ASPNETCORE -#endif -#if !NSTD && !NET40 private TagBuilder Tag { get @@ -98,14 +97,17 @@ private TagBuilder Tag if (this.tagValue != null) { - ////tag.SetInnerText(this.tagValue); // net40 - tag.InnerHtml.Append(this.tagValue); // netstandard2.0 +#if ASPMVCCORE + tag.InnerHtml.Append(this.tagValue); // netstandard2.0 +#endif +#if ASPMVC + tag.SetInnerText(this.tagValue); // net40 +#endif } return tag; } } -#endif /// /// Prepare a HTML element of the specified name to contain the item's value. @@ -216,28 +218,59 @@ public PageInfoObject SetValue(string value) /// public override string ToString() { +#if ASPMVCCORE + var sb = new StringWriter(); +#elif ASPMVC + var sb = new StringBuilder(); +#endif + this.ToString(sb); + return sb.ToString(); + } + + /// + /// Returns a that contains the generated HTML tags. + /// + /// + /// A that contains the generated HTML tags. + /// + public void ToString( +#if ASPMVCCORE + StringWriter sb +#elif ASPMVC + StringBuilder sb +#endif + ) + { #if NSTD || NET40 return ""; #else var tag = this.Tag; if (this.openGraphTag != null) { - return this.openGraphTag.ToString(); +#if ASPMVCCORE + sb.Write(this.openGraphTag.ToString()); +#else + sb.Append(this.openGraphTag.ToString()); +#endif } else if (tag != null) { -#if ASPMVCCORE - return tag.ToString(); -#else - return tag.ToString(singleTagNames.Contains(this.tagName) ? TagRenderMode.SelfClosing : TagRenderMode.Normal); -#endif - } - else - { - return ""; - } -#endif - } +#if ASPMVCCORE + tag.WriteTo(sb, HtmlEncoder.Default); +#else + sb.Append(tag.ToString(singleTagNames.Contains(this.tagName) ? TagRenderMode.SelfClosing : TagRenderMode.Normal)); +#endif + } + else + { +#if ASPMVCCORE + sb.Write(""); +#else + sb.Append(""); +#endif + } +#endif + } } /// diff --git a/Sources/NET45.SrkToolkit.Web.Mvc5/Properties/AssemblyInfo.cs b/Sources/SrkToolkit.Web.AspMvc5/Properties/AssemblyInfo.cs similarity index 62% rename from Sources/NET45.SrkToolkit.Web.Mvc5/Properties/AssemblyInfo.cs rename to Sources/SrkToolkit.Web.AspMvc5/Properties/AssemblyInfo.cs index 659bf6b..68392ae 100644 --- a/Sources/NET45.SrkToolkit.Web.Mvc5/Properties/AssemblyInfo.cs +++ b/Sources/SrkToolkit.Web.AspMvc5/Properties/AssemblyInfo.cs @@ -3,8 +3,5 @@ using System.Runtime.InteropServices; using System; -[assembly: AssemblyTitle("SrkToolkit.Web.Mvc5")] -[assembly: AssemblyDescription("SrkToolkit.Web for .NET 4.5 and ASP MVC 5")] - [assembly: CLSCompliant(true)] [assembly: Guid("a2fdfb36-514d-43ac-8524-a6ace628b7d6")] diff --git a/Sources/SrkToolkit.Web.AspMvc5/Services/BaseSessionService.cs b/Sources/SrkToolkit.Web.AspMvc5/Services/BaseSessionService.cs new file mode 100644 index 0000000..07f589e --- /dev/null +++ b/Sources/SrkToolkit.Web.AspMvc5/Services/BaseSessionService.cs @@ -0,0 +1,110 @@ +// +// Copyright 2014 SandRock +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace SrkToolkit.Web.Services +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + + /// + /// + /// + public class BaseSessionService + { + private readonly ISessionServiceSource source; + + /// + /// Initializes an instance with a HttpSessionStateBase object (likely from ASP MVC). + /// + /// + public BaseSessionService(HttpSessionStateBase httpSessionStateBase) + { + this.source = new HttpBaseSessionServiceSource(httpSessionStateBase); + } + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP session dictionary. + public BaseSessionService(IDictionary httpSessionDictionary) + { + this.source = new DictionarySessionServiceSource(httpSessionDictionary); + } + + /// + /// Clears everything form the session. + /// + public void Clear() + { + this.source.Clear(); + } + + /// + /// Clears a session value. + /// + /// + protected void Clear(string key) + { + this.source.Clear(key); + } + + /// + /// Sets a session value. + /// + /// + /// + /// + protected void Set(string key, T value) + { + this.source.Set(key, value); + } + + + /// + /// Gets a session reference-type value. + /// + /// + /// The key. + /// + protected T GetObject(string key) + where T : class + { + var obj = this.source.Get(key); + if (obj == null) + return null; + + return (T)obj; + } + + /// + /// Gets a session nullable value-type value. + /// + /// + /// The key. + /// + protected T? GetValue(string key) + where T : struct + { + var obj = this.source.Get(key); + if (obj == null) + return default(T?); + + return (T)obj; + } + } +} diff --git a/Sources/SrkToolkit.Web.AspMvc5/Services/HttpBaseSessionServiceSource.cs b/Sources/SrkToolkit.Web.AspMvc5/Services/HttpBaseSessionServiceSource.cs new file mode 100644 index 0000000..20ac8ef --- /dev/null +++ b/Sources/SrkToolkit.Web.AspMvc5/Services/HttpBaseSessionServiceSource.cs @@ -0,0 +1,90 @@ +// +// Copyright 2014 SandRock +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace SrkToolkit.Web.Services +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Web; + + /// + /// Default implementation of using as provider. + /// + public class HttpBaseSessionServiceSource : ISessionServiceSource + { + private readonly HttpSessionStateBase source; + + /// + /// Initializes a new instance of the class. + /// + /// The source. + public HttpBaseSessionServiceSource(HttpSessionStateBase source) + { + this.source = source; + } + + /// + /// Gets on object by its key. + /// + /// + /// + public object Get(string key) + { + if (this.source == null) + return null; + + return this.source[key]; + } + + /// + /// Clears an object from session. + /// + /// + public void Clear(string key) + { + if (this.source == null) + return; + + this.source.Remove(key); + } + + /// + /// Set an object in session. + /// + /// + /// + public void Set(string key, object value) + { + if (this.source == null) + return; + + this.source[key] = value; + } + + /// + /// Clears the session. + /// + public void Clear() + { + if (this.source == null) + return; + + this.source.Clear(); + } + } +} diff --git a/Sources/SrkToolkit.Web.AspMvc5/Services/IResultService.cs b/Sources/SrkToolkit.Web.AspMvc5/Services/IResultService.cs new file mode 100644 index 0000000..cd3f3c9 --- /dev/null +++ b/Sources/SrkToolkit.Web.AspMvc5/Services/IResultService.cs @@ -0,0 +1,101 @@ +// +// Copyright 2014 SandRock +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace SrkToolkit.Web.Services +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Web.Mvc; + + /// + /// Helps return generic HTTP responses. + /// + public interface IResultService + { + /// + /// Returns a 403 Forbidden view. + /// + /// a custom message can be specified. leave null for random message. + ActionResult Forbidden(string message = null); + + /// + /// Shows a 404 page. + /// + /// a custom message can be specified. leave null for random message. + /// + ActionResult NotFound(string message = null); + + /// + /// Shows a 400 page. + /// + ActionResult BadRequest(string message = null); + + /// + /// Returns a standard JSON result for a successful operation. + /// + /// + ActionResult JsonSuccess(); + + /// + /// Returns a standard JSON result containing data. + /// + /// The data. + /// + ActionResult JsonSuccess(object data); + + /// + /// Returns a standard JSON result containing an error. + /// + /// + ActionResult JsonError(); + + /// + /// Returns a standard JSON result containing an error. + /// + /// helps identify the the error + /// + ActionResult JsonError(string errorCode); + + /// + /// Returns a standard JSON result containing an error. + /// + /// helps identify the the error + /// the translated error message to display + /// + ActionResult JsonError(string errorCode, string errorMessage); + + /// + /// Returns a standard JSON result containing an error. + /// + /// helps identify the the error + /// the translated error message to display + /// The data. + /// + ActionResult JsonError(string errorCode, string errorMessage, object data); + + /// + /// Returns a standard JSON result containing an error. + /// + /// The HTTP code. + /// helps identify the the error + /// the translated error message to display + /// The data. + /// + ActionResult JsonError(int httpCode, string errorCode, string errorMessage, object data); + } +} diff --git a/Sources/SrkToolkit.Web.AspMvc5/Services/ISessionServiceSource.cs b/Sources/SrkToolkit.Web.AspMvc5/Services/ISessionServiceSource.cs new file mode 100644 index 0000000..199fa14 --- /dev/null +++ b/Sources/SrkToolkit.Web.AspMvc5/Services/ISessionServiceSource.cs @@ -0,0 +1,54 @@ +// +// Copyright 2014 SandRock +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace SrkToolkit.Web.Services +{ + using System; + using System.Collections.Generic; + using System.Web; + using System.Text; + + /// + /// Abstraction of . + /// + public interface ISessionServiceSource + { + /// + /// Gets on object by its key. + /// + /// + /// + object Get(string key); + + /// + /// Clears an object from session. + /// + /// + void Clear(string key); + + /// + /// Set an object in session. + /// + /// + /// + void Set(string key, object value); + + /// + /// Clears the session. + /// + void Clear(); + } +} diff --git a/Sources/SrkToolkit.Web.AspMvc5/Services/ResultService.cs b/Sources/SrkToolkit.Web.AspMvc5/Services/ResultService.cs new file mode 100644 index 0000000..cf1e1af --- /dev/null +++ b/Sources/SrkToolkit.Web.AspMvc5/Services/ResultService.cs @@ -0,0 +1,275 @@ +// +// Copyright 2014 SandRock +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace SrkToolkit.Web.Services +{ + using System; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + using SrkToolkit.Web.HttpErrors; + + /// + /// Helps return generic HTTP responses. + /// + /// The type of the error controller. + public class ResultService : ResultServiceBase, IResultService + where TErrorController : IErrorController, new() + { + /// + /// Initializes a new instance of the class. + /// + /// The HTTP context. + public ResultService(HttpContextBase httpContext) + : base(httpContext) + { + } + + /// + /// Gets the route to the "forbidden" page. + /// + public static RouteData ForbiddenRoute + { + get + { + RouteData routeData = new RouteData(); + routeData.Values.Add("controller", "Error"); + routeData.Values.Add("action", "Forbidden"); + return routeData; + } + } + + /// + /// Gets the route to the "not found" page. + /// + public static RouteData NotFoundRoute + { + get + { + RouteData routeData = new RouteData(); + routeData.Values.Add("controller", "Error"); + routeData.Values.Add("action", "NotFound"); + return routeData; + } + } + + /// + /// Gets the route to the "method not allowed" page. + /// + public static RouteData MethodNotAllowedRoute + { + get + { + RouteData routeData = new RouteData(); + routeData.Values.Add("controller", "Error"); + routeData.Values.Add("action", "MethodNotAllowed"); + return routeData; + } + } + + /// + /// Gets the route to the "gone" page. + /// + public static RouteData GoneRoute + { + get + { + RouteData routeData = new RouteData(); + routeData.Values.Add("controller", "Error"); + routeData.Values.Add("action", "Gone"); + return routeData; + } + } + + /// + /// Gets the route to the "bad request" page. + /// + public static RouteData BadRequestRoute + { + get + { + RouteData routeData = new RouteData(); + routeData.Values.Add("controller", "Error"); + routeData.Values.Add("action", "BadRequest"); + return routeData; + } + } + + /// + /// Gets the route to the "internal error" page. + /// + public static RouteData InternalRoute + { + get + { + RouteData routeData = new RouteData(); + routeData.Values.Add("controller", "Error"); + routeData.Values.Add("action", "Internal"); + return routeData; + } + } + + /// + /// Returns a 403 Forbidden view. + /// + /// a custom message can be specified. leave null for random message. + public ActionResult Forbidden(string message = null) + { + this.HttpContext.Response.TrySkipIisCustomErrors = true; // motherfucking helpfull + + var ctrlContext = new ControllerContext(); + ctrlContext.HttpContext = this.HttpContext; + ctrlContext.RouteData = ForbiddenRoute; + if (message != null) + { + ctrlContext.RouteData.Values[ResultServiceBase.RouteDataMessageKey] = message; + ctrlContext.RouteData.DataTokens[ResultServiceBase.RouteDataMessageKey] = message; + } + + IController ctrl = new TErrorController(); + + ctrl.Execute(new RequestContext(this.HttpContext, ctrlContext.RouteData)); + return null; + } + + /// + /// Returns a 500 error view with a custom message. + /// + /// a custom message can be specified. leave null for standard message. + public ActionResult Error(string message) + { + this.HttpContext.Response.TrySkipIisCustomErrors = true; // motherfucking helpfull + + var ctrlContext = new ControllerContext(); + ctrlContext.HttpContext = this.HttpContext; + ctrlContext.RouteData = InternalRoute; + ctrlContext.RouteData.Values["error"] = new Exception(message); + if (message != null) + { + ctrlContext.RouteData.Values[ResultServiceBase.RouteDataMessageKey] = message; + ctrlContext.RouteData.DataTokens[ResultServiceBase.RouteDataMessageKey] = message; + } + + IController ctrl = new BaseErrorController + { + ControllerContext = ctrlContext, + }; + + ctrl.Execute(new RequestContext(this.HttpContext, ctrlContext.RouteData)); + return null; + } + + /// + /// Shows a 404 page. + /// + /// a custom message can be specified. leave null for random message. + /// + public ActionResult NotFound(string message = null) + { + this.HttpContext.Response.TrySkipIisCustomErrors = true; // motherfucking helpfull + + var ctrlContext = new ControllerContext(); + ctrlContext.HttpContext = this.HttpContext; + ctrlContext.RouteData = NotFoundRoute; + if (message != null) + { + ctrlContext.RouteData.Values[ResultServiceBase.RouteDataMessageKey] = message; + ctrlContext.RouteData.DataTokens[ResultServiceBase.RouteDataMessageKey] = message; + } + + IController ctrl = new BaseErrorController + { + ControllerContext = ctrlContext, + }; + + ctrl.Execute(new RequestContext(this.HttpContext, ctrlContext.RouteData)); + + return null; + } + + public ActionResult MethodNotAllowed() + { + this.HttpContext.Response.TrySkipIisCustomErrors = true; // motherfucking helpfull + + var ctrlContext = new ControllerContext(); + ctrlContext.HttpContext = this.HttpContext; + ctrlContext.RouteData = MethodNotAllowedRoute; + + IController ctrl = new BaseErrorController + { + ControllerContext = ctrlContext, + }; + + ctrl.Execute(new RequestContext(this.HttpContext, ctrlContext.RouteData)); + + return null; + } + + /// + /// Shows a 410 page. + /// + /// a custom message can be specified. leave null for random message. + /// + public ActionResult Gone(string message = null) + { + this.HttpContext.Response.TrySkipIisCustomErrors = true; // motherfucking helpfull + + var ctrlContext = new ControllerContext(); + ctrlContext.HttpContext = this.HttpContext; + ctrlContext.RouteData = GoneRoute; + if (message != null) + { + ctrlContext.RouteData.Values[ResultServiceBase.RouteDataMessageKey] = message; + ctrlContext.RouteData.DataTokens[ResultServiceBase.RouteDataMessageKey] = message; + } + + IController ctrl = new BaseErrorController + { + ControllerContext = ctrlContext, + }; + + ctrl.Execute(new RequestContext(this.HttpContext, ctrlContext.RouteData)); + + return null; + } + + /// + /// Shows a 400 page. + /// + public ActionResult BadRequest(string message = null) + { + this.HttpContext.Response.TrySkipIisCustomErrors = true; // motherfucking helpfull + + var ctrlContext = new ControllerContext(); + ctrlContext.HttpContext = this.HttpContext; + ctrlContext.RouteData = BadRequestRoute; + if (message != null) + { + ctrlContext.RouteData.Values[ResultServiceBase.RouteDataMessageKey] = message; + ctrlContext.RouteData.DataTokens[ResultServiceBase.RouteDataMessageKey] = message; + } + + IController ctrl = new BaseErrorController + { + ControllerContext = ctrlContext, + }; + + ctrl.Execute(new RequestContext(this.HttpContext, ctrlContext.RouteData)); + + return null; + } + } +} diff --git a/Sources/SrkToolkit.Web.AspMvc5/Services/ResultServiceBase.cs b/Sources/SrkToolkit.Web.AspMvc5/Services/ResultServiceBase.cs new file mode 100644 index 0000000..6705642 --- /dev/null +++ b/Sources/SrkToolkit.Web.AspMvc5/Services/ResultServiceBase.cs @@ -0,0 +1,254 @@ +// +// Copyright 2014 SandRock +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace SrkToolkit.Web.Services +{ + using System; + using System.Web; + using System.Web.Mvc; + using System.Web.Routing; + using SrkToolkit.Web.HttpErrors; + + /// + /// Helps return generic HTTP responses. + /// + public class ResultServiceBase + { + private readonly HttpContextBase httpContext; + + public const string RouteDataExceptionKey = "error"; + public const string RouteDataMessageKey = "message"; + public const string RouteDataHttpCodeKey = "http code"; + + private int jsonErrorHttpStatusCode = 400; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP context. + public ResultServiceBase(HttpContextBase httpContext) + { + this.httpContext = httpContext; + } + + /// + /// Gets or sets the json error HTTP status code (default is 400). + /// + public int JsonErrorHttpStatusCode + { + get { return this.jsonErrorHttpStatusCode; } + set { this.jsonErrorHttpStatusCode = value; } + } + + /// + /// Returns a standard JSON result for a successful operation. + /// + /// + public ActionResult JsonSuccess() + { + return new JsonNetResult + { + Data = new + { + Success = true, + ErrorCode = default(string), + ErrorMessage = default(string), + Data = default(string), + }, + }; + } + + /// + /// Returns a standard JSON result containing data. + /// + /// + /// + public ActionResult JsonSuccess(object data) + { + return new JsonNetResult + { + Data = new + { + Success = true, + ErrorCode = default(string), + ErrorMessage = default(string), + Data = data, + }, + }; + } + + /// + /// Returns a standard JSON result containing an error. + /// + /// + public ActionResult JsonError() + { + return new JsonNetResult + { + HttpStatusCode = this.JsonErrorHttpStatusCode, + Data = new + { + Success = false, + ErrorCode = default(string), + ErrorMessage = default(string), + Data = default(string), + }, + }; + } + + /// + /// Returns a standard JSON result containing an error. + /// + /// helps identify the the error + /// + public ActionResult JsonError(string errorCode) + { + return new JsonNetResult + { + HttpStatusCode = this.JsonErrorHttpStatusCode, + Data = new + { + Success = false, + ErrorCode = errorCode, + ErrorMessage = default(string), + Data = default(string), + }, + }; + } + + /// + /// Returns a standard JSON result containing an error. + /// + /// helps identify the the error + /// the translated error message to display + /// + public ActionResult JsonError(string errorCode, string errorMessage) + { + return new JsonNetResult + { + HttpStatusCode = this.JsonErrorHttpStatusCode, + Data = new + { + Success = false, + ErrorCode = errorCode, + ErrorMessage = errorMessage, + Data = default(string), + }, + }; + } + + /// + /// Returns a standard JSON result containing an error. + /// + /// helps identify the the error + /// the translated error message to display + /// The data. + /// + public ActionResult JsonError(string errorCode, string errorMessage, object data) + { + return new JsonNetResult + { + HttpStatusCode = this.JsonErrorHttpStatusCode, + Data = new + { + Success = false, + ErrorCode = errorCode, + ErrorMessage = errorMessage, + Data = data, + }, + }; + } + + /// + /// Returns a standard JSON result containing an error. + /// + /// The HTTP code. + /// helps identify the the error + /// the translated error message to display + /// The data. + /// + public ActionResult JsonError(int httpCode, string errorCode, string errorMessage, object data) + { + var result = new JsonNetResult + { + Data = new + { + Success = false, + ErrorCode = errorCode, + ErrorMessage = errorMessage, + Data = data, + }, + }; + result.HttpStatusCode = httpCode; + return result; + } + + /// + /// Gets the HTTP context. + /// + protected HttpContextBase HttpContext + { + get { return this.httpContext; } + } + + /// + /// Returns a JSON ActionResult containing the exception details. + /// + /// + /// + /// + /// + /// + public ActionResult JsonErrorWithException(int httpCode, string errorCode, string errorMessage, Exception exception) + { + return new JsonNetResult + { + HttpStatusCode = httpCode, + Data = new + { + Success = false, + ErrorCode = errorCode, + ErrorMessage = errorMessage, + Data = default(string), + Exception = DescribeException(exception), + }, + }; + } + + /// + /// Returns an anonymous object containing the exception details. + /// + /// + /// + public static object DescribeException(Exception exception) + { + if (exception != null) + { + return new + { + Type = exception.GetType().FullName, + Message = exception.Message, + StackTrace = exception.StackTrace, + Inner = DescribeException(exception.InnerException), + }; + } + else + { + return null; + } + } + } +} diff --git a/Sources/SrkToolkit.Web.AspMvc5/SrkHtmlExtensions.cs b/Sources/SrkToolkit.Web.AspMvc5/SrkHtmlExtensions.cs new file mode 100644 index 0000000..15e3725 --- /dev/null +++ b/Sources/SrkToolkit.Web.AspMvc5/SrkHtmlExtensions.cs @@ -0,0 +1,1149 @@ +// +// Copyright 2014 SandRock +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +namespace System.Web.Mvc +{ + using SrkToolkit.Web.Open; + using SrkToolkit.Web; + using SrkToolkit.Web.Models; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + using System.Linq.Expressions; + using System.Web.Mvc.Html; + using System.Web.Routing; + using System.Web.UI.WebControls; + + /// + /// HTML extensions. + /// + public static class SrkHtmlExtensions + { + internal const string DefaultDateTimeFormatsKey = "SrkDisplayDateFormat"; + internal static readonly string[] DefaultDateTimeFormats = new string[] + { + /* 0 => */ "D", // date + /* 1 => */ "D zzz", // date + tz + /* 2 => */ "T", // time + /* 3 => */ "T zzz", // time + tz + /* 4 => */ "c", // timespan + /* 5 => */ "F", // datetime + /* 6 => */ "t", // short time + /* 7 => */ "g", // short timespan + }; + + private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + + #region SetTimezone, GetTimezone, GetUserDate, GetUtcDate, SetCulture, GetCulture + + /// + /// Sets the timezone for displays of dates and times. + /// + /// The HTML. + /// Name of the time zone. + /// + /// + /// + public static HtmlHelper SetTimezone(this HtmlHelper html, string timeZoneName) + { + if (string.IsNullOrEmpty(timeZoneName)) + throw new ArgumentException("The value cannot be empty", "timeZoneName"); + + SrkHtmlExtensions.SetTimezone(html, TimeZoneInfo.FindSystemTimeZoneById(timeZoneName)); + return html; + } + + /// + /// Sets the timezone for displays of dates and times. + /// + /// The HTML. + /// The time zone. + /// + /// + public static HtmlHelper SetTimezone(this HtmlHelper html, TimeZoneInfo timeZone) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewContext != null && html.ViewContext.HttpContext != null) + html.ViewContext.HttpContext.Items["Timezone"] = timeZone; + html.ViewData["Timezone"] = timeZone; + return html; + } + + /// + /// Gets the timezone for displays of dates and times. + /// + /// The HTML. + /// + /// html + public static TimeZoneInfo GetTimezone(this HtmlHelper html) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewContext != null && html.ViewContext.HttpContext != null) + return (TimeZoneInfo)html.ViewData["Timezone"] ?? (TimeZoneInfo)html.ViewContext.HttpContext.Items["Timezone"] ?? TimeZoneInfo.Utc; + return (TimeZoneInfo)html.ViewData["Timezone"] ?? TimeZoneInfo.Utc; + } + + /// + /// Gets a based on the user's specified with . + /// + /// The HTML. + /// The date. + /// The specified in the UTC time zone. + /// The specified in the user's time zone. + public static DateTime GetUserDate(this HtmlHelper html, DateTime date, out DateTime utcDate) + { + var tz = html.GetTimezone(); + if (date.Kind == DateTimeKind.Utc) + { + utcDate = date; + return tz.ConvertFromUtc(date); + } + else if (date.Kind == DateTimeKind.Local) + { + utcDate = date.ToUniversalTime(); + return tz.ConvertFromUtc(utcDate); + } + else if (date.Kind == DateTimeKind.Unspecified) + { + utcDate = tz.ConvertToUtc(date); + return date; + } + + utcDate = DateTime.MinValue; + return utcDate; + } + + /// + /// Gets the UTC based on the user's specified with . + /// + /// The HTML. + /// The date. + /// The specified in the UTC time zone. + /// DateTime.Kind ' + date.Kind + ' is not supported + public static DateTime GetUtcDate(this HtmlHelper html, DateTime date) + { + if (date.Kind == DateTimeKind.Utc) + { + return date; + } + else if (date.Kind == DateTimeKind.Local) + { + return date.ToUniversalTime(); + } + else if (date.Kind == DateTimeKind.Unspecified) + { + var tz = html.GetTimezone(); + return tz.ConvertToUtc(date); + } + + throw new NotSupportedException("DateTime.Kind '" + date.Kind + "' is not supported"); + } + + /// + /// Sets the current culture. + /// + /// The HTML. + /// Culture name. + /// + /// + /// + public static HtmlHelper SetCulture(this HtmlHelper html, string culture) + { + if (string.IsNullOrEmpty(culture)) + throw new ArgumentException("The value cannot be empty", "culture"); + + SrkHtmlExtensions.SetCulture(html, CultureInfo.GetCultureInfo(culture)); + return html; + } + + /// + /// Sets the current culture. + /// + /// The HTML. + /// The culture. + /// + /// + public static HtmlHelper SetCulture(this HtmlHelper html, CultureInfo culture) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewContext != null && html.ViewContext.HttpContext != null) + html.ViewContext.HttpContext.Items["Culture"] = culture; + html.ViewData["Culture"] = culture; + return html; + } + + /// + /// Gets the current culture. + /// + /// The HTML. + /// + /// html + public static CultureInfo GetCulture(this HtmlHelper html) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewContext != null && html.ViewContext.HttpContext != null) + return (CultureInfo)html.ViewData["Culture"] ?? (CultureInfo)html.ViewContext.HttpContext.Items["Culture"] ?? CultureInfo.CurrentUICulture; + return (CultureInfo)html.ViewData["Culture"] ?? CultureInfo.CurrentCulture; + } + + /// + /// Sets the current UI culture. + /// + /// The HTML. + /// Culture name. + /// + /// + /// + public static HtmlHelper SetUICulture(this HtmlHelper html, string uICulture) + { + if (string.IsNullOrEmpty(uICulture)) + throw new ArgumentException("The value cannot be empty", "culture"); + + SrkHtmlExtensions.SetUICulture(html, CultureInfo.GetCultureInfo(uICulture)); + return html; + } + + /// + /// Sets the current UI culture. + /// + /// The HTML. + /// The culture. + /// + /// + public static HtmlHelper SetUICulture(this HtmlHelper html, CultureInfo uICulture) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewContext != null && html.ViewContext.HttpContext != null) + html.ViewContext.HttpContext.Items["UICulture"] = uICulture; + html.ViewData["UICulture"] = uICulture; + return html; + } + + /// + /// Gets the current UI culture. + /// + /// The HTML. + /// + /// html + public static CultureInfo GetUICulture(this HtmlHelper html) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewContext != null && html.ViewContext.HttpContext != null) + return (CultureInfo)html.ViewData["UICulture"] ?? (CultureInfo)html.ViewContext.HttpContext.Items["UICulture"] ?? CultureInfo.CurrentUICulture; + return (CultureInfo)html.ViewData["UICulture"] ?? CultureInfo.CurrentUICulture; + } + + #region Display date/time + + /// + /// Sets the date and time formats. + /// + /// The HTML. + /// The date format for Html.DisplayDate(DateTime). + /// The date tz format for Html.DisplayDate(DateTimeOffset). + /// The time format for Html.DisplayTime(DateTime). + /// The time tz format for Html.DisplayDate(DateTimeOffset). + /// The timespan format for Html.DisplayTime(TimeSpan). + /// The date time format for Html.DisplayDateTime(DateTime). + /// The short time format for Html.DisplayShortTime(DateTime). + /// The short timespan format for Html.DisplayShortTime(TimeSpan). + /// + /// html + /// or + /// html.ViewContext + /// or + /// html.ViewContext.HttpContext + public static HtmlHelper SetDateTimeFormats(this HtmlHelper html, string dateFormat = null, string dateTzFormat = null, string timeFormat = null, string timeTzFormat = null, string timespanFormat = null, string dateTimeFormat = null, string shortTimeFormat = null, string shortTimespanFormat = null) + { + if (html == null) + throw new ArgumentNullException("html"); + if (html.ViewContext == null) + throw new ArgumentNullException("html.ViewContext"); + if (html.ViewContext.HttpContext == null) + throw new ArgumentNullException("html.ViewContext.HttpContext"); + + html.ViewContext.HttpContext.SetDateTimeFormats(dateFormat, dateTzFormat, timeFormat, timeTzFormat, timespanFormat, dateTimeFormat); + + + return html; + } + + /// + /// Gets the date and time formats. + /// + /// The HTML. + /// + /// + /// html + /// or + /// html.ViewContext + /// or + /// html.ViewContext.HttpContext + /// + public static string[] GetDateTimeFormats(this HtmlHelper html) + { + if (html == null) + throw new ArgumentNullException("html"); + if (html.ViewContext == null) + throw new ArgumentNullException("html.ViewContext"); + if (html.ViewContext.HttpContext == null) + throw new ArgumentNullException("html.ViewContext.HttpContext"); + + var values = (string[])html.ViewContext.HttpContext.Items[DefaultDateTimeFormatsKey] ?? DefaultDateTimeFormats.ToArray(); + + return values; + } + + /// + /// Displays a date and a time. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// The display date format (use to change the default display value format). + /// + public static MvcHtmlString DisplayDateTime(this HtmlHelper html, DateTime date, bool useTimeTag = true, string display = null, string displayDateFormat = null) + { + var defaultFormat = html.GetDateTimeFormats()[5]; + DateTime utc; + DateTime userDate = html.GetUserDate(date, out utc); + string displayTime = userDate.ToString(displayDateFormat ?? defaultFormat); + if (display == null) + display = displayTime; + + if (useTimeTag) + { + string tag = string.Format( + "", + display, + utc.ToString("O"), + userDate.ToString("G"), + GetDateClasses(utc) + "display-datetime"); + return MvcHtmlString.Create(tag); + } + else + { + return MvcHtmlString.Create(display); + } + } + + private static string GetDateClasses(DateTime date) + { + string classes = ""; + if (date.Kind == DateTimeKind.Utc) + { + classes += date > DateTime.UtcNow ? "future " : "past "; + classes += date.IsEqualTo(DateTime.UtcNow, DateTimePrecision.Day) ? "today " : "not-today "; + } + + if (date.Kind == DateTimeKind.Local) + { + classes += date > DateTime.Now ? "future " : "past "; + classes += date.IsEqualTo(DateTime.Now, DateTimePrecision.Day) ? "today " : "not-today "; + } + + return classes; + } + + private static string GetDateClasses(DateTimeOffset date) + { + return GetDateClasses(date.UtcDateTime); + } + + /// + /// Displays a date. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// The display date format (use to change the default display value format). + /// + public static MvcHtmlString DisplayDate(this HtmlHelper html, DateTime date, bool useTimeTag = true, string display = null, string displayDateFormat = null) + { + DateTime utc; + DateTime userDate = html.GetUserDate(date, out utc); + var defaultFormat = html.GetDateTimeFormats()[0]; + string displayTime = userDate.ToString(displayDateFormat ?? defaultFormat); + if (display == null) + display = displayTime; + + if (useTimeTag) + { + string tag = string.Format( + "", + display, + utc.ToString("O"), + userDate.ToString("D"), + GetDateClasses(utc) + "display-date"); + return MvcHtmlString.Create(tag); + } + else + { + return MvcHtmlString.Create(display); + } + } + + /// + /// Displays a date. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// The display date format (use to change the default display value format). + /// + public static MvcHtmlString DisplayDate(this HtmlHelper html, DateTimeOffset date, bool useTimeTag = true, string display = null, string displayDateFormat = null) + { + var defaultFormat = html.GetDateTimeFormats()[1]; + string displayTime = date.ToString(displayDateFormat ?? defaultFormat); + if (display == null) + display = displayTime; + + if (useTimeTag) + { + string tag = string.Format( + "", + display, + date.ToUniversalTime().ToString("O"), + date.ToString("D zzz"), + GetDateClasses(date) + "display-date"); + return MvcHtmlString.Create(tag); + } + else + { + return MvcHtmlString.Create(display); + } + } + + /// + /// Displays a time. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// The display date format (use to change the default display value format). + /// + public static MvcHtmlString DisplayTime(this HtmlHelper html, DateTime date, bool useTimeTag = true, string display = null, string displayDateFormat = null) + { + DateTime utc; + DateTime userDate = html.GetUserDate(date, out utc); + var defaultFormat = html.GetDateTimeFormats()[2]; + string displayTime = userDate.ToString(displayDateFormat ?? defaultFormat); + if (display == null) + display = displayTime; + + if (useTimeTag) + { + string tag = string.Format( + "", + display, + utc.ToString("O"), + userDate.ToString("G"), + GetDateClasses(utc) + "display-time"); + return MvcHtmlString.Create(tag); + } + else + { + return MvcHtmlString.Create(display); + } + } + + /// + /// Displays a time. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// The display date format (use to change the default display value format). + /// + public static MvcHtmlString DisplayTime(this HtmlHelper html, DateTimeOffset date, bool useTimeTag = true, string display = null, string displayDateFormat = null) + { + var defaultFormat = html.GetDateTimeFormats()[3]; + string displayTime = date.ToLocalTime().ToString(displayDateFormat ?? defaultFormat); + if (display == null) + display = displayTime; + + if (useTimeTag) + { + string tag = string.Format( + "", + display, + date.ToUniversalTime().ToString("O"), + date.ToString("R"), + GetDateClasses(date) + "display-time"); + return MvcHtmlString.Create(tag); + } + else + { + return MvcHtmlString.Create(display); + } + } + + /// + /// Displays a time. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// The display date format (use to change the default display value format). + /// + public static MvcHtmlString DisplayTime(this HtmlHelper html, TimeSpan date, bool useTimeTag = true, string display = null, string displayDateFormat = null) + { + var defaultFormat = html.GetDateTimeFormats()[4]; + string displayTime = date.ToString(displayDateFormat ?? defaultFormat); + if (display == null) + display = displayTime; + + if (useTimeTag) + { + string tag = string.Format( + "", + display, + date.ToString("c"), + date.ToString("c"), + "display-time"); + return MvcHtmlString.Create(tag); + } + else + { + return MvcHtmlString.Create(display); + } + } + + /// + /// Returns the date (to UTC) in JavaScript format like 'new Date(123456789000)'. + /// + /// The HTML. + /// The date. + /// The precision. + /// + public static MvcHtmlString JsDate(this HtmlHelper html, DateTime date, DateTimePrecision precision = DateTimePrecision.Second) + { + DateTime utc = SrkHtmlExtensions.GetUtcDate(html, date); + /* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date + * new Date(value); + * value: Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch) + * + * I use this constructor because it accepts a UTC date. + * The other constructors use a local date so we can't rely on them. + * + * ToString("F0") is important to avoid the exponential notation. + */ + string value = "new Date(" + + (utc.ToPrecision(precision).Subtract(UnixEpoch).TotalMilliseconds).ToString("F0") + + ")"; + return MvcHtmlString.Create(value); + } + + /// + /// Displays a time. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// + public static MvcHtmlString DisplayShortTime(this HtmlHelper html, DateTime date, bool useTimeTag = true, string display = null) + { + var defaultFormat = html.GetDateTimeFormats()[6]; + return html.DisplayTime(date, useTimeTag, display, displayDateFormat: defaultFormat); + } + + /// + /// Displays a time. + /// + /// The HTML. + /// The date value. + /// if set to true the date will be enclsoed in a <time> tag. + /// The display value (use to manualy set the display value). + /// + public static MvcHtmlString DisplayShortTime(this HtmlHelper html, TimeSpan date, bool useTimeTag = true, string display = null) + { + var defaultFormat = html.GetDateTimeFormats()[7]; + return html.DisplayTime(date, useTimeTag, display, displayDateFormat: defaultFormat); + } + + #endregion + + #region Display text + + /// + /// Replaces new lines by line breaks (<br />) + /// + /// The HTML. + /// The content. + /// if set to true make links from URLs and email addresses. + /// The class attribute to associate to <a> tags (defaults to "external"). + /// The target attribute to associate to <a> tags (default to "_blank"). + /// + public static MvcHtmlString LineBreaks(this HtmlHelper html, string content, bool makeLinks = false, string linkClasses = "external accentColor", string linkTarget = "_self") + { + if (content == null) + return MvcHtmlString.Create(string.Empty); + + content = content.ProperHtmlEscape(); + + if (makeLinks) + { + content = content.LinksAsHtml(linkClasses: linkClasses, linkTarget: linkTarget); + } + + content = content.AddHtmlLineBreaks(); + + return MvcHtmlString.Create(content); + } + + /// + /// Trims the text from the right, leaving the specified number of characters. + /// + /// The HTML. + /// The text. + /// The number of characters desired. + /// The ending string (used only if trim occured). + /// + public static string TrimText(this HtmlHelper html, string text, int chars, string ending = "...") + { + return text.TrimTextRight(chars, ending); + } + + /// + /// Formats a user string as HTML; + /// Replaces newlines with line breaks. + /// Replaces URLs with links. + /// Escapes HTML chars. + /// + /// The HTML. + /// the content to transform + /// if set to true make links from URLs and email addresses. + /// if set to true make paragraphs from groups of text (separated by multiple lines). + /// if set to true make line breaks from new lines. + /// if set to true make twitter links from @mentions and #hashes. + /// The class attribute to associate to <a> tags (defaults to "external"). + /// The target attribute to associate to <a> tags (default to "_blank"). + /// Indicates wether to wrap the HTML into a div element. + /// + /// an escaped HTML string + /// + public static MvcHtmlString DisplayText(this HtmlHelper html, string content, bool makeLinks = true, bool makeParagraphs = true, bool makeLineBreaks = true, bool twitterLinks = false, string linksClass = "external", string linksTarget = "_blank", string wrapClass = null) + { + if (content == null) + return MvcHtmlString.Create(string.Empty); + + content = content.ProperHtmlEscape(); + + if (makeLinks) + content = content.LinksAsHtml(linkClasses: linksClass, linkTarget: linksTarget, avoidDoubleEscape: true); + + if (twitterLinks) + content = content.TwitterLinksAsHtml(linkClasses: linksClass + " twitter", linkTarget: linksTarget); + + if (makeParagraphs) + content = content.HtmlParagraphizify(makeLineBreaks: makeLineBreaks); + else if (makeLineBreaks) + content = content.AddHtmlLineBreaks(); + + if (wrapClass == null) + return MvcHtmlString.Create(content); + else + return MvcHtmlString.Create("
" + content + "
"); + } + + #endregion + + #endregion + + /// + /// Returns many HTML radio buttons for the specified list and selected value. + /// + /// The type of the model. + /// The type of the property. + /// The HTML helper. + /// The model expression. + /// The list of values. + /// + public static MvcHtmlString RadioButtonSelectList( + this HtmlHelper htmlHelper, + Expression> expression, + IEnumerable listOfValues) + { + var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); + var sb = new StringBuilder(); + + if (listOfValues != null) + { + // Create a radio button for each item in the list + foreach (SelectListItem item in listOfValues) + { + // Generate an id to be given to the radio button field + ////var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value); + var id = metaData.PropertyName + "_" + item.Value; + + // Create and populate a radio button using the existing html helpers + var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text)); + var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString(); + + // Create the html string that will be returned to the client + // e.g. + sb.AppendFormat("
{0}{1}
", radio, label); + } + } + + return MvcHtmlString.Create(sb.ToString()); + } + + #region GetFullHtmlFieldName + + public static string GetFullHtmlFieldName(this HtmlHelper helper, Expression> expression) + { + return helper.ViewData.TemplateInfo.GetFullHtmlFieldName(expression); + } + + public static string GetFullHtmlFieldId(this HtmlHelper helper, Expression> expression) + { + return helper.ViewData.TemplateInfo.GetFullHtmlFieldId(expression); + } + + public static string GetFullHtmlFieldName(this TemplateInfo templateInfo, Expression> expression) + { + return templateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)); + } + + public static string GetFullHtmlFieldId(this TemplateInfo templateInfo, Expression> expression) + { + return templateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)); + } + + public static string GetFullHtmlFieldDisplayName(this HtmlHelper helper, Expression> expression) + { + var propertyName = helper.GetFullHtmlFieldName(expression); + + return helper.ViewData.ModelMetadata.Properties.Single(p => p.PropertyName == propertyName).DisplayName; + } + + #endregion + + #region DescriptionFor + + /// + /// Returns an HTML span element and the property name of the property that is represented by the specified expression. + /// + /// The type of the model. + /// The type of the property. + /// The HTML helper instance that this method extends. + /// An expression that identifies the property to display. + /// An HTML span element and the property name of the property that is represented by the specified expression + public static MvcHtmlString DescriptionFor( + this HtmlHelper helper, + Expression> expression) + { + return DescriptionFor(helper, expression, null, null); + } + + /// + /// Returns an HTML span element and the property name of the property that is represented by the specified expression. + /// + /// The type of the model. + /// The type of the property. + /// The HTML helper instance that this method extends. + /// An expression that identifies the property to display. + /// An object that contains the HTML attributes to set for the element. + /// + /// An HTML span element and the property name of the property that is represented by the specified expression + /// + public static MvcHtmlString DescriptionFor( + this HtmlHelper helper, + Expression> expression, + object htmlAttributes) + { + return DescriptionFor(helper, expression, null, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); + } + + /// + /// Returns an HTML span element and the property name of the property that is represented by the specified expression. + /// + /// The type of the model. + /// The type of the property. + /// The HTML helper instance that this method extends. + /// An expression that identifies the property to display. + /// An object that contains the HTML attributes to set for the element. + /// + /// An HTML span element and the property name of the property that is represented by the specified expression + /// + public static MvcHtmlString DescriptionFor( + this HtmlHelper helper, + Expression> expression, + IDictionary htmlAttributes) + { + return DescriptionFor(helper, expression, null, htmlAttributes); + } + + /// + /// Returns an HTML span element and the property name of the property that is represented by the specified expression. + /// + /// The type of the model. + /// The type of the property. + /// The HTML helper instance that this method extends. + /// An expression that identifies the property to display. + /// The description text to display. + /// An object that contains the HTML attributes to set for the element. + /// + /// An HTML span element and the property name of the property that is represented by the specified expression + /// + public static MvcHtmlString DescriptionFor( + this HtmlHelper helper, + Expression> expression, + string descriptionText, + IDictionary htmlAttributes) + { + var meta = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); + var value = descriptionText.NullIfEmpty() ?? meta.Description.NullIfEmpty(); + + if (string.IsNullOrEmpty(value)) + return MvcHtmlString.Empty; + + var htmlFieldName = ExpressionHelper.GetExpressionText(expression); + var id = TagBuilder.CreateSanitizedId(helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)); + var tag = new TagBuilder("span"); + tag.Attributes.Add("data-for", id); + tag.MergeAttributes(htmlAttributes, true); + tag.SetInnerText(value); + return tag.ToMvcHtmlString(TagRenderMode.Normal); + } + + #endregion + + #region BeginFormEx + + /// + /// Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by an action method. + /// + /// The HTML helper. + /// An object that contains the HTML attributes to set for the element. + /// An opening <form> tag. + public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, object htmlAttributes) + { + string rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl; + return htmlHelper.BeginForm(null, null, htmlHelper.ViewContext.RouteData.Values, FormMethod.Post, new RouteValueDictionary(htmlAttributes) as IDictionary); + } + + /// + /// Writes an opening <form> tag to the response. When the user submits the form, the request will be processed by an action method. + /// + /// The HTML helper. + /// An object that contains the HTML attributes to set for the element. + /// An object that contains the parameters for a route. The parameters are retrieved through reflection by examining the properties of the object. This object is typically created by using object initializer syntax. + /// An opening <form> tag. + public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, object htmlAttributes, object routeValues) + { + string rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl; + return htmlHelper.BeginForm(null, null, routeValues, FormMethod.Post, htmlAttributes); + } + + #endregion + + #region Submit + + /// + /// Returns a submit input element by using the specified HTML helper and the name of the form field. + /// + /// The HTML. + /// The value. + /// An input element whose type attribute is set to "submit". + public static MvcHtmlString Submit(this HtmlHelper html, string value) + { + var builder = new TagBuilder("input"); + builder.MergeAttribute("type", "submit"); + builder.MergeAttribute("value", value); + return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing)); + } + + /// + /// Returns a submit input element by using the specified HTML helper and the name of the form field. + /// + /// The HTML. + /// The value. + /// The name. + /// An input element whose type attribute is set to "submit". + public static MvcHtmlString Submit(this HtmlHelper html, string value, string name) + { + var builder = new TagBuilder("input"); + builder.MergeAttribute("type", "submit"); + builder.MergeAttribute("name", name); + builder.MergeAttribute("value", value); + return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing)); + } + + /// + /// Returns a submit input element by using the specified HTML helper and the name of the form field. + /// + /// The HTML. + /// The value. + /// The name. + /// An object that contains the HTML attributes to set for the element. + /// An input element whose type attribute is set to "submit". + public static MvcHtmlString Submit(this HtmlHelper html, string value, string name, object htmlAttributes) + { + var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); + var builder = new TagBuilder("input"); + builder.MergeAttributes(attributes); + builder.MergeAttribute("type", "submit"); + builder.MergeAttribute("name", name); + builder.MergeAttribute("value", value); + return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing)); + } + + #endregion + + #region File + + /// + /// Returns a file input element by using the specified HTML helper and the name of the form field. + /// + /// The HTML. + /// The name. + /// An input element whose type attribute is set to "file". + public static MvcHtmlString File(this HtmlHelper html, string name) + { + var builder = new TagBuilder("input"); + builder.MergeAttribute("type", "file"); + builder.MergeAttribute("name", name); + return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing)); + } + + /// + /// Returns a file input element by using the specified HTML helper and the name of the form field. + /// + /// The HTML. + /// The name. + /// An object that contains the HTML attributes to set for the element. + /// An input element whose type attribute is set to "file". + public static MvcHtmlString File(this HtmlHelper html, string name, object htmlAttributes) + { + var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); + var builder = new TagBuilder("input"); + builder.MergeAttributes(attributes); + builder.MergeAttribute("type", "file"); + builder.MergeAttribute("name", name); + return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing)); + } + + #endregion + + #region OpenGraph + + /// + /// Gets the opengraph object associated with the current HTTP request. + /// + /// + /// + public static SrkOpenGraphHtmlExtensions OpenGraph(this HtmlHelper html) + { + return new SrkOpenGraphHtmlExtensions(html); + } + + #endregion + + #region ActionLink + + /// + /// Returns an anchor element (a element) that contains the virtual path of the specified action. + /// + /// The HTML helper instance that this method extends. + /// The inner text of the anchor element. + /// + /// An object that contains the parameters for a route. The parameters are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax. + /// An object that contains the HTML attributes to set for the element. + /// The URL fragment name (the anchor name). + /// The name of the controller. + /// The protocol for the URL, such as "http" or "https". + /// The host name for the URL. + /// + public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes = null, string fragment = null, string controllerName = null, string protocol = null, string hostName = null) + { + return htmlHelper.ActionLink(linkText, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes); + } + + #endregion + + /// + /// Helps write a CSS class base on a condition. + /// + /// The HTML. + /// A display condition. + /// The class to display if the condition is true. + /// The class to display if the condition is false. + /// The CSS class corresponding to the condition + public static string CssClass(this HtmlHelper html, bool condition, string classTrue, string classFalse = null) + { + return condition ? classTrue : classFalse; + } + + /// + /// Helps write a CSS class base on a condition. + /// + /// The HTML. + /// A display condition. + /// The class to display if the condition is true. + /// The class to display if the condition is false. + /// The class to display if the condition is null. + /// The CSS class corresponding to the condition + public static string CssClass(this HtmlHelper html, bool? condition, string classTrue, string classFalse = null, string classNull = null) + { + if (condition != null) + return condition.Value ? classTrue : classFalse; + return classNull; + } + + /// + /// Determines whether the model state contains other validation errors. + /// + /// The HTML. + /// + /// html + public static bool HasOtherValidationErrors(this HtmlHelper html) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewData.ModelState.IsValid) + return false; + + if (!html.ViewData.ModelState.ContainsKey(string.Empty)) + return false; + + if (html.ViewData.ModelState[string.Empty] == null) + return true; + + if (html.ViewData.ModelState[string.Empty].Errors == null) + return true; + + return html.ViewData.ModelState[string.Empty].Errors.Count > 0; + } + + /// + /// Enhancement of that shows no HTML when there are no errors to display. + /// + /// The HTML. + /// A string that contains an unordered list (ul element) of validation messages. + public static MvcHtmlString ValidationSummaryEx(this HtmlHelper html) + { + if (SrkHtmlExtensions.HasOtherValidationErrors(html)) + { + return html.ValidationSummary(true); + } + + return null; + } + + /// + /// Gets the associated to the request. + /// + /// The HTML. + /// + public static NavigationLine NavigationLine(this HtmlHelper html) + { + if (html.ViewContext == null) + throw new ArgumentNullException("ViewContext is not set", "ctrl"); + + if (html.ViewContext.HttpContext == null) + throw new ArgumentNullException("HttpContext is not set", "ctrl"); + + var line = html.ViewContext.HttpContext.Items[SrkControllerExtensions.NavigationLineKey] as NavigationLine; + if (line == null) + { + line = new NavigationLine(); + html.ViewContext.HttpContext.Items[SrkControllerExtensions.NavigationLineKey] = line; + } + + return line; + } + + /// + /// Returns an anchor element (a element) that contains a phone call url. + /// + /// The HTML. + /// The phone number. + /// + public static MvcHtmlString CallLink(this HtmlHelper html, string phoneNumber) + { + return SrkHtmlExtensions.CallLink(html, phoneNumber, new { @class = "tel", }); + } + + /// + /// Returns an anchor element (a element) that contains a phone call url. + /// + /// The HTML. + /// The phone number. + /// An object that contains the HTML attributes for the element. + /// + public static MvcHtmlString CallLink(this HtmlHelper html, string phoneNumber, object attributes) + { + var tag = new TagBuilder("a"); + tag.Attributes.Add("href", "tel:" + phoneNumber); + var attrCollection = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes); + tag.MergeAttributes(attrCollection, true); + tag.SetInnerText(phoneNumber); + return tag.ToMvcHtmlString(TagRenderMode.Normal); + } + + /// + /// Helps attach descriptors to a page in order to generate meta/link tags. + /// + /// The HTML. + /// The for the current request. + /// html or html.ViewContext or html.ViewContext.HttpContext + public static PageInfo GetPageInfo(this HtmlHelper html) + { + if (html == null) + throw new ArgumentNullException("html"); + + if (html.ViewContext == null) + throw new ArgumentNullException("html.ViewContext"); + + if (html.ViewContext.HttpContext == null) + throw new ArgumentNullException("html.ViewContext.HttpContext"); + + var httpContext = html.ViewContext.HttpContext; + var item = httpContext.Items[SrkControllerExtensions.PageInfoKey] as PageInfo; + if (item == null) + { + item = new PageInfo(); + httpContext.Items[SrkControllerExtensions.PageInfoKey] = item; + } + + return item; + } + } +} diff --git a/Sources/SrkToolkit.Web.AspMvc5/SrkToolkit.Web.AspMvc5.csproj b/Sources/SrkToolkit.Web.AspMvc5/SrkToolkit.Web.AspMvc5.csproj index 8fab804..7639183 100644 --- a/Sources/SrkToolkit.Web.AspMvc5/SrkToolkit.Web.AspMvc5.csproj +++ b/Sources/SrkToolkit.Web.AspMvc5/SrkToolkit.Web.AspMvc5.csproj @@ -3,16 +3,43 @@ disable disable - net45;net46 - 9 + 10 + SrkToolkit.Web for .NET 4.5 and ASP MVC 5 + net472;net462 + + TRACE;ASPMVC + + + + TRACE;ASPMVC + + + + + True + + logo-200.png + + + SrkToolkit.snk + + + + + ..\..\..\..\..\..\.nuget\packages\microsoft.extensions.hosting.abstractions\2.0.0\lib\netstandard2.0\Microsoft.Extensions.Hosting.Abstractions.dll + + + + + @@ -20,7 +47,104 @@ + + + + + + + + + Fakes\Dummy.cs + + + Filters\Dummy.cs + + + HttpErrors\Dummy.cs + + + Internals.cs + + + Models\HttpErrorModel.cs + + + Models\NavigationLine.cs + + + Models\NavigationLineEntry.cs + + + Models\TempMessage.cs + + + Mvc\DecimalModelBinder.cs + + + Mvc\Dummy.cs + + + Mvc\IntegerModelBinder.cs + + + Services\DictionarySessionServiceSource.cs + + + SrkControllerExtensions.cs + + + SrkHttpApplication.cs + + + SrkHttpApplication.tt.cs + + + SrkHttpContextExtensions.cs + + + SrkHttpRequestExtensions.cs + + + SrkMvcCollectionExtensions.cs + + + SrkRequestExtensions.cs + + + SrkTagBuilderExtensions.cs + + + SrkTempDataDictionaryExtensions.cs + + + SrkUrlHelperExtensions.cs + + + SrkViewExtensions.cs + + + WebDependencies.cs + + + WebDependenciesExtensions.cs + + + WebDependency.cs + + + WebDependencyFile.cs + + + + + + + SrkHttpApplication.tt + + + diff --git a/Sources/SrkToolkit.Web.AspNetCore2/Mvc/DecimalModelBinder.cs b/Sources/SrkToolkit.Web.AspNetCore2/Mvc/DecimalModelBinder.cs index ecdee11..c9c6630 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/Mvc/DecimalModelBinder.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/Mvc/DecimalModelBinder.cs @@ -16,13 +16,21 @@ namespace SrkToolkit.Web.Mvc { - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.ModelBinding; +#if ASPMVCCORE + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Mvc.ModelBinding; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using System; using System.Collections.Generic; using System.Linq; using System.Text; - using System.Web.Mvc; using System.Globalization; using System.Reflection; diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkControllerExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkControllerExtensions.cs index aa89ae9..e2971ca 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkControllerExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkControllerExtensions.cs @@ -16,8 +16,17 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Routing; +#if ASPMVCCORE + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Routing; +#endif + +#if ASPMVC + using System.Web.Mvc; + using System.Web.Caching; + using System.Web.Routing; +#endif + using SrkToolkit.Web.Models; using SrkToolkit.Web.Open; using System; @@ -52,7 +61,8 @@ public static NavigationLine NavigationLine(this Controller ctrl) return line; } -/* + +#if ASPMVC /// /// Gets an item from the HTTP cache. /// @@ -63,7 +73,7 @@ public static NavigationLine NavigationLine(this Controller ctrl) /// The build data. /// The identifier. /// - [Obsolete("Under devleopment")] + [Obsolete("Under development")] public static T GetFromCache(this Controller ctrl, TimeSpan duration, CacheItemPriority priority, Func buildData, string id) where T : class { @@ -88,7 +98,7 @@ public static T GetFromCache(this Controller ctrl, TimeSpan duration, CacheIt /// The priority. /// The build data. /// - [Obsolete("Under devleopment")] + [Obsolete("Under development")] public static T GetFromCache(this Controller ctrl, TimeSpan duration, CacheItemPriority priority, Func buildData) where T : class { @@ -103,7 +113,7 @@ public static T GetFromCache(this Controller ctrl, TimeSpan duration, CacheIt return value; } -*//* + /// /// Clears an item from the HTTP cache. /// @@ -111,7 +121,7 @@ public static T GetFromCache(this Controller ctrl, TimeSpan duration, CacheIt /// The controller. /// The identifier. /// - [Obsolete("Under devleopment")] + [Obsolete("Under development")] public static T ClearFromCache(this Controller ctrl, string id) where T : class { @@ -133,7 +143,7 @@ public static T ClearFromCache(this Controller ctrl, string id) /// /// The control. /// - [Obsolete("Under devleopment")] + [Obsolete("Under development")] public static T ClearFromCache(this Controller ctrl) where T : class { @@ -148,7 +158,7 @@ public static T ClearFromCache(this Controller ctrl) return null; } -*/ +#endif /// /// Gets a action result that will redirect the user to the specified local path. Fallbacks to a second path. Then fallbacks to /Home/Index /// @@ -177,7 +187,7 @@ public static ActionResult RedirectToLocal(this Controller controller, string lo return new RedirectToRouteResult(values); } } -/* +#if ASPMVC /// /// Gets the first valid local URL from the method arguments. /// @@ -216,7 +226,8 @@ public static string GetAnyLocalUrl(this Controller controller, string url1, boo return null; } -*/ +#endif + /// /// Helps attach descriptors to a page in order to generate meta/link tags. /// diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpContextExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpContextExtensions.cs index 8d479c2..50407cb 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpContextExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpContextExtensions.cs @@ -16,7 +16,18 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Http; + +#if ASPMVCCORE + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Routing; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using System; using System.Collections.Generic; using System.Globalization; @@ -41,7 +52,8 @@ public static string GetUserIdentityName(this HttpContext httpContext) return httpContext.User != null && httpContext.User.Identity != null ? httpContext.User.Identity.Name.NullIfEmptyOrWhitespace() : null; } -/* + +#if ASPMVC /// /// Fast access to HttpContext.User.Identity.Name. /// @@ -55,7 +67,7 @@ public static string GetUserIdentityName(this HttpContextBase httpContext) return httpContext.User != null && httpContext.User.Identity != null ? httpContext.User.Identity.Name.NullIfEmptyOrWhitespace() : null; } -*//* + /// /// Sets the timezone for displays of dates and times. /// @@ -72,7 +84,7 @@ public static HttpContextBase SetTimezone(this HttpContextBase http, string time SrkHttpContextExtensions.SetTimezone(http, TimeZoneInfo.FindSystemTimeZoneById(timeZoneName)); return http; } -*//* + /// /// Sets the timezone for displays of dates and times. /// @@ -88,7 +100,8 @@ public static HttpContextBase SetTimezone(this HttpContextBase http, TimeZoneInf http.Items["Timezone"] = timeZone; return http; } -*/ +#endif + /// /// Sets the timezone for displays of dates and times. /// @@ -121,7 +134,8 @@ public static HttpContext SetTimezone(this HttpContext http, TimeZoneInfo timeZo http.Items["Timezone"] = timeZone; return http; } -/* + +#if ASPMVC /// /// Gets the timezone for displays of dates and times. /// @@ -135,7 +149,8 @@ public static TimeZoneInfo GetTimezone(this HttpContextBase http) return (TimeZoneInfo)http.Items["Timezone"] ?? TimeZoneInfo.Utc; } -*/ +#endif + /// /// Gets the timezone for displays of dates and times. /// @@ -149,7 +164,8 @@ public static TimeZoneInfo GetTimezone(this HttpContext http) return (TimeZoneInfo)http.Items["Timezone"] ?? TimeZoneInfo.Utc; } -/* + +#if ASPMVC /// /// Sets the culture. /// @@ -173,7 +189,8 @@ public static HttpContextBase SetCulture(this HttpContextBase http, string cultu http.Items["Culture"] = cultureInfo; return http; } -*/ +#endif + /// /// Sets the culture. /// @@ -197,7 +214,8 @@ public static HttpContext SetCulture(this HttpContext http, string culture) http.Items["Culture"] = cultureInfo; return http; } -/* + +#if ASPMVC /// /// Sets the culture. /// @@ -213,7 +231,8 @@ public static HttpContextBase SetCulture(this HttpContextBase http, CultureInfo http.Items["Culture"] = culture; return http; } -*/ +#endif + /// /// Sets the culture. /// @@ -229,7 +248,8 @@ public static HttpContext SetCulture(this HttpContext http, CultureInfo culture) http.Items["Culture"] = culture; return http; } -/* + +#if ASPMVC /// /// Gets the current culture. /// @@ -243,7 +263,8 @@ public static CultureInfo GetCulture(this HttpContextBase http) return (CultureInfo)http.Items["Culture"] ?? CultureInfo.CurrentCulture; } -*/ +#endif + /// /// Gets the current culture. /// @@ -257,7 +278,8 @@ public static CultureInfo GetCulture(this HttpContext http) return (CultureInfo)http.Items["Culture"] ?? CultureInfo.CurrentCulture; } -/* + +#if ASPMVC /// /// Sets the UICulture. /// @@ -281,7 +303,8 @@ public static HttpContextBase SetUICulture(this HttpContextBase http, string uIC http.Items["UICulture"] = cultureInfo; return http; } -*/ +#endif + /// /// Sets the UICulture. /// @@ -305,7 +328,8 @@ public static HttpContext SetUICulture(this HttpContext http, string uICulture) http.Items["UICulture"] = cultureInfo; return http; } -/* + +#if ASPMVC /// /// Sets the UICulture. /// @@ -321,7 +345,8 @@ public static HttpContextBase SetUICulture(this HttpContextBase http, CultureInf http.Items["UICulture"] = uICulture; return http; } -*/ +#endif + /// /// Sets the UICulture. /// @@ -337,7 +362,8 @@ public static HttpContext SetUICulture(this HttpContext http, CultureInfo uICult http.Items["UICulture"] = uICulture; return http; } -/* + +#if ASPMVC /// /// Gets the current UICulture. /// @@ -351,7 +377,8 @@ public static CultureInfo GetUICulture(this HttpContextBase http) return (CultureInfo)http.Items["UICulture"] ?? CultureInfo.CurrentUICulture; } -*/ +#endif + /// /// Gets the current UICulture. /// @@ -365,7 +392,8 @@ public static CultureInfo GetUICulture(this HttpContext http) return (CultureInfo)http.Items["UICulture"] ?? CultureInfo.CurrentUICulture; } -/* + +#if ASPMVC /// /// Sets the date and time formats. /// @@ -379,7 +407,7 @@ public static CultureInfo GetUICulture(this HttpContext http) /// The short time format for Html.DisplayShortTime(DateTime). /// The short timespan format for Html.DisplayShortTime(TimeSpan). /// httpContext - public static void SetDateTimeFormats(this HttpContext httpContext, string dateFormat = null, string dateTzFormat = null, string timeFormat = null, string timeTzFormat = null, string timespanFormat = null, string dateTimeFormat = null, string shortTimeFormat = null, string shortTimespanFormat = null) + public static void SetDateTimeFormats(this HttpContextBase httpContext, string dateFormat = null, string dateTzFormat = null, string timeFormat = null, string timeTzFormat = null, string timespanFormat = null, string dateTimeFormat = null, string shortTimeFormat = null, string shortTimespanFormat = null) { if (httpContext == null) throw new ArgumentNullException("httpContext"); @@ -438,7 +466,7 @@ public static void SetDateTimeFormats(this HttpContext httpContext, string dateF httpContext.Items[SrkHtmlExtensions.DefaultDateTimeFormatsKey] = values; } -*//* + /// /// Gets the date and time formats. /// @@ -450,11 +478,12 @@ public static string[] GetDateTimeFormats(this HttpContextBase httpContext) if (httpContext == null) throw new ArgumentNullException("httpContext"); - var values = (string[])httpContext.Items[System.Web.Mvc.SrkHtmlExtensions.defaultDateTimeFormatsKey] - ?? System.Web.Mvc.SrkHtmlExtensions.defaultDateTimeFormats.ToArray(); + var values = (string[])httpContext.Items[System.Web.Mvc.SrkHtmlExtensions.DefaultDateTimeFormatsKey] + ?? System.Web.Mvc.SrkHtmlExtensions.DefaultDateTimeFormats.ToArray(); return values; } -*/ +#endif + } } diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpRequestExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpRequestExtensions.cs index ab17355..ca5ea3d 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpRequestExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkHttpRequestExtensions.cs @@ -1,14 +1,26 @@  namespace SrkToolkit.AspNetCore { - using Microsoft.AspNetCore.Http; + +#if ASPMVCCORE + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Routing; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + + using System; using System.Diagnostics; using System.Linq; - using System.Net.Http; public static class SrkHttpRequestExtensions { +#if ASPMVCCORE public static bool PrefersJson(this HttpRequestMessage request) { if (request.Headers.Accept.Any()) @@ -24,9 +36,10 @@ public static bool PrefersJson(this HttpRequestMessage request) return false; } - +#endif + +/* // TODO: support HttpRequest.PrefersJson, but which nuget? -#if !NETSTANDARD public static bool PrefersJson(this HttpRequest request) { Debug.Assert(request != null, nameof(request) + " != null"); @@ -43,6 +56,7 @@ public static bool PrefersJson(this HttpRequest request) return false; } -#endif +*/ + } } diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkMvcCollectionExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkMvcCollectionExtensions.cs index 724157e..05e9c2f 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkMvcCollectionExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkMvcCollectionExtensions.cs @@ -16,7 +16,15 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Mvc.Rendering; +#if ASPMVCCORE + using Microsoft.AspNetCore.Mvc.Rendering; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using System; using System.Collections.Generic; using System.Linq; diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkRequestExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkRequestExtensions.cs index 0d86b3d..9f96a35 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkRequestExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkRequestExtensions.cs @@ -16,9 +16,19 @@ namespace SrkToolkit.Web { +#if ASPMVCCORE using Microsoft.AspNetCore.Http; - using System; - using System.Collections.Generic; + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Routing; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + + using System; + using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; @@ -41,13 +51,23 @@ public static class SrkRequestExtensions /// /// true if [is XML HTTP request] [the specified request]; otherwise, false. /// - public static bool IsXmlHttpRequest(this HttpRequest request) - { + public static bool IsXmlHttpRequest( +#if ASPMVCCORE + this HttpRequest request +#elif ASPMVC + this HttpRequestBase request +#endif + ) + { var header = request.Headers["X-Requested-With"]; if (string.IsNullOrEmpty(header)) return false; - return xhrValues.Any(searchValue => header.Any(value => value.Equals(searchValue, StringComparison.OrdinalIgnoreCase))); +#if ASPMVCCORE + return xhrValues.Any(searchValue => header.Any(value => value.Equals(searchValue, StringComparison.OrdinalIgnoreCase))); +#elif ASPMVC + return xhrValues.Contains(header.ToUpperInvariant()); +#endif } /// @@ -55,50 +75,105 @@ public static bool IsXmlHttpRequest(this HttpRequest request) /// /// The request. /// - public static bool IsHttpGetRequest(this HttpRequest request) - { - return "GET".Equals(request.Method, StringComparison.OrdinalIgnoreCase); - } + public static bool IsHttpGetRequest( +#if ASPMVCCORE + this HttpRequest request +#elif ASPMVC + this HttpRequestBase request +#endif + ) + { + +#if ASPMVCCORE + return "GET".Equals(request.Method, StringComparison.OrdinalIgnoreCase); +#elif ASPMVC + return "GET".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase); +#endif + } /// /// Determines whether the HTTP method is POST. /// /// The request. /// - public static bool IsHttpPostRequest(this HttpRequest request) - { - return "POST".Equals(request.Method, StringComparison.OrdinalIgnoreCase); - } + public static bool IsHttpPostRequest( +#if ASPMVCCORE + this HttpRequest request +#elif ASPMVC + this HttpRequestBase request +#endif + ) + { + +#if ASPMVCCORE + return "POST".Equals(request.Method, StringComparison.OrdinalIgnoreCase); +#elif ASPMVC + return "POST".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase); +#endif + } /// /// Determines whether the HTTP method is DELETE. /// /// The request. /// - public static bool IsHttpDeleteRequest(this HttpRequest request) - { - return "DELETE".Equals(request.Method, StringComparison.OrdinalIgnoreCase); - } + public static bool IsHttpDeleteRequest( +#if ASPMVCCORE + this HttpRequest request +#elif ASPMVC + this HttpRequestBase request +#endif + ) + { + +#if ASPMVCCORE + return "DELETE".Equals(request.Method, StringComparison.OrdinalIgnoreCase); +#elif ASPMVC + return "DELETE".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase); +#endif + } /// /// Determines whether the HTTP method is PUT. /// /// The request. /// - public static bool IsHttpPutRequest(this HttpRequest request) - { - return "PUT".Equals(request.Method, StringComparison.OrdinalIgnoreCase); - } + public static bool IsHttpPutRequest( +#if ASPMVCCORE + this HttpRequest request +#elif ASPMVC + this HttpRequestBase request +#endif + ) + { + +#if ASPMVCCORE + return "PUT".Equals(request.Method, StringComparison.OrdinalIgnoreCase); +#elif ASPMVC + return "PUT".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase); +#endif + } /// /// Determines whether the HTTP method is HEAD. /// /// The request. /// - public static bool IsHttpHeadRequest(this HttpRequest request) - { - return "HEAD".Equals(request.Method, StringComparison.OrdinalIgnoreCase); - } + public static bool IsHttpHeadRequest( +#if ASPMVCCORE + this HttpRequest request +#elif ASPMVC + this HttpRequestBase request +#endif + ) + { + +#if ASPMVCCORE + return "HEAD".Equals(request.Method, StringComparison.OrdinalIgnoreCase); +#elif ASPMVC + return "HEAD".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase); +#endif + } /// /// Determines whether the specified URL is local to the request's host. @@ -106,8 +181,14 @@ public static bool IsHttpHeadRequest(this HttpRequest request) /// The request. /// The URL. /// - public static bool IsUrlLocalToHost(this HttpRequest request, string url) - { + public static bool IsUrlLocalToHost( +#if ASPMVCCORE + this HttpRequest request, +#elif ASPMVC + this HttpRequestBase request, +#endif + string url) + { return IsUrlLocalToHost(url); } @@ -127,13 +208,24 @@ private static bool IsUrlLocalToHost(string url) /// The request. /// true if the first accept type is JSON; otherwise, false /// request - public static bool PrefersJson(this HttpRequest request) - { + public static bool PrefersJson( +#if ASPMVCCORE + this HttpRequest request +#elif ASPMVC + this HttpRequestBase request +#endif + ) + { if (request == null) throw new ArgumentNullException("request"); - return PrefersJson(request.Headers["Accept"]); - } + +#if ASPMVCCORE + return PrefersJson(request.Headers["Accept"]); +#elif ASPMVC + return PrefersJson(request.AcceptTypes); +#endif + } private static bool PrefersJson(string[] acceptTypes) { diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkTagBuilderExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkTagBuilderExtensions.cs index eddb62f..8b45ade 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkTagBuilderExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkTagBuilderExtensions.cs @@ -16,31 +16,42 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Html; - using Microsoft.AspNetCore.Mvc.Rendering; +#if ASPMVCCORE + using Microsoft.AspNetCore.Html; + using Microsoft.AspNetCore.Mvc.Rendering; + using System.Text.Encodings.Web; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using System; using System.Collections.Generic; using System.Linq; using System.Text; - using System.Text.Encodings.Web; /// /// Extension methods for the class. /// public static class SrkTagBuilderExtensions { -/* + +#if ASPMVC /// /// To the MVC HTML string. /// /// The tag builder. /// The render mode. /// - public static HtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode) - { - return new HtmlString(tagBuilder.ToString(renderMode)); - } -*/ + public static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode) + { + return new MvcHtmlString(tagBuilder.ToString(renderMode)); + } +#endif + +#if ASPMVCCORE public static HtmlString ToHtmlString(this TagBuilder tag) { if (tag == null) @@ -51,6 +62,7 @@ public static HtmlString ToHtmlString(this TagBuilder tag) using var writer = new StringWriter(); tag.WriteTo(writer, HtmlEncoder.Default); return new HtmlString(writer.ToString()); - } + } +#endif } } diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkTempDataDictionaryExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkTempDataDictionaryExtensions.cs index 340f196..60fb905 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkTempDataDictionaryExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkTempDataDictionaryExtensions.cs @@ -16,7 +16,15 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Mvc.ViewFeatures; +#if ASPMVCCORE + using Microsoft.AspNetCore.Mvc.ViewFeatures; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using SrkToolkit.Web.Models; using System.Collections.Generic; @@ -31,8 +39,14 @@ public static class SrkTempDataDictionaryExtensions /// The temp data. /// The error message. /// indicates the message contains HTML markup - public static void AddError(this ITempDataDictionary tempData, string errorMessage, bool isMarkup = false) - { + public static void AddError( +#if ASPMVC + this TempDataDictionary tempData, +#elif ASPMVCCORE + this ITempDataDictionary tempData, +#endif + string errorMessage, bool isMarkup = false) + { var message = new TempMessage(TempMessageKind.Error, errorMessage, isMarkup); AddMessage(tempData, message); @@ -44,8 +58,14 @@ public static void AddError(this ITempDataDictionary tempData, string errorMessa /// The temp data. /// The warning message. /// indicates the message contains HTML markup - public static void AddWarning(this ITempDataDictionary tempData, string warningMessage, bool isMarkup = false) - { + public static void AddWarning( +#if ASPMVC + this TempDataDictionary tempData, +#elif ASPMVCCORE + this ITempDataDictionary tempData, +#endif + string warningMessage, bool isMarkup = false) + { var message = new TempMessage(TempMessageKind.Warning, warningMessage, isMarkup); AddMessage(tempData, message); @@ -57,8 +77,14 @@ public static void AddWarning(this ITempDataDictionary tempData, string warningM /// The temp data. /// The info message. /// indicates the message contains HTML markup - public static void AddInfo(this ITempDataDictionary tempData, string infoMessage, bool isMarkup = false) - { + public static void AddInfo( +#if ASPMVC + this TempDataDictionary tempData, +#elif ASPMVCCORE + this ITempDataDictionary tempData, +#endif + string infoMessage, bool isMarkup = false) + { var message = new TempMessage(TempMessageKind.Information, infoMessage, isMarkup); AddMessage(tempData, message); @@ -70,8 +96,14 @@ public static void AddInfo(this ITempDataDictionary tempData, string infoMessage /// The temp data. /// The info message. /// indicates the message contains HTML markup - public static void AddConfirmation(this ITempDataDictionary tempData, string message, bool isMarkup = false) - { + public static void AddConfirmation( +#if ASPMVC + this TempDataDictionary tempData, +#elif ASPMVCCORE + this ITempDataDictionary tempData, +#endif + string message, bool isMarkup = false) + { var msg = new TempMessage(TempMessageKind.Confirmation, message, isMarkup); AddMessage(tempData, msg); @@ -82,8 +114,14 @@ public static void AddConfirmation(this ITempDataDictionary tempData, string mes /// /// The temp data. /// - public static IList GetAll(this ITempDataDictionary tempData) - { + public static IList GetAll( +#if ASPMVC + this TempDataDictionary tempData +#elif ASPMVCCORE + this ITempDataDictionary tempData +#endif + ) + { var list = new List(); if (tempData.ContainsKey(TempMessage.TempDataKey)) @@ -96,8 +134,14 @@ public static IList GetAll(this ITempDataDictionary tempData) return list; } - private static void AddMessage(ITempDataDictionary tempData, TempMessage message) - { + private static void AddMessage( +#if ASPMVC + this TempDataDictionary tempData, +#elif ASPMVCCORE + this ITempDataDictionary tempData, +#endif + TempMessage message) + { IList list = null; if (tempData.ContainsKey(TempMessage.TempDataKey)) diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkToolkit.Web.AspNetCore2.csproj b/Sources/SrkToolkit.Web.AspNetCore2/SrkToolkit.Web.AspNetCore2.csproj index b9a2fa4..955b586 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkToolkit.Web.AspNetCore2.csproj +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkToolkit.Web.AspNetCore2.csproj @@ -3,7 +3,7 @@ netstandard2.0 enable - default + 10 SrkToolkit.Web true 2.0.147-preview2 @@ -91,7 +91,6 @@ - @@ -124,10 +123,6 @@ - - - - diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkUrlHelperExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkUrlHelperExtensions.cs index 090cc21..df8166b 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkUrlHelperExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkUrlHelperExtensions.cs @@ -16,8 +16,17 @@ namespace SrkToolkit.Web { +#if ASPMVCCORE + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Routing; + using Microsoft.AspNetCore.Mvc.Routing; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using System; using System.Collections.Generic; using System.Linq; @@ -102,8 +111,14 @@ public static Uri ResetQueryString(this Uri uri, params string[] keysAndValues) /// the modified URL /// /// keysAndValues must be contain pairs of key and value;keysAndValues - public static string ResetQueryString(this IUrlHelper helper, string url, params string[] keysAndValues) - { + public static string ResetQueryString( +#if ASPMVC + this UrlHelper helper, +#elif ASPMVCCORE + this IUrlHelper helper, +#endif + string url, params string[] keysAndValues) + { return SetQueryString(url, true, keysAndValues); } @@ -144,8 +159,14 @@ public static Uri SetQueryString(this Uri uri, params string[] keysAndValues) /// the modified URL /// /// keysAndValues must be contain pairs of key and value;keysAndValues - public static string SetQueryString(this IUrlHelper helper, string url, params string[] keysAndValues) - { + public static string SetQueryString( +#if ASPMVC + this UrlHelper helper, +#elif ASPMVCCORE + this IUrlHelper helper, +#endif + string url, params string[] keysAndValues) + { return SetQueryString(url, keysAndValues); } diff --git a/Sources/SrkToolkit.Web.AspNetCore2/SrkViewExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/SrkViewExtensions.cs index 1e8075c..950c4d6 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/SrkViewExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/SrkViewExtensions.cs @@ -16,7 +16,17 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Mvc.Razor; +#if ASPMVCCORE + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Mvc; + using Microsoft.AspNetCore.Mvc.Razor; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using SrkToolkit.Web.Models; using System; using System.Collections.Generic; @@ -33,8 +43,14 @@ public static class SrkViewExtensions ///
/// /// - public static IList TempMessages(this IRazorPage view) - { + public static IList TempMessages( +#if ASPMVC + this WebViewPage view +#elif ASPMVCCORE + this IRazorPage view +#endif + ) + { if (view == null) throw new ArgumentNullException(nameof(view)); diff --git a/Sources/SrkToolkit.Web.AspNetCore2/WebDependencies.cs b/Sources/SrkToolkit.Web.AspNetCore2/WebDependencies.cs index 5d1b28c..97a1895 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/WebDependencies.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/WebDependencies.cs @@ -16,21 +16,33 @@ namespace SrkToolkit.Web { - using Microsoft.AspNetCore.Html; +#if ASPMVCCORE + using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc.Rendering; - using System; - using System.Collections.Generic; + using Microsoft.AspNetCore.Mvc.Rendering; + using System.Text.Encodings.Web; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; + using System.Web.Hosting; +#endif + + using System; + using System.Collections.Generic; + using System.IO; using System.Linq; using System.Text; - using System.Text.Encodings.Web; /// /// Manages web dependencies such as scripts and styles. /// public class WebDependencies { +#if ASPMVCCORE private readonly PathString requestPathBase; +#endif protected Dictionary> includes; /// @@ -40,6 +52,7 @@ public WebDependencies() { } +#if ASPMVCCORE public WebDependencies(PathString requestPathBase) { this.requestPathBase = requestPathBase; @@ -50,6 +63,13 @@ protected string ApplicationVirtualPath get { return this.requestPathBase.HasValue ? this.requestPathBase.ToString() : "/"; } ////set { this.requestPathBase = new PathString(value); } } +#endif +#if ASPMVC + protected string ApplicationVirtualPath + { + get { return HostingEnvironment.ApplicationVirtualPath; } + } +#endif /// /// Renders the specified dependency. @@ -70,10 +90,18 @@ public HtmlString Render(WebDependency value) RenderDependency(value.Files[i], sb); } - return new HtmlString(sb.ToString()); +#if ASPMVCCORE + return new HtmlString(sb.ToString()); +#elif ASPMVC + return MvcHtmlString.Create(sb.ToString()); +#endif } - return HtmlString.Empty; +#if ASPMVCCORE + return HtmlString.Empty; +#elif ASPMVC + return MvcHtmlString.Empty; +#endif } /// @@ -200,8 +228,12 @@ protected void RenderDependency(WebDependencyFile value, StringWriter sb) tag.MergeAttributes(value.Attributes); } +#if ASPMVCCORE tag.WriteTo(sb, HtmlEncoder.Default); sb.WriteLine(); +#elif ASPMVC + sb.WriteLine(tag.ToString(TagRenderMode.Normal)); +#endif break; case WebDependencyFileType.Css: @@ -229,9 +261,14 @@ protected void RenderDependency(WebDependencyFile value, StringWriter sb) tag.MergeAttributes(value.Attributes); } +#if ASPMVCCORE tag.TagRenderMode = TagRenderMode.SelfClosing; tag.WriteTo(sb, HtmlEncoder.Default); sb.WriteLine(); +#elif ASPMVC + sb.WriteLine(tag.ToString(TagRenderMode.SelfClosing)); +#endif + sb.WriteLine(); break; default: diff --git a/Sources/SrkToolkit.Web.AspNetCore2/WebDependenciesExtensions.cs b/Sources/SrkToolkit.Web.AspNetCore2/WebDependenciesExtensions.cs index 76bcfac..35a2ffd 100644 --- a/Sources/SrkToolkit.Web.AspNetCore2/WebDependenciesExtensions.cs +++ b/Sources/SrkToolkit.Web.AspNetCore2/WebDependenciesExtensions.cs @@ -16,8 +16,16 @@ namespace SrkToolkit.Web { +#if ASPMVCCORE using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Razor; +#endif + +#if ASPMVC + using System.Web; + using System.Web.Mvc; +#endif + using System; using System.Collections.Generic; using System.Linq; @@ -34,7 +42,13 @@ public static class WebDependenciesExtensions /// The view. /// /// view - public static WebDependencies WebDependencies(this IRazorPage view) + public static WebDependencies WebDependencies( +#if ASPMVC + this WebViewPage view +#elif ASPMVCCORE + this IRazorPage view +#endif + ) { if (view == null) throw new ArgumentNullException("view"); @@ -47,7 +61,11 @@ public static WebDependencies WebDependencies(this IRazorPage view) if (obj == null) { +#if ASPMVC + obj = new WebDependencies(); +#elif ASPMVCCORE obj = new WebDependencies(view.ViewContext.HttpContext.Request.PathBase); +#endif view.ViewContext.ViewData["WebDependencies"] = obj; if (view.ViewContext.HttpContext != null) view.ViewContext.HttpContext.Items["WebDependencies"] = obj; @@ -75,7 +93,11 @@ public static WebDependencies WebDependencies(this Controller controller) if (obj == null) { +#if ASPMVC + obj = new WebDependencies(); +#elif ASPMVCCORE obj = new WebDependencies(controller.Request.PathBase); +#endif controller.ViewData["WebDependencies"] = obj; if (controller.HttpContext != null) controller.HttpContext.Items["WebDependencies"] = obj;