diff --git a/Settings.StyleCop b/Settings.StyleCop index bb722e022f..7b8130298c 100644 --- a/Settings.StyleCop +++ b/Settings.StyleCop @@ -12,6 +12,11 @@ + + + False + + False @@ -22,6 +27,11 @@ False + + + False + + @@ -274,6 +284,11 @@ False + + + False + + False @@ -384,11 +399,21 @@ False + + + False + + False + + + False + + @@ -399,7 +424,7 @@ False - + diff --git a/src/Microsoft.AspNet.Mvc.Common/TypeExtensions.cs b/src/Microsoft.AspNet.Mvc.Common/TypeExtensions.cs index 2a8daaef8f..062c7b0ef1 100644 --- a/src/Microsoft.AspNet.Mvc.Common/TypeExtensions.cs +++ b/src/Microsoft.AspNet.Mvc.Common/TypeExtensions.cs @@ -19,7 +19,7 @@ namespace Microsoft.AspNet.Mvc return false; } - for (int idx = 0; idx < t1.Length; ++idx) + for (var idx = 0; idx < t1.Length; ++idx) { if (t1[idx] != t2[idx]) { diff --git a/src/Microsoft.AspNet.Mvc.Core/ActionResults/FilePathResult.cs b/src/Microsoft.AspNet.Mvc.Core/ActionResults/FilePathResult.cs index 001f1e23e3..9eb2b9610f 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ActionResults/FilePathResult.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ActionResults/FilePathResult.cs @@ -119,7 +119,6 @@ namespace Microsoft.AspNet.Mvc throw new FileNotFoundException(message, path); } - // Internal for unit testing purposes only /// /// Creates a normalized representation of the given . The default /// implementation doesn't support files with '\' in the file name and treats the '\' as @@ -128,6 +127,7 @@ namespace Microsoft.AspNet.Mvc /// /// The path to normalize. /// The normalized path. + // Internal for unit testing purposes only protected internal virtual string NormalizePath([NotNull] string path) { // Unix systems support '\' as part of the file name. So '\' is not @@ -153,13 +153,13 @@ namespace Microsoft.AspNet.Mvc return path.Replace('\\', '/'); } - // Internal for unit testing purposes only /// /// Determines if the provided path is absolute or relative. The default implementation considers /// paths starting with '/' to be relative. /// /// The path to examine. /// True if the path is absolute. + // Internal for unit testing purposes only protected internal virtual bool IsPathRooted([NotNull] string path) { // We consider paths to be rooted if they start with '<>:' and do diff --git a/src/Microsoft.AspNet.Mvc.Core/ActionResults/FileResult.cs b/src/Microsoft.AspNet.Mvc.Core/ActionResults/FileResult.cs index 1b7fba8f97..7039145eb7 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ActionResults/FileResult.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ActionResults/FileResult.cs @@ -84,7 +84,7 @@ namespace Microsoft.AspNet.Mvc { builder.Append('%'); - int i = b; + var i = b; AddHexDigitToStringBuilder(i >> 4, builder); AddHexDigitToStringBuilder(i % 16, builder); } diff --git a/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryToken.cs b/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryToken.cs index 3affb8fac6..b16dc900bd 100644 --- a/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryToken.cs +++ b/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryToken.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.AspNet.Mvc { internal sealed class AntiForgeryToken diff --git a/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryTokenStore.cs b/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryTokenStore.cs index 0ab6401f88..d9576fe4dc 100644 --- a/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryTokenStore.cs +++ b/src/Microsoft.AspNet.Mvc.Core/AntiForgery/AntiForgeryTokenStore.cs @@ -23,7 +23,8 @@ namespace Microsoft.AspNet.Mvc public AntiForgeryToken GetCookieToken(HttpContext httpContext) { - var contextAccessor = httpContext.RequestServices.GetRequiredService>(); + var contextAccessor = + httpContext.RequestServices.GetRequiredService>(); if (contextAccessor.Value != null) { return contextAccessor.Value.CookieToken; @@ -56,7 +57,8 @@ namespace Microsoft.AspNet.Mvc { // Add the cookie to the request based context. // This is useful if the cookie needs to be reloaded in the context of the same request. - var contextAccessor = httpContext.RequestServices.GetRequiredService>(); + var contextAccessor = + httpContext.RequestServices.GetRequiredService>(); Debug.Assert(contextAccessor.Value == null, "AntiForgeryContext should be set only once per request."); contextAccessor.SetValue(new AntiForgeryContext() { CookieToken = token }); diff --git a/src/Microsoft.AspNet.Mvc.Core/ApplicationModels/DefaultActionModelBuilder.cs b/src/Microsoft.AspNet.Mvc.Core/ApplicationModels/DefaultActionModelBuilder.cs index 41c584a2b3..76af6f93f3 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ApplicationModels/DefaultActionModelBuilder.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ApplicationModels/DefaultActionModelBuilder.cs @@ -233,7 +233,6 @@ namespace Microsoft.AspNet.Mvc.ApplicationModels typeInfo.GetRuntimeInterfaceMap(typeof(IDisposable)).TargetMethods[0] == methodInfo); } - /// /// Creates an for the given . /// diff --git a/src/Microsoft.AspNet.Mvc.Core/Controller.cs b/src/Microsoft.AspNet.Mvc.Core/Controller.cs index 53bb774895..c5f8b85b62 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Controller.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Controller.cs @@ -67,9 +67,8 @@ namespace Microsoft.AspNet.Mvc { if (_viewEngine == null) { - _viewEngine = ActionContext?. - HttpContext?. - RequestServices.GetRequiredService(); + _viewEngine = + ActionContext?.HttpContext?.RequestServices.GetRequiredService(); } return _viewEngine; @@ -797,7 +796,7 @@ namespace Microsoft.AspNet.Mvc } /// - /// Updates the specified instance using values from the controller's current + /// Updates the specified instance using values from the controller's current /// . /// /// The type of the model object. @@ -811,7 +810,7 @@ namespace Microsoft.AspNet.Mvc } /// - /// Updates the specified instance using values from the controller's current + /// Updates the specified instance using values from the controller's current /// and a . /// /// The type of the model object. @@ -826,7 +825,7 @@ namespace Microsoft.AspNet.Mvc { if (BindingContextProvider == null) { - var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), + var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), GetType().FullName); throw new InvalidOperationException(message); } @@ -836,7 +835,7 @@ namespace Microsoft.AspNet.Mvc } /// - /// Updates the specified instance using the and a + /// Updates the specified instance using the and a /// . /// /// The type of the model object. @@ -853,7 +852,7 @@ namespace Microsoft.AspNet.Mvc { if (BindingContextProvider == null) { - var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), + var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), GetType().FullName); throw new InvalidOperationException(message); } @@ -870,14 +869,14 @@ namespace Microsoft.AspNet.Mvc } /// - /// Updates the specified instance using values from the controller's current + /// Updates the specified instance using values from the controller's current /// and a . /// /// The type of the model object. /// The model instance to update. /// The prefix to use when looking up values in the current . /// - /// (s) which represent top-level properties + /// (s) which represent top-level properties /// which need to be included for the current model. /// A that on completion returns true if the update is successful [NonAction] @@ -907,7 +906,7 @@ namespace Microsoft.AspNet.Mvc } /// - /// Updates the specified instance using values from the controller's current + /// Updates the specified instance using values from the controller's current /// and a . /// /// The type of the model object. @@ -925,7 +924,7 @@ namespace Microsoft.AspNet.Mvc { if (BindingContextProvider == null) { - var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), + var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), GetType().FullName); throw new InvalidOperationException(message); } @@ -943,7 +942,7 @@ namespace Microsoft.AspNet.Mvc } /// - /// Updates the specified instance using the and a + /// Updates the specified instance using the and a /// . /// /// The type of the model object. @@ -951,7 +950,7 @@ namespace Microsoft.AspNet.Mvc /// The prefix to use when looking up values in the /// /// The used for looking up values. - /// (s) which represent top-level properties + /// (s) which represent top-level properties /// which need to be included for the current model. /// A that on completion returns true if the update is successful [NonAction] @@ -964,7 +963,7 @@ namespace Microsoft.AspNet.Mvc { if (BindingContextProvider == null) { - var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), + var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), GetType().FullName); throw new InvalidOperationException(message); } @@ -982,7 +981,7 @@ namespace Microsoft.AspNet.Mvc } /// - /// Updates the specified instance using the and a + /// Updates the specified instance using the and a /// . /// /// The type of the model object. @@ -1002,7 +1001,7 @@ namespace Microsoft.AspNet.Mvc { if (BindingContextProvider == null) { - var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), + var message = Resources.FormatPropertyOfTypeCannotBeNull(nameof(BindingContextProvider), GetType().FullName); throw new InvalidOperationException(message); } diff --git a/src/Microsoft.AspNet.Mvc.Core/ControllerActionDescriptorProvider.cs b/src/Microsoft.AspNet.Mvc.Core/ControllerActionDescriptorProvider.cs index 347591e91b..cbc7cf575d 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ControllerActionDescriptorProvider.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ControllerActionDescriptorProvider.cs @@ -5,8 +5,8 @@ using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Mvc.ApplicationModels; -using Microsoft.AspNet.Mvc.Logging; using Microsoft.AspNet.Mvc.Filters; +using Microsoft.AspNet.Mvc.Logging; using Microsoft.Framework.Logging; using Microsoft.Framework.OptionsModel; diff --git a/src/Microsoft.AspNet.Mvc.Core/DefaultAssemblyProvider.cs b/src/Microsoft.AspNet.Mvc.Core/DefaultAssemblyProvider.cs index 1a42fccba1..aa7f43835e 100644 --- a/src/Microsoft.AspNet.Mvc.Core/DefaultAssemblyProvider.cs +++ b/src/Microsoft.AspNet.Mvc.Core/DefaultAssemblyProvider.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNet.Mvc public class DefaultAssemblyProvider : IAssemblyProvider { /// - /// Gets the set of assembly names that are used as root for discovery of + /// Gets the set of assembly names that are used as root for discovery of /// MVC controllers, view components and views. /// protected virtual HashSet ReferenceAssemblies { get; } = new HashSet(StringComparer.Ordinal) @@ -44,7 +44,7 @@ namespace Microsoft.AspNet.Mvc /// /// Returns a list of libraries that references the assemblies in . - /// By default it returns all assemblies that reference any of the primary MVC assemblies + /// By default it returns all assemblies that reference any of the primary MVC assemblies /// while ignoring MVC assemblies. /// /// A set of . diff --git a/src/Microsoft.AspNet.Mvc.Core/DefaultControllerActionArgumentBinder.cs b/src/Microsoft.AspNet.Mvc.Core/DefaultControllerActionArgumentBinder.cs index e1b3fcb77e..8dbf3e9cbb 100644 --- a/src/Microsoft.AspNet.Mvc.Core/DefaultControllerActionArgumentBinder.cs +++ b/src/Microsoft.AspNet.Mvc.Core/DefaultControllerActionArgumentBinder.cs @@ -87,7 +87,8 @@ namespace Microsoft.AspNet.Mvc foreach (var parameter in parameterMetadata) { var parameterType = parameter.ModelType; - var modelBindingContext = GetModelBindingContext(parameter, actionBindingContext, operationBindingContext); + var modelBindingContext = + GetModelBindingContext(parameter, actionBindingContext, operationBindingContext); if (await actionBindingContext.ModelBinder.BindModelAsync(modelBindingContext)) { arguments[parameter.PropertyName] = modelBindingContext.Model; diff --git a/src/Microsoft.AspNet.Mvc.Core/DefaultPropertyBindingPredicateProvider.cs b/src/Microsoft.AspNet.Mvc.Core/DefaultPropertyBindingPredicateProvider.cs index 1ef3dd7b05..a986fd453b 100644 --- a/src/Microsoft.AspNet.Mvc.Core/DefaultPropertyBindingPredicateProvider.cs +++ b/src/Microsoft.AspNet.Mvc.Core/DefaultPropertyBindingPredicateProvider.cs @@ -17,7 +17,8 @@ namespace Microsoft.AspNet.Mvc public class DefaultPropertyBindingPredicateProvider : IPropertyBindingPredicateProvider where TModel : class { - private static readonly Func _defaultFilter = (context, propertyName) => true; + private static readonly Func _defaultFilter = + (context, propertyName) => true; /// /// The prefix which is used while generating the property filter. @@ -57,7 +58,8 @@ namespace Microsoft.AspNet.Mvc } } - private Func GetPredicateFromExpression(IEnumerable>> includeExpressions) + private Func GetPredicateFromExpression( + IEnumerable>> includeExpressions) { var expression = ModelBindingHelper.GetIncludePredicateExpression(Prefix, includeExpressions.ToArray()); return expression.Compile(); diff --git a/src/Microsoft.AspNet.Mvc.Core/Description/DefaultApiDescriptionProvider.cs b/src/Microsoft.AspNet.Mvc.Core/Description/DefaultApiDescriptionProvider.cs index 591737d166..48b2f1016f 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Description/DefaultApiDescriptionProvider.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Description/DefaultApiDescriptionProvider.cs @@ -45,7 +45,6 @@ namespace Microsoft.AspNet.Mvc.Description get { return DefaultOrder.DefaultFrameworkSortOrder; } } - /// public void Invoke(ApiDescriptionProviderContext context, Action callNext) { @@ -157,7 +156,8 @@ namespace Microsoft.AspNet.Mvc.Description // Process parameters that only appear on the path template if any. foreach (var templateParameter in templateParameters) { - var parameterDescription = GetParameter(parameterDescriptor: null, templateParameter: templateParameter); + var parameterDescription = + GetParameter(parameterDescriptor: null, templateParameter: templateParameter); apiDescription.ParameterDescriptions.Add(parameterDescription); } } diff --git a/src/Microsoft.AspNet.Mvc.Core/Filters/IAuthorizationFilter.cs b/src/Microsoft.AspNet.Mvc.Core/Filters/IAuthorizationFilter.cs index 9b1cbccd50..af929411b5 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Filters/IAuthorizationFilter.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Filters/IAuthorizationFilter.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.AspNet.Mvc { public interface IAuthorizationFilter : IFilter diff --git a/src/Microsoft.AspNet.Mvc.Core/Filters/IExceptionFilter.cs b/src/Microsoft.AspNet.Mvc.Core/Filters/IExceptionFilter.cs index 8d6bbf41e9..d9cc2a1234 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Filters/IExceptionFilter.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Filters/IExceptionFilter.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.AspNet.Mvc { public interface IExceptionFilter : IFilter diff --git a/src/Microsoft.AspNet.Mvc.Core/Formatters/IInputFormatterSelector.cs b/src/Microsoft.AspNet.Mvc.Core/Formatters/IInputFormatterSelector.cs index 81dc2095d2..982a6d2c0a 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Formatters/IInputFormatterSelector.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Formatters/IInputFormatterSelector.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.AspNet.Mvc { public interface IInputFormatterSelector diff --git a/src/Microsoft.AspNet.Mvc.Core/HttpMethodAttribute.cs b/src/Microsoft.AspNet.Mvc.Core/HttpMethodAttribute.cs index 64f5913186..429a536cda 100644 --- a/src/Microsoft.AspNet.Mvc.Core/HttpMethodAttribute.cs +++ b/src/Microsoft.AspNet.Mvc.Core/HttpMethodAttribute.cs @@ -13,8 +13,8 @@ namespace Microsoft.AspNet.Mvc [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public abstract class HttpMethodAttribute : Attribute, IActionHttpMethodProvider, IRouteTemplateProvider { - private int? _order; private readonly IEnumerable _httpMethods; + private int? _order; /// /// Creates a new with the given diff --git a/src/Microsoft.AspNet.Mvc.Core/Logging/ActionConstraintValues.cs b/src/Microsoft.AspNet.Mvc.Core/Logging/ActionConstraintValues.cs index 9b68e6729b..af798e4519 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Logging/ActionConstraintValues.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Logging/ActionConstraintValues.cs @@ -32,7 +32,8 @@ namespace Microsoft.AspNet.Mvc.Logging public Type ActionConstraintMetadataType { get; } /// - /// The constraint order if this is an . See . + /// The constraint order if this is an . See + /// . /// public int Order { get; } diff --git a/src/Microsoft.AspNet.Mvc.Core/Logging/ActionDescriptorValues.cs b/src/Microsoft.AspNet.Mvc.Core/Logging/ActionDescriptorValues.cs index 0e7c488ea2..8dc5de8420 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Logging/ActionDescriptorValues.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Logging/ActionDescriptorValues.cs @@ -25,7 +25,8 @@ namespace Microsoft.AspNet.Mvc.Logging AttributeRouteInfo = new AttributeRouteInfoValues(inner.AttributeRouteInfo); RouteValueDefaults = inner.RouteValueDefaults.ToDictionary(i => i.Key, i => i.Value.ToString()); ActionConstraints = inner.ActionConstraints?.Select(a => new ActionConstraintValues(a))?.ToList(); - HttpMethods = inner.ActionConstraints?.OfType().SelectMany(c => c.HttpMethods).ToList(); + HttpMethods = + inner.ActionConstraints?.OfType().SelectMany(c => c.HttpMethods).ToList(); Properties = inner.Properties.ToDictionary(i => i.Key.ToString(), i => i.Value.GetType()); var controllerActionDescriptor = inner as ControllerActionDescriptor; if (controllerActionDescriptor != null) diff --git a/src/Microsoft.AspNet.Mvc.Core/Logging/AttributeRouteModelValues.cs b/src/Microsoft.AspNet.Mvc.Core/Logging/AttributeRouteModelValues.cs index 7a5167b4f7..ba9b0e42d9 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Logging/AttributeRouteModelValues.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Logging/AttributeRouteModelValues.cs @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using Microsoft.Framework.Logging; using Microsoft.AspNet.Mvc.ApplicationModels; +using Microsoft.Framework.Logging; namespace Microsoft.AspNet.Mvc.Logging { diff --git a/src/Microsoft.AspNet.Mvc.Core/Logging/ControllerModelValues.cs b/src/Microsoft.AspNet.Mvc.Core/Logging/ControllerModelValues.cs index 3ca2d23014..3d8c909b0e 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Logging/ControllerModelValues.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Logging/ControllerModelValues.cs @@ -4,8 +4,8 @@ using System; using System.Collections.Generic; using System.Linq; -using Microsoft.Framework.Logging; using Microsoft.AspNet.Mvc.ApplicationModels; +using Microsoft.Framework.Logging; namespace Microsoft.AspNet.Mvc.Logging { diff --git a/src/Microsoft.AspNet.Mvc.Core/Logging/FilterValues.cs b/src/Microsoft.AspNet.Mvc.Core/Logging/FilterValues.cs index 60151950cb..2e6fa23978 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Logging/FilterValues.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Logging/FilterValues.cs @@ -1,4 +1,7 @@ -using System; +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; using System.Collections.Generic; using System.Linq; using Microsoft.Framework.Logging; diff --git a/src/Microsoft.AspNet.Mvc.Core/ModelBinders/BodyModelBinder.cs b/src/Microsoft.AspNet.Mvc.Core/ModelBinders/BodyModelBinder.cs index f8e89ecee8..61f29da8d9 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ModelBinders/BodyModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ModelBinders/BodyModelBinder.cs @@ -40,7 +40,7 @@ namespace Microsoft.AspNet.Mvc if (formatter == null) { var unsupportedContentType = Resources.FormatUnsupportedContentType( - bindingContext.OperationBindingContext.HttpContext.Request.ContentType); + bindingContext.OperationBindingContext.HttpContext.Request.ContentType); bindingContext.ModelState.AddModelError(bindingContext.ModelName, unsupportedContentType); // Should always return true so that the model binding process ends here. diff --git a/src/Microsoft.AspNet.Mvc.Core/ParameterBinding/ModelBindingHelper.cs b/src/Microsoft.AspNet.Mvc.Core/ParameterBinding/ModelBindingHelper.cs index ae1965a9ca..19080e1c64 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ParameterBinding/ModelBindingHelper.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ParameterBinding/ModelBindingHelper.cs @@ -90,7 +90,7 @@ namespace Microsoft.AspNet.Mvc where TModel : class { var includeExpression = GetIncludePredicateExpression(prefix, includeExpressions); - Func predicate = includeExpression.Compile(); + var predicate = includeExpression.Compile(); return TryUpdateModelAsync( model, diff --git a/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/DefaultHtmlGenerator.cs b/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/DefaultHtmlGenerator.cs index 0c3f2754d1..b36898f2ee 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/DefaultHtmlGenerator.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/DefaultHtmlGenerator.cs @@ -432,7 +432,8 @@ namespace Microsoft.AspNet.Mvc.Rendering if (defaultValue != null) { - selectList = UpdateSelectListItemsWithDefaultValue(selectList, defaultValue, allowMultiple, out selectedValues); + selectList = + UpdateSelectListItemsWithDefaultValue(selectList, defaultValue, allowMultiple, out selectedValues); } else { @@ -606,7 +607,9 @@ namespace Microsoft.AspNet.Mvc.Rendering // Only the style of the span is changed according to the errors if message is null or empty. // Otherwise the content and style is handled by the client-side validation. - var className = (modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName; + var className = (modelError != null) ? + HtmlHelper.ValidationMessageCssClassName : + HtmlHelper.ValidationMessageValidCssClassName; tagBuilder.AddCssClass(className); if (!string.IsNullOrEmpty(message)) diff --git a/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/HtmlHelper.cs b/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/HtmlHelper.cs index 78f26f7633..f305184861 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/HtmlHelper.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/HtmlHelper.cs @@ -702,7 +702,6 @@ namespace Microsoft.AspNet.Mvc.Rendering return CreateForm(); } - protected virtual HtmlString GenerateHidden( ModelMetadata metadata, string name, diff --git a/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/TagBuilder.cs b/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/TagBuilder.cs index 71272a2b2e..33ee0f6e4f 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/TagBuilder.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Rendering/Html/TagBuilder.cs @@ -237,8 +237,8 @@ namespace Microsoft.AspNet.Mvc.Rendering case '-': case '_': case ':': - // Note '.' is valid according to the HTML 4.01 specification. Disallowed here to avoid confusion - // with CSS class selectors or when using jQuery. + // Note '.' is valid according to the HTML 4.01 specification. Disallowed here to avoid + // confusion with CSS class selectors or when using jQuery. return true; default: diff --git a/src/Microsoft.AspNet.Mvc.Core/Routing/AttributeRoute.cs b/src/Microsoft.AspNet.Mvc.Core/Routing/AttributeRoute.cs index 362d4c67f1..7ed95e37b1 100644 --- a/src/Microsoft.AspNet.Mvc.Core/Routing/AttributeRoute.cs +++ b/src/Microsoft.AspNet.Mvc.Core/Routing/AttributeRoute.cs @@ -20,12 +20,12 @@ namespace Microsoft.AspNet.Mvc.Routing public class AttributeRoute : IRouter { private readonly IRouter _next; + private readonly LinkGenerationDecisionTree _linkGenerationTree; private readonly TemplateRoute[] _matchingRoutes; private readonly IDictionary _namedEntries; private ILogger _logger; private ILogger _constraintLogger; - private readonly LinkGenerationDecisionTree _linkGenerationTree; /// /// Creates a new . diff --git a/src/Microsoft.AspNet.Mvc.Core/UrlHelper.cs b/src/Microsoft.AspNet.Mvc.Core/UrlHelper.cs index 66003c1a09..8dca748c38 100644 --- a/src/Microsoft.AspNet.Mvc.Core/UrlHelper.cs +++ b/src/Microsoft.AspNet.Mvc.Core/UrlHelper.cs @@ -22,7 +22,8 @@ namespace Microsoft.AspNet.Mvc private readonly IActionSelector _actionSelector; /// - /// Initializes a new instance of the class using the specified action context and action selector. + /// Initializes a new instance of the class using the specified action context and + /// action selector. /// /// The to access the action context /// of the current request. diff --git a/src/Microsoft.AspNet.Mvc.Core/ViewComponents/ContentViewComponentResult.cs b/src/Microsoft.AspNet.Mvc.Core/ViewComponents/ContentViewComponentResult.cs index 4ef89e3ce8..69dcc7fe12 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ViewComponents/ContentViewComponentResult.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ViewComponents/ContentViewComponentResult.cs @@ -13,10 +13,10 @@ namespace Microsoft.AspNet.Mvc /// /// always writes HTML encoded text from the /// property. - /// + /// /// When using , the provided content will be HTML /// encoded and stored in . - /// + /// /// To write pre-encoded conent, use . /// public class ContentViewComponentResult : IViewComponentResult diff --git a/src/Microsoft.AspNet.Mvc.Core/ViewContext.cs b/src/Microsoft.AspNet.Mvc.Core/ViewContext.cs index f1e398c4ee..031fe6047b 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ViewContext.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ViewContext.cs @@ -8,12 +8,11 @@ namespace Microsoft.AspNet.Mvc { public class ViewContext : ActionContext { - private DynamicViewData _viewBag; - // We need a default FormContext if the user uses html
instead of an MvcForm private readonly FormContext _defaultFormContext = new FormContext(); private FormContext _formContext; + private DynamicViewData _viewBag; public ViewContext( [NotNull] ActionContext actionContext, diff --git a/src/Microsoft.AspNet.Mvc.Core/ViewDataDictionaryOfT.cs b/src/Microsoft.AspNet.Mvc.Core/ViewDataDictionaryOfT.cs index a4c063f3dd..051d83b11c 100644 --- a/src/Microsoft.AspNet.Mvc.Core/ViewDataDictionaryOfT.cs +++ b/src/Microsoft.AspNet.Mvc.Core/ViewDataDictionaryOfT.cs @@ -7,7 +7,6 @@ namespace Microsoft.AspNet.Mvc { public class ViewDataDictionary : ViewDataDictionary { - // References may not show up due to ITypeActivator use in RazorPageActivator. /// /// Initializes a new instance of the class. /// @@ -15,6 +14,7 @@ namespace Microsoft.AspNet.Mvc /// For use when creating a for a new top-level scope. /// /// + // References may not show up due to ITypeActivator use in RazorPageActivator. public ViewDataDictionary( [NotNull] IModelMetadataProvider metadataProvider, [NotNull] ModelStateDictionary modelState) @@ -22,7 +22,6 @@ namespace Microsoft.AspNet.Mvc { } - // References may not show up due to ITypeActivator use in RazorPageActivator. /// /// Initializes a new instance of the class based in part on an /// existing instance. @@ -40,14 +39,12 @@ namespace Microsoft.AspNet.Mvc /// /// /// + // References may not show up due to ITypeActivator use in RazorPageActivator. public ViewDataDictionary([NotNull] ViewDataDictionary source) : base(source, declaredModelType: typeof(TModel)) { } - // Model parameter type is object to allow "model: null" calls even when TModel is a value type. A TModel - // parameter would likely require IEquatable type restrictions to pass expected null value to the base - // constructor. /// /// Initializes a new instance of the class based in part on an /// existing instance. This constructor is careful to avoid exceptions @@ -64,6 +61,9 @@ namespace Microsoft.AspNet.Mvc /// /// /// + // Model parameter type is object to allow "model: null" calls even when TModel is a value type. A TModel + // parameter would likely require IEquatable type restrictions to pass expected null value to the base + // constructor. public ViewDataDictionary([NotNull] ViewDataDictionary source, object model) : base(source, model, declaredModelType: typeof(TModel)) { diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/BindAttribute.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/BindAttribute.cs index 559d2a27a6..396d5a9b2a 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/BindAttribute.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/BindAttribute.cs @@ -14,7 +14,8 @@ namespace Microsoft.AspNet.Mvc [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public class BindAttribute : Attribute, IModelNameProvider, IPropertyBindingPredicateProvider { - private static readonly Func _defaultFilter = (context, propertyName) => true; + private static readonly Func _defaultFilter = + (context, propertyName) => true; private Func _predicateFromInclude; diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CollectionModelBinder.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CollectionModelBinder.cs index f64a0175e3..f2e6ff25d1 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CollectionModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CollectionModelBinder.cs @@ -47,7 +47,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding var rawValueArray = RawValueToObjectArray(rawValue); foreach (var rawValueElement in rawValueArray) { - var innerModelMetadata = + var innerModelMetadata = bindingContext.OperationBindingContext.MetadataProvider.GetMetadataForType(null, typeof(TElement)); var innerBindingContext = new ModelBindingContext(bindingContext, bindingContext.ModelName, @@ -101,7 +101,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding foreach (var indexName in indexNames) { var fullChildName = ModelBindingHelper.CreateIndexModelName(bindingContext.ModelName, indexName); - var childModelMetadata = + var childModelMetadata = bindingContext.OperationBindingContext.MetadataProvider.GetMetadataForType(null, typeof(TElement)); var childBindingContext = new ModelBindingContext(bindingContext, fullChildName, childModelMetadata); diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ComplexModelDtoModelBinder.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ComplexModelDtoModelBinder.cs index 8cfe74c323..3a133acbcb 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ComplexModelDtoModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ComplexModelDtoModelBinder.cs @@ -22,7 +22,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding var propertyModelName = ModelBindingHelper.CreatePropertyModelName(bindingContext.ModelName, propertyMetadata.PropertyName); - var propertyBindingContext = new ModelBindingContext(bindingContext, + var propertyBindingContext = new ModelBindingContext(bindingContext, propertyModelName, propertyMetadata); diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CompositeModelBinder.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CompositeModelBinder.cs index e94fd3a0b7..8d2ace61f4 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CompositeModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/CompositeModelBinder.cs @@ -80,16 +80,17 @@ namespace Microsoft.AspNet.Mvc.ModelBinding bindingContext.ModelName); } - var validationContext = new ModelValidationContext(bindingContext.OperationBindingContext.MetadataProvider, - bindingContext.OperationBindingContext.ValidatorProvider, - bindingContext.ModelState, - bindingContext.ModelMetadata, - containerMetadata: null); + var validationContext = new ModelValidationContext( + bindingContext.OperationBindingContext.MetadataProvider, + bindingContext.OperationBindingContext.ValidatorProvider, + bindingContext.ModelState, + bindingContext.ModelMetadata, + containerMetadata: null); newBindingContext.ValidationNode.Validate(validationContext, parentNode: null); } - bindingContext.OperationBindingContext.BodyBindingState = + bindingContext.OperationBindingContext.BodyBindingState = newBindingContext.OperationBindingContext.BodyBindingState; bindingContext.Model = newBindingContext.Model; return true; @@ -147,13 +148,14 @@ namespace Microsoft.AspNet.Mvc.ModelBinding var metadata = oldBindingContext.ModelMetadata.BinderMetadata as IValueProviderMetadata; if (metadata != null) { - // ValueProvider property might contain a filtered list of value providers. + // ValueProvider property might contain a filtered list of value providers. // While deciding to bind a particular property which is annotated with a IValueProviderMetadata, - // instead of refiltering an already filtered list, we need to filter value providers from a global list - // of all value providers. This is so that every artifact that is explicitly marked using an - // IValueProviderMetadata can restrict model binding to only use value providers which support this + // instead of refiltering an already filtered list, we need to filter value providers from a global + // list of all value providers. This is so that every artifact that is explicitly marked using an + // IValueProviderMetadata can restrict model binding to only use value providers which support this // IValueProviderMetadata. - var valueProvider = oldBindingContext.OperationBindingContext.ValueProvider as IMetadataAwareValueProvider; + var valueProvider = + oldBindingContext.OperationBindingContext.ValueProvider as IMetadataAwareValueProvider; if (valueProvider != null) { newBindingContext.ValueProvider = valueProvider.Filter(metadata); @@ -171,7 +173,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding var currentModelNeedsToReadBody = newIsFormatterBasedMetadataFound || newIsFormBasedMetadataFound; var oldState = oldBindingContext.OperationBindingContext.BodyBindingState; - // We need to throw if there are multiple models which can cause body to be read multiple times. + // We need to throw if there are multiple models which can cause body to be read multiple times. // Reading form data multiple times is ok since we cache form data. For the models marked to read using // formatters, multiple reads are not allowed. if (oldState == BodyBindingState.FormatterBased && currentModelNeedsToReadBody || @@ -179,7 +181,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding { throw new InvalidOperationException(Resources.MultipleBodyParametersOrPropertiesAreNotAllowed); } - + var state = oldBindingContext.OperationBindingContext.BodyBindingState; if (newIsFormatterBasedMetadataFound) { @@ -187,7 +189,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding } else if (newIsFormBasedMetadataFound && oldState != BodyBindingState.FormatterBased) { - // Only update the model binding state if we have not discovered formatter based state already. + // Only update the model binding state if we have not discovered formatter based state already. state = BodyBindingState.FormBased; } diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/GenericModelBinder.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/GenericModelBinder.cs index 51a02c69b5..178addd3d0 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/GenericModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/GenericModelBinder.cs @@ -30,7 +30,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding var binder = (IModelBinder)_activator.CreateInstance(_serviceProvider, binderType); await binder.BindModelAsync(bindingContext); - // Was able to resolve a binder type, hence we should tell the model binding system to return + // Was able to resolve a binder type, hence we should tell the model binding system to return // true so that none of the other model binders participate. return true; } diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ICompositeModelBinder.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ICompositeModelBinder.cs index 7ba9ad00c6..39e16fff9d 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ICompositeModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/ICompositeModelBinder.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.AspNet.Mvc.ModelBinding { /// diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/KeyValuePairModelBinder.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/KeyValuePairModelBinder.cs index 431cb3ef22..e04a17d282 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/KeyValuePairModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/KeyValuePairModelBinder.cs @@ -28,12 +28,12 @@ namespace Microsoft.AspNet.Mvc.ModelBinding internal async Task> TryBindStrongModel(ModelBindingContext parentBindingContext, string propertyName) { - var propertyModelMetadata = + var propertyModelMetadata = parentBindingContext.OperationBindingContext.MetadataProvider.GetMetadataForType(modelAccessor: null, modelType: typeof(TModel)); - var propertyModelName = + var propertyModelName = ModelBindingHelper.CreatePropertyModelName(parentBindingContext.ModelName, propertyName); - var propertyBindingContext = + var propertyBindingContext = new ModelBindingContext(parentBindingContext, propertyModelName, propertyModelMetadata); if (await propertyBindingContext.OperationBindingContext.ModelBinder.BindModelAsync(propertyBindingContext)) diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/MutableObjectModelBinder.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/MutableObjectModelBinder.cs index 359c50ff69..a23cfaf57c 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/MutableObjectModelBinder.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Binders/MutableObjectModelBinder.cs @@ -220,7 +220,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding var complexModelDtoMetadata = bindingContext.OperationBindingContext.MetadataProvider.GetMetadataForType(() => originalDto, typeof(ComplexModelDto)); - var dtoBindingContext = + var dtoBindingContext = new ModelBindingContext(bindingContext, bindingContext.ModelName, complexModelDtoMetadata); await bindingContext.OperationBindingContext.ModelBinder.BindModelAsync(dtoBindingContext); diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Metadata/IModelMetadataProvider.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Metadata/IModelMetadataProvider.cs index 648e0a02b1..866b885a63 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Metadata/IModelMetadataProvider.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Metadata/IModelMetadataProvider.cs @@ -11,7 +11,10 @@ namespace Microsoft.AspNet.Mvc.ModelBinding { IEnumerable GetMetadataForProperties(object container, [NotNull] Type containerType); - ModelMetadata GetMetadataForProperty(Func modelAccessor, [NotNull] Type containerType, [NotNull] string propertyName); + ModelMetadata GetMetadataForProperty( + Func modelAccessor, + [NotNull] Type containerType, + [NotNull] string propertyName); ModelMetadata GetMetadataForType(Func modelAccessor, [NotNull] Type modelType); diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/ModelBindingContext.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/ModelBindingContext.cs index 58042ebcac..b8448eb8ef 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/ModelBindingContext.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/ModelBindingContext.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Microsoft.AspNet.Http; namespace Microsoft.AspNet.Mvc.ModelBinding { @@ -13,7 +12,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding /// public class ModelBindingContext { - private static readonly Func + private static readonly Func _defaultPropertyFilter = (context, propertyName) => true; private string _modelName; @@ -53,7 +52,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding } /// - /// Represents the associated with this context. + /// Represents the associated with this context. /// public OperationBindingContext OperationBindingContext { get; set; } diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ClientModelValidationContext.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ClientModelValidationContext.cs index 76101f10c7..05e47f2249 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ClientModelValidationContext.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ClientModelValidationContext.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.AspNet.Mvc.ModelBinding { public class ClientModelValidationContext diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DataAnnotationsModelValidatorProvider.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DataAnnotationsModelValidatorProvider.cs index 6bea81e5a5..d7d4e554a1 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DataAnnotationsModelValidatorProvider.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DataAnnotationsModelValidatorProvider.cs @@ -22,13 +22,6 @@ namespace Microsoft.AspNet.Mvc.ModelBinding // A factory for validators based on ValidationAttribute. internal delegate IModelValidator DataAnnotationsModelValidationFactory(ValidationAttribute attribute); - // A factory for validators based on IValidatableObject - private delegate IModelValidator DataAnnotationsValidatableObjectAdapterFactory(); - - private static bool _addImplicitRequiredAttributeForValueTypes = true; - private readonly Dictionary _attributeFactories = - BuildAttributeFactoriesDictionary(); - // Factories for validation attributes private static readonly DataAnnotationsModelValidationFactory _defaultAttributeFactory = (attribute) => new DataAnnotationsModelValidator(attribute); @@ -37,6 +30,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding private static readonly DataAnnotationsValidatableObjectAdapterFactory _defaultValidatableFactory = () => new ValidatableObjectAdapter(); + private static bool _addImplicitRequiredAttributeForValueTypes = true; + private readonly Dictionary _attributeFactories = + BuildAttributeFactoriesDictionary(); + + // A factory for validators based on IValidatableObject + private delegate IModelValidator DataAnnotationsValidatableObjectAdapterFactory(); + internal Dictionary AttributeFactories { get { return _attributeFactories; } diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DefaultBodyModelValidator.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DefaultBodyModelValidator.cs index ca3a9a7f0c..c42550e7d8 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DefaultBodyModelValidator.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/DefaultBodyModelValidator.cs @@ -56,7 +56,9 @@ namespace Microsoft.AspNet.Mvc.ModelBinding // We don't need to recursively traverse the graph for types that shouldn't be validated var modelType = metadata.Model.GetType(); - if (IsTypeExcludedFromValidation(validationContext.ModelValidationContext.ExcludeFromValidationFilters, modelType)) + if (IsTypeExcludedFromValidation( + validationContext.ModelValidationContext.ExcludeFromValidationFilters, + modelType)) { return ShallowValidate(metadata, validationContext, validators); } diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelClientValidationRegexRule.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelClientValidationRegexRule.cs index 8db5f92558..89067c81ad 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelClientValidationRegexRule.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelClientValidationRegexRule.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - namespace Microsoft.AspNet.Mvc.ModelBinding { public class ModelClientValidationRegexRule : ModelClientValidationRule diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelValidationNode.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelValidationNode.cs index c5a577149e..fdacf2d6d3 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelValidationNode.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/Validation/ModelValidationNode.cs @@ -104,7 +104,8 @@ namespace Microsoft.AspNet.Mvc.ModelBinding { if (SuppressValidation || !validationContext.ModelState.CanAddErrors) { - // Short circuit if validation does not need to be applied or if we've reached the max number of validation errors. + // Short circuit if validation does not need to be applied or if we've reached the max number of + // validation errors. return; } diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/CompositeValueProvider.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/CompositeValueProvider.cs index 059d682bc0..d7654c7dd5 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/CompositeValueProvider.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/CompositeValueProvider.cs @@ -12,7 +12,8 @@ namespace Microsoft.AspNet.Mvc.ModelBinding /// /// Represents a whose values come from a collection of s. /// - public class CompositeValueProvider : Collection, IEnumerableValueProvider, IMetadataAwareValueProvider + public class CompositeValueProvider + : Collection, IEnumerableValueProvider, IMetadataAwareValueProvider { /// /// Initializes a new instance of . diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/MetadataAwareValueProvider.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/MetadataAwareValueProvider.cs index 63123f688d..6d27eb6768 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/MetadataAwareValueProvider.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/MetadataAwareValueProvider.cs @@ -9,7 +9,9 @@ namespace Microsoft.AspNet.Mvc.ModelBinding /// A value provider which can filter /// based on . /// - /// Represents a type implementing + /// + /// Represents a type implementing + /// public abstract class MetadataAwareValueProvider : IMetadataAwareValueProvider where TBinderMetadata : IValueProviderMetadata { diff --git a/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/ReadableStringCollectionValueProvider.cs b/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/ReadableStringCollectionValueProvider.cs index 389a4ad00b..a6fbd97016 100644 --- a/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/ReadableStringCollectionValueProvider.cs +++ b/src/Microsoft.AspNet.Mvc.ModelBinding/ValueProviders/ReadableStringCollectionValueProvider.cs @@ -16,8 +16,8 @@ namespace Microsoft.AspNet.Mvc.ModelBinding where TBinderMetadata : IValueProviderMetadata { private readonly CultureInfo _culture; - private PrefixContainer _prefixContainer; private readonly Func> _valuesFactory; + private PrefixContainer _prefixContainer; private IReadableStringCollection _values; /// diff --git a/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilationOptionsProviderExtension.cs b/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilationOptionsProviderExtension.cs index 4e0ccc6179..eca324b7be 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilationOptionsProviderExtension.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilationOptionsProviderExtension.cs @@ -15,8 +15,12 @@ namespace Microsoft.AspNet.Mvc.Razor /// Parses the for the current executing application and returns a /// used for Roslyn compilation. /// - /// A that reads compiler options. - /// The for the executing application. + /// + /// A that reads compiler options. + /// + /// + /// The for the executing application. + /// /// The for the current application. public static CompilationSettings GetCompilationSettings( [NotNull] this ICompilerOptionsProvider compilerOptionsProvider, diff --git a/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCache.cs b/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCache.cs index 95d10908f5..c4a269d1bc 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCache.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCache.cs @@ -28,7 +28,7 @@ namespace Microsoft.AspNet.Mvc.Razor /// file system. /// public CompilerCache(IAssemblyProvider provider, IRazorFileSystemCache fileSystem) - : this (GetFileInfos(provider.CandidateAssemblies), fileSystem) + : this(GetFileInfos(provider.CandidateAssemblies), fileSystem) { } diff --git a/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCacheEntry.cs b/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCacheEntry.cs index ffbccc2d40..bd6f73102c 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCacheEntry.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Compilation/CompilerCacheEntry.cs @@ -65,7 +65,13 @@ namespace Microsoft.AspNet.Mvc.Razor /// /// Gets a flag that indicates if the file is precompiled. /// - public bool IsPreCompiled { get { return Hash != null; } } + public bool IsPreCompiled + { + get + { + return Hash != null; + } + } /// /// Gets or sets the for the nearest ViewStart that the compiled type diff --git a/src/Microsoft.AspNet.Mvc.Razor/Compilation/DefaultRazorFileSystemCache.cs b/src/Microsoft.AspNet.Mvc.Razor/Compilation/DefaultRazorFileSystemCache.cs index b60d694078..d03d66def9 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Compilation/DefaultRazorFileSystemCache.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Compilation/DefaultRazorFileSystemCache.cs @@ -4,8 +4,8 @@ using System; using System.Collections.Concurrent; using Microsoft.AspNet.FileSystems; -using Microsoft.Framework.OptionsModel; using Microsoft.Framework.Expiration.Interfaces; +using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Mvc.Razor { diff --git a/src/Microsoft.AspNet.Mvc.Razor/Compilation/RoslynCompilationService.cs b/src/Microsoft.AspNet.Mvc.Razor/Compilation/RoslynCompilationService.cs index 047ce5acb3..43f236a1bc 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Compilation/RoslynCompilationService.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Compilation/RoslynCompilationService.cs @@ -119,8 +119,7 @@ namespace Microsoft.AspNet.Mvc.Razor } var type = assembly.GetExportedTypes() - .First(t => t.Name. - StartsWith(_classPrefix, StringComparison.Ordinal)); + .First(t => t.Name.StartsWith(_classPrefix, StringComparison.Ordinal)); return UncachedCompilationResult.Successful(type, compilationContent); } diff --git a/src/Microsoft.AspNet.Mvc.Razor/IBeforeCompileContext.cs b/src/Microsoft.AspNet.Mvc.Razor/IBeforeCompileContext.cs new file mode 100644 index 0000000000..b7a5979fd0 --- /dev/null +++ b/src/Microsoft.AspNet.Mvc.Razor/IBeforeCompileContext.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Microsoft.Framework.Runtime +{ + [AssemblyNeutral] + public interface IBeforeCompileContext + { + CSharpCompilation CSharpCompilation { get; set; } + + IList Resources { get; } + + IList Diagnostics { get; } + } +} diff --git a/src/Microsoft.AspNet.Mvc.Razor/IViewLocationExpander.cs b/src/Microsoft.AspNet.Mvc.Razor/IViewLocationExpander.cs index 73c089dd35..df423fc89e 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/IViewLocationExpander.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/IViewLocationExpander.cs @@ -24,9 +24,9 @@ namespace Microsoft.AspNet.Mvc.Razor public interface IViewLocationExpander { /// - /// Invoked by a to determine the values that would be consumed by this instance of - /// . The calculated values are used to determine if the view location has - /// changed since the last time it was located. + /// Invoked by a to determine the values that would be consumed by this instance + /// of . The calculated values are used to determine if the view location + /// has changed since the last time it was located. /// /// The for the current view location /// expansion operation. diff --git a/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorErrorExtensions.cs b/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorErrorExtensions.cs index 1c74e69617..8047d956c2 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorErrorExtensions.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorErrorExtensions.cs @@ -11,12 +11,13 @@ namespace Microsoft.AspNet.Mvc.Razor { public static Diagnostic ToDiagnostics([NotNull] this RazorError error, [NotNull] string filePath) { - var descriptor = new DiagnosticDescriptor(id: "Razor", - title: "Razor parsing error", - messageFormat: error.Message.Replace("{", "{{").Replace("}", "}}"), - category: "Razor.Parser", - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true); + var descriptor = new DiagnosticDescriptor( + id: "Razor", + title: "Razor parsing error", + messageFormat: error.Message.Replace("{", "{{").Replace("}", "}}"), + category: "Razor.Parser", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); var textSpan = new TextSpan(error.Location.AbsoluteIndex, error.Length); var linePositionStart = new LinePosition(error.Location.LineIndex, error.Location.CharacterIndex); diff --git a/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorFileInfoCollectionGenerator.cs b/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorFileInfoCollectionGenerator.cs index 956aa62d63..5dc2b51c4a 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorFileInfoCollectionGenerator.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorFileInfoCollectionGenerator.cs @@ -43,7 +43,6 @@ namespace Microsoft.AspNet.Mvc.Razor return syntaxTree; } - protected virtual string GenerateFile([NotNull] RazorFileInfo fileInfo) { return string.Format(FileFormat, diff --git a/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorPreCompiler.cs b/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorPreCompiler.cs index b41c3bf017..0b59bc46a2 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorPreCompiler.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/Razor/PreCompileViews/RazorPreCompiler.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.IO; using Microsoft.AspNet.FileSystems; -using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; @@ -79,7 +78,7 @@ namespace Microsoft.AspNet.Mvc.Razor private IEnumerable GetFileInfosRecursive(string currentPath) { - string path = currentPath; + var path = currentPath; var fileInfos = _fileSystem.GetDirectoryContents(path); if (!fileInfos.Exists) @@ -152,16 +151,3 @@ namespace Microsoft.AspNet.Mvc.Razor } } } - -namespace Microsoft.Framework.Runtime -{ - [AssemblyNeutral] - public interface IBeforeCompileContext - { - CSharpCompilation CSharpCompilation { get; set; } - - IList Resources { get; } - - IList Diagnostics { get; } - } -} diff --git a/src/Microsoft.AspNet.Mvc.Razor/RazorPage.cs b/src/Microsoft.AspNet.Mvc.Razor/RazorPage.cs index 2e63d1b060..9b5b48a719 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/RazorPage.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/RazorPage.cs @@ -122,12 +122,14 @@ namespace Microsoft.AspNet.Mvc.Razor { if (_tagHelperActivator == null) { - _tagHelperActivator = ViewContext.HttpContext.RequestServices.GetRequiredService(); + _tagHelperActivator = + ViewContext.HttpContext.RequestServices.GetRequiredService(); } return _tagHelperActivator; } } + /// /// Creates and activates a . /// diff --git a/src/Microsoft.AspNet.Mvc.Razor/RazorView.cs b/src/Microsoft.AspNet.Mvc.Razor/RazorView.cs index 0133be5f7a..1ed944a9a7 100644 --- a/src/Microsoft.AspNet.Mvc.Razor/RazorView.cs +++ b/src/Microsoft.AspNet.Mvc.Razor/RazorView.cs @@ -33,8 +33,7 @@ namespace Microsoft.AspNet.Mvc.Razor IRazorPageActivator pageActivator, IViewStartProvider viewStartProvider, IRazorPage razorPage, - bool isPartial - ) + bool isPartial) { _viewEngine = viewEngine; _pageActivator = pageActivator; @@ -53,7 +52,6 @@ namespace Microsoft.AspNet.Mvc.Razor /// public bool IsPartial { get; } - private bool EnableInstrumentation { get { return _pageExecutionFeature != null; } @@ -97,8 +95,8 @@ namespace Microsoft.AspNet.Mvc.Razor bool executeViewStart) { var razorTextWriter = new RazorTextWriter(context.Writer, context.Writer.Encoding); - TextWriter writer = razorTextWriter; - IBufferedTextWriter bufferedWriter = razorTextWriter; + var writer = (TextWriter)razorTextWriter; + var bufferedWriter = (IBufferedTextWriter)razorTextWriter; if (EnableInstrumentation) { diff --git a/src/Microsoft.AspNet.Mvc.TagHelpers/FormTagHelper.cs b/src/Microsoft.AspNet.Mvc.TagHelpers/FormTagHelper.cs index ca9246bf3d..ce6453de4a 100644 --- a/src/Microsoft.AspNet.Mvc.TagHelpers/FormTagHelper.cs +++ b/src/Microsoft.AspNet.Mvc.TagHelpers/FormTagHelper.cs @@ -65,7 +65,7 @@ namespace Microsoft.AspNet.Mvc.TagHelpers /// public override void Process(TagHelperContext context, TagHelperOutput output) { - bool antiForgeryDefault = true; + var antiForgeryDefault = true; var routePrefixedAttributes = output.FindPrefixedAttributes(RouteAttributePrefix); // If "action" is already set, it means the user is attempting to use a normal . diff --git a/src/Microsoft.AspNet.Mvc.TagHelpers/ValidationSummaryTagHelper.cs b/src/Microsoft.AspNet.Mvc.TagHelpers/ValidationSummaryTagHelper.cs index 6a97dba832..3463b9acec 100644 --- a/src/Microsoft.AspNet.Mvc.TagHelpers/ValidationSummaryTagHelper.cs +++ b/src/Microsoft.AspNet.Mvc.TagHelpers/ValidationSummaryTagHelper.cs @@ -26,7 +26,6 @@ namespace Microsoft.AspNet.Mvc.TagHelpers [Activate] protected internal IHtmlGenerator Generator { get; set; } - // TODO: https://github.com/aspnet/Razor/issues/196 Change to ValidationSummary enum once #196 has been completed. /// /// If All or ModelOnly, appends a validation summary. Acceptable values are defined by the /// enum. diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ApiController.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ApiController.cs index 54ff8becf5..7c908794e7 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ApiController.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ApiController.cs @@ -41,7 +41,8 @@ namespace System.Web.Http } /// - /// Gets model state after the model binding process. This ModelState will be empty before model binding happens. + /// Gets model state after the model binding process. This ModelState will be empty before model binding + /// happens. /// public ModelStateDictionary ModelState { diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/CollectionExtensions.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/CollectionExtensions.cs index 6dd42fdce5..eb3b0ca83e 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/CollectionExtensions.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/CollectionExtensions.cs @@ -15,14 +15,15 @@ namespace System.Collections.Generic internal static class CollectionExtensions { /// - /// Return a new array with the value added to the end. Slow and best suited to long lived arrays with few writes relative to reads. + /// Return a new array with the value added to the end. Slow and best suited to long lived arrays with few + /// writes relative to reads. /// public static T[] AppendAndReallocate(this T[] array, T value) { Debug.Assert(array != null); - int originalLength = array.Length; - T[] newArray = new T[originalLength + 1]; + var originalLength = array.Length; + var newArray = new T[originalLength + 1]; array.CopyTo(newArray, 0); newArray[originalLength] = value; return newArray; @@ -36,7 +37,7 @@ namespace System.Collections.Generic { Debug.Assert(values != null); - T[] array = values as T[]; + var array = values as T[]; if (array == null) { array = values.ToArray(); @@ -52,13 +53,13 @@ namespace System.Collections.Generic { Debug.Assert(enumerable != null); - Collection collection = enumerable as Collection; + var collection = enumerable as Collection; if (collection != null) { return collection; } // Check for IList so that collection can wrap it instead of copying - IList list = enumerable as IList; + var list = enumerable as IList; if (list == null) { list = new List(enumerable); @@ -73,7 +74,7 @@ namespace System.Collections.Generic { Debug.Assert(enumerable != null); - IList list = enumerable as IList; + var list = enumerable as IList; if (list != null) { return list; @@ -82,8 +83,8 @@ namespace System.Collections.Generic } /// - /// Return the enumerable as a List of T, copying if required. Optimized for common case where it is an List of T - /// or a ListWrapperCollection of T. Avoid mutating the return value. + /// Return the enumerable as a List of T, copying if required. Optimized for common case where it is an List of + /// T or a ListWrapperCollection of T. Avoid mutating the return value. /// public static List AsList(this IEnumerable enumerable) { @@ -127,7 +128,7 @@ namespace System.Collections.Generic return default(T); case 1: - T value = list[0]; + var value = list[0]; return value; default: @@ -137,18 +138,21 @@ namespace System.Collections.Generic } /// - /// Returns a single value in list matching type TMatch if there is only one, null if there are none of type TMatch or calls the - /// errorAction with errorArg1 if there is more than one. + /// Returns a single value in list matching type TMatch if there is only one, null if there are none of type + /// TMatch or calls the errorAction with errorArg1 if there is more than one. /// - public static TMatch SingleOfTypeDefaultOrError(this IList list, Action errorAction, TArg1 errorArg1) where TMatch : class + public static TMatch SingleOfTypeDefaultOrError( + this IList list, + Action errorAction, + TArg1 errorArg1) where TMatch : class { Debug.Assert(list != null); Debug.Assert(errorAction != null); TMatch result = null; - for (int i = 0; i < list.Count; i++) + for (var i = 0; i < list.Count; i++) { - TMatch typedValue = list[i] as TMatch; + var typedValue = list[i] as TMatch; if (typedValue != null) { if (result == null) @@ -166,15 +170,16 @@ namespace System.Collections.Generic } /// - /// Convert an ICollection to an array, removing null values. Fast path for case where there are no null values. + /// Convert an ICollection to an array, removing null values. Fast path for case where there are no null + /// values. /// public static T[] ToArrayWithoutNulls(this ICollection collection) where T : class { Debug.Assert(collection != null); - T[] result = new T[collection.Count]; - int count = 0; - foreach (T value in collection) + var result = new T[collection.Count]; + var count = 0; + foreach (var value in collection) { if (value != null) { @@ -188,38 +193,46 @@ namespace System.Collections.Generic } else { - T[] trimmedResult = new T[count]; + var trimmedResult = new T[count]; Array.Copy(result, trimmedResult, count); return trimmedResult; } } /// - /// Convert the array to a Dictionary using the keySelector to extract keys from values and the specified comparer. Optimized for array input. + /// Convert the array to a Dictionary using the keySelector to extract keys from values and the specified + /// comparer. Optimized for array input. /// - public static Dictionary ToDictionaryFast(this TValue[] array, Func keySelector, IEqualityComparer comparer) + public static Dictionary ToDictionaryFast( + this TValue[] array, + Func keySelector, + IEqualityComparer comparer) { Debug.Assert(array != null); Debug.Assert(keySelector != null); - Dictionary dictionary = new Dictionary(array.Length, comparer); - for (int i = 0; i < array.Length; i++) + var dictionary = new Dictionary(array.Length, comparer); + for (var i = 0; i < array.Length; i++) { - TValue value = array[i]; + var value = array[i]; dictionary.Add(keySelector(value), value); } return dictionary; } /// - /// Convert the list to a Dictionary using the keySelector to extract keys from values and the specified comparer. Optimized for IList of T input with fast path for array. + /// Convert the list to a Dictionary using the keySelector to extract keys from values and the specified + /// comparer. Optimized for IList of T input with fast path for array. /// - public static Dictionary ToDictionaryFast(this IList list, Func keySelector, IEqualityComparer comparer) + public static Dictionary ToDictionaryFast( + this IList list, + Func keySelector, + IEqualityComparer comparer) { Debug.Assert(list != null); Debug.Assert(keySelector != null); - TValue[] array = list as TValue[]; + var array = list as TValue[]; if (array != null) { return ToDictionaryFast(array, keySelector, comparer); @@ -228,25 +241,29 @@ namespace System.Collections.Generic } /// - /// Convert the enumerable to a Dictionary using the keySelector to extract keys from values and the specified comparer. Fast paths for array and IList of T. + /// Convert the enumerable to a Dictionary using the keySelector to extract keys from values and the specified + /// comparer. Fast paths for array and IList of T. /// - public static Dictionary ToDictionaryFast(this IEnumerable enumerable, Func keySelector, IEqualityComparer comparer) + public static Dictionary ToDictionaryFast( + this IEnumerable enumerable, + Func keySelector, + IEqualityComparer comparer) { Debug.Assert(enumerable != null); Debug.Assert(keySelector != null); - TValue[] array = enumerable as TValue[]; + var array = enumerable as TValue[]; if (array != null) { return ToDictionaryFast(array, keySelector, comparer); } - IList list = enumerable as IList; + var list = enumerable as IList; if (list != null) { return ToDictionaryFastNoCheck(list, keySelector, comparer); } - Dictionary dictionary = new Dictionary(comparer); - foreach (TValue value in enumerable) + var dictionary = new Dictionary(comparer); + foreach (var value in enumerable) { dictionary.Add(keySelector(value), value); } @@ -254,18 +271,22 @@ namespace System.Collections.Generic } /// - /// Convert the list to a Dictionary using the keySelector to extract keys from values and the specified comparer. Optimized for IList of T input. No checking for other types. + /// Convert the list to a Dictionary using the keySelector to extract keys from values and the specified + /// comparer. Optimized for IList of T input. No checking for other types. /// - private static Dictionary ToDictionaryFastNoCheck(IList list, Func keySelector, IEqualityComparer comparer) + private static Dictionary ToDictionaryFastNoCheck( + IList list, + Func keySelector, + IEqualityComparer comparer) { Debug.Assert(list != null); Debug.Assert(keySelector != null); - int listCount = list.Count; - Dictionary dictionary = new Dictionary(listCount, comparer); - for (int i = 0; i < listCount; i++) + var listCount = list.Count; + var dictionary = new Dictionary(listCount, comparer); + for (var i = 0; i < listCount; i++) { - TValue value = list[i]; + var value = list[i]; dictionary.Add(keySelector(value), value); } return dictionary; diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/DefaultContentNegotiator.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/DefaultContentNegotiator.cs index fe95f0955e..4d411c78ff 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/DefaultContentNegotiator.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/DefaultContentNegotiator.cs @@ -9,9 +9,7 @@ using System.Diagnostics; using System.Linq; using System.Net.Http.Headers; using System.Text; -using System.Web.Http; using Microsoft.AspNet.Mvc; -using System.Net.Http.Formatting; namespace System.Net.Http.Formatting { @@ -48,35 +46,39 @@ namespace System.Net.Http.Formatting public bool ExcludeMatchOnTypeOnly { get; private set; } /// - /// Performs content negotiating by selecting the most appropriate out of the passed in - /// for the given that can serialize an object of the given - /// . + /// Performs content negotiating by selecting the most appropriate out of the + /// passed in for the given that can serialize an + /// object of the given . /// /// The type to be serialized. /// The request. /// The set of objects from which to choose. - /// The result of the negotiation containing the most appropriate instance, - /// or null if there is no appropriate formatter. - public virtual ContentNegotiationResult Negotiate([NotNull] Type type, [NotNull] HttpRequestMessage request, [NotNull] IEnumerable formatters) + /// The result of the negotiation containing the most appropriate + /// instance, or null if there is no appropriate formatter. + public virtual ContentNegotiationResult Negotiate( + [NotNull] Type type, + [NotNull] HttpRequestMessage request, + [NotNull] IEnumerable formatters) { // Go through each formatter to compute how well it matches. - Collection matches = ComputeFormatterMatches(type, request, formatters); + var matches = ComputeFormatterMatches(type, request, formatters); // Select best formatter match among the matches - MediaTypeFormatterMatch bestFormatterMatch = SelectResponseMediaTypeFormatter(matches); + var bestFormatterMatch = SelectResponseMediaTypeFormatter(matches); // We found a best formatter if (bestFormatterMatch != null) { // Find the best character encoding for the selected formatter - Encoding bestEncodingMatch = SelectResponseCharacterEncoding(request, bestFormatterMatch.Formatter); + var bestEncodingMatch = SelectResponseCharacterEncoding(request, bestFormatterMatch.Formatter); if (bestEncodingMatch != null) { bestFormatterMatch.MediaType.CharSet = bestEncodingMatch.WebName; } - MediaTypeHeaderValue bestMediaType = bestFormatterMatch.MediaType; - MediaTypeFormatter bestFormatter = bestFormatterMatch.Formatter.GetPerRequestFormatterInstance(type, request, bestMediaType); + var bestMediaType = bestFormatterMatch.MediaType; + var bestFormatter = + bestFormatterMatch.Formatter.GetPerRequestFormatterInstance(type, request, bestMediaType); return new ContentNegotiationResult(bestFormatter, bestMediaType); } @@ -84,25 +86,28 @@ namespace System.Net.Http.Formatting } /// - /// Determine how well each formatter matches by associating a value - /// with the formatter. Then associate the quality of the match based on q-factors and other parameters. The result of this - /// method is a collection of the matches found categorized and assigned a quality value. + /// Determine how well each formatter matches by associating a + /// value with the formatter. Then associate the quality of the match based on q-factors and other parameters. + /// The result of this method is a collection of the matches found categorized and assigned a quality value. /// /// The type to be serialized. /// The request. /// The set of objects from which to choose. /// A collection containing all the matches. - protected virtual Collection ComputeFormatterMatches([NotNull] Type type, [NotNull] HttpRequestMessage request, [NotNull] IEnumerable formatters) + protected virtual Collection ComputeFormatterMatches( + [NotNull] Type type, + [NotNull] HttpRequestMessage request, + [NotNull] IEnumerable formatters) { IEnumerable sortedAcceptValues = null; // Go through each formatter to find how well it matches. - ListWrapperCollection matches = new ListWrapperCollection(); - MediaTypeFormatter[] writingFormatters = GetWritingFormatters(formatters); - for (int i = 0; i < writingFormatters.Length; i++) + var matches = + new ListWrapperCollection(); + var writingFormatters = GetWritingFormatters(formatters); + for (var i = 0; i < writingFormatters.Length; i++) { - MediaTypeFormatter formatter = writingFormatters[i]; - MediaTypeFormatterMatch match = null; + var formatter = writingFormatters[i]; // Check first that formatter can write the actual type if (!formatter.CanWriteType(type)) @@ -117,7 +122,9 @@ namespace System.Net.Http.Formatting // Sort the Accept header values in descending order based on q-factor sortedAcceptValues = SortMediaTypeWithQualityHeaderValuesByQFactor(request.Headers.Accept); } - if ((match = MatchAcceptHeader(sortedAcceptValues, formatter)) != null) + + var match = MatchAcceptHeader(sortedAcceptValues, formatter); + if (match != null) { matches.Add(match); continue; @@ -132,7 +139,7 @@ namespace System.Net.Http.Formatting // Check whether we should match on type or stop the matching process. // The latter is used to generate 406 (Not Acceptable) status codes. - bool shouldMatchOnType = ShouldMatchOnType(sortedAcceptValues); + var shouldMatchOnType = ShouldMatchOnType(sortedAcceptValues); // Match against the type of object we are writing out if (shouldMatchOnType && (match = MatchType(type, formatter)) != null) @@ -150,11 +157,12 @@ namespace System.Net.Http.Formatting /// /// The collection of matches. /// The determined to be the best match. - protected virtual MediaTypeFormatterMatch SelectResponseMediaTypeFormatter([NotNull] ICollection matches) + protected virtual MediaTypeFormatterMatch SelectResponseMediaTypeFormatter( + [NotNull] ICollection matches) { // Performance-sensitive - List matchList = matches.AsList(); + var matchList = matches.AsList(); MediaTypeFormatterMatch bestMatchOnType = null; MediaTypeFormatterMatch bestMatchOnAcceptHeaderLiteral = null; @@ -164,9 +172,9 @@ namespace System.Net.Http.Formatting MediaTypeFormatterMatch bestMatchOnRequestMediaType = null; // Go through each formatter to find the best match in each category. - for (int i = 0; i < matchList.Count; i++) + for (var i = 0; i < matchList.Count; i++) { - MediaTypeFormatterMatch match = matchList[i]; + var match = matchList[i]; switch (match.Ranking) { case MediaTypeFormatterMatchRanking.MatchOnCanWriteType: @@ -186,13 +194,15 @@ namespace System.Net.Http.Formatting case MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange: // Matches on accept headers must choose the highest quality match. // A match of 0.0 means we won't use it at all. - bestMatchOnAcceptHeaderSubtypeMediaRange = UpdateBestMatch(bestMatchOnAcceptHeaderSubtypeMediaRange, match); + bestMatchOnAcceptHeaderSubtypeMediaRange = + UpdateBestMatch(bestMatchOnAcceptHeaderSubtypeMediaRange, match); break; case MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange: // Matches on accept headers must choose the highest quality match. // A match of 0.0 means we won't use it at all. - bestMatchOnAcceptHeaderAllMediaRange = UpdateBestMatch(bestMatchOnAcceptHeaderAllMediaRange, match); + bestMatchOnAcceptHeaderAllMediaRange = + UpdateBestMatch(bestMatchOnAcceptHeaderAllMediaRange, match); break; case MediaTypeFormatterMatchRanking.MatchOnRequestMediaType: @@ -206,12 +216,13 @@ namespace System.Net.Http.Formatting } // If we received matches based on both supported media types and from media type mappings, - // we want to give precedence to the media type mappings, but only if their quality is >= that of the supported media type. - // We do this because media type mappings are the user's extensibility point and must take precedence over normal - // supported media types in the case of a tie. The 99% case is where both have quality 1.0. + // we want to give precedence to the media type mappings, but only if their quality is >= that of the + // supported media type. We do this because media type mappings are the user's extensibility point and must + // take precedence over normal supported media types in the case of a tie. The 99% case is where both have + // quality 1.0. if (bestMatchOnMediaTypeMapping != null) { - MediaTypeFormatterMatch mappingOverride = bestMatchOnMediaTypeMapping; + var mappingOverride = bestMatchOnMediaTypeMapping; mappingOverride = UpdateBestMatch(mappingOverride, bestMatchOnAcceptHeaderLiteral); mappingOverride = UpdateBestMatch(mappingOverride, bestMatchOnAcceptHeaderSubtypeMediaRange); mappingOverride = UpdateBestMatch(mappingOverride, bestMatchOnAcceptHeaderAllMediaRange); @@ -256,21 +267,24 @@ namespace System.Net.Http.Formatting /// If no encoding is found then we use the default for the formatter. /// /// The determined to be the best match. - protected virtual Encoding SelectResponseCharacterEncoding([NotNull] HttpRequestMessage request, [NotNull] MediaTypeFormatter formatter) + protected virtual Encoding SelectResponseCharacterEncoding( + [NotNull] HttpRequestMessage request, + [NotNull] MediaTypeFormatter formatter) { // If there are any SupportedEncodings then we pick an encoding - List supportedEncodings = formatter.SupportedEncodings.ToList(); + var supportedEncodings = formatter.SupportedEncodings.ToList(); if (supportedEncodings.Count > 0) { // Sort Accept-Charset header values - IEnumerable sortedAcceptCharsetValues = SortStringWithQualityHeaderValuesByQFactor(request.Headers.AcceptCharset); + var sortedAcceptCharsetValues = + SortStringWithQualityHeaderValuesByQFactor(request.Headers.AcceptCharset); // Check for match based on accept-charset headers foreach (StringWithQualityHeaderValue acceptCharset in sortedAcceptCharsetValues) { - for (int i = 0; i < supportedEncodings.Count; i++) + for (var i = 0; i < supportedEncodings.Count; i++) { - Encoding encoding = supportedEncodings[i]; + var encoding = supportedEncodings[i]; if (encoding != null && acceptCharset.Quality != FormattingUtilities.NoMatch && (acceptCharset.Value.Equals(encoding.WebName, StringComparison.OrdinalIgnoreCase) || acceptCharset.Value.Equals("*", StringComparison.Ordinal))) @@ -292,17 +306,22 @@ namespace System.Net.Http.Formatting /// /// The sorted accept header values to match. /// The formatter to match against. - /// A indicating the quality of the match or null is no match. - protected virtual MediaTypeFormatterMatch MatchAcceptHeader([NotNull] IEnumerable sortedAcceptValues, [NotNull] MediaTypeFormatter formatter) + /// + /// A indicating the quality of the match or null is no match. + /// + protected virtual MediaTypeFormatterMatch MatchAcceptHeader( + [NotNull] IEnumerable sortedAcceptValues, + [NotNull] MediaTypeFormatter formatter) { foreach (MediaTypeWithQualityHeaderValue acceptMediaTypeValue in sortedAcceptValues) { - List supportedMediaTypes = formatter.SupportedMediaTypes.ToList(); - for (int i = 0; i < supportedMediaTypes.Count; i++) + var supportedMediaTypes = formatter.SupportedMediaTypes.ToList(); + for (var i = 0; i < supportedMediaTypes.Count; i++) { - MediaTypeHeaderValue supportedMediaType = supportedMediaTypes[i]; + var supportedMediaType = supportedMediaTypes[i]; MediaTypeHeaderValueRange range; - if (supportedMediaType != null && acceptMediaTypeValue.Quality != FormattingUtilities.NoMatch && + if (supportedMediaType != null && + acceptMediaTypeValue.Quality != FormattingUtilities.NoMatch && supportedMediaType.IsSubsetOf(acceptMediaTypeValue, out range)) { MediaTypeFormatterMatchRanking ranking; @@ -321,7 +340,11 @@ namespace System.Net.Http.Formatting break; } - return new MediaTypeFormatterMatch(formatter, supportedMediaType, acceptMediaTypeValue.Quality, ranking); + return new MediaTypeFormatterMatch( + formatter, + supportedMediaType, + acceptMediaTypeValue.Quality, + ranking); } } } @@ -335,21 +358,29 @@ namespace System.Net.Http.Formatting /// /// The request to match. /// The formatter to match against. - /// A indicating the quality of the match or null is no match. - protected virtual MediaTypeFormatterMatch MatchRequestMediaType([NotNull] HttpRequestMessage request, [NotNull] MediaTypeFormatter formatter) + /// + /// A indicating the quality of the match or null is no match. + /// + protected virtual MediaTypeFormatterMatch MatchRequestMediaType( + [NotNull] HttpRequestMessage request, + [NotNull] MediaTypeFormatter formatter) { if (request.Content != null) { - MediaTypeHeaderValue requestMediaType = request.Content.Headers.ContentType; + var requestMediaType = request.Content.Headers.ContentType; if (requestMediaType != null) { - List supportedMediaTypes = formatter.SupportedMediaTypes.ToList(); - for (int i = 0; i < supportedMediaTypes.Count; i++) + var supportedMediaTypes = formatter.SupportedMediaTypes.ToList(); + for (var i = 0; i < supportedMediaTypes.Count; i++) { - MediaTypeHeaderValue supportedMediaType = supportedMediaTypes[i]; + var supportedMediaType = supportedMediaTypes[i]; if (supportedMediaType != null && supportedMediaType.IsSubsetOf(requestMediaType)) { - return new MediaTypeFormatterMatch(formatter, supportedMediaType, FormattingUtilities.Match, MediaTypeFormatterMatchRanking.MatchOnRequestMediaType); + return new MediaTypeFormatterMatch( + formatter, + supportedMediaType, + FormattingUtilities.Match, + MediaTypeFormatterMatchRanking.MatchOnRequestMediaType); } } } @@ -365,8 +396,11 @@ namespace System.Net.Http.Formatting /// then we don't match on type unless there are no accept headers. /// /// The sorted accept header values to match. - /// True if not ExcludeMatchOnTypeOnly and accept headers with a q-factor bigger than 0.0 are present. - protected virtual bool ShouldMatchOnType([NotNull] IEnumerable sortedAcceptValues) + /// + /// True if not ExcludeMatchOnTypeOnly and accept headers with a q-factor bigger than 0.0 are present. + /// + protected virtual bool ShouldMatchOnType( + [NotNull] IEnumerable sortedAcceptValues) { return !(ExcludeMatchOnTypeOnly && sortedAcceptValues.Any()); } @@ -376,18 +410,26 @@ namespace System.Net.Http.Formatting /// /// The type to be serialized. /// The formatter we are matching against. - /// A indicating the quality of the match or null is no match. - protected virtual MediaTypeFormatterMatch MatchType([NotNull] Type type, [NotNull] MediaTypeFormatter formatter) + /// + /// A indicating the quality of the match or null is no match. + /// + protected virtual MediaTypeFormatterMatch MatchType( + [NotNull] Type type, + [NotNull] MediaTypeFormatter formatter) { // We already know that we do match on type -- otherwise we wouldn't even be called -- // so this is just a matter of determining how we match. MediaTypeHeaderValue mediaType = null; - List supportedMediaTypes = formatter.SupportedMediaTypes.ToList(); + var supportedMediaTypes = formatter.SupportedMediaTypes.ToList(); if (supportedMediaTypes.Count > 0) { mediaType = supportedMediaTypes[0]; } - return new MediaTypeFormatterMatch(formatter, mediaType, FormattingUtilities.Match, MediaTypeFormatterMatchRanking.MatchOnCanWriteType); + return new MediaTypeFormatterMatch( + formatter, + mediaType, + FormattingUtilities.Match, + MediaTypeFormatterMatchRanking.MatchOnCanWriteType); } /// @@ -396,13 +438,16 @@ namespace System.Net.Http.Formatting /// /// The header values to sort. /// The sorted header values. - protected virtual IEnumerable SortMediaTypeWithQualityHeaderValuesByQFactor(ICollection headerValues) + protected virtual IEnumerable SortMediaTypeWithQualityHeaderValuesByQFactor( + ICollection headerValues) { if (headerValues.Count > 1) { // Use OrderBy() instead of Array.Sort() as it performs fewer comparisons. In this case the comparisons // are quite expensive so OrderBy() performs better. - return headerValues.OrderByDescending(m => m, MediaTypeWithQualityHeaderValueComparer.QualityComparer).ToArray(); + return headerValues + .OrderByDescending(m => m, MediaTypeWithQualityHeaderValueComparer.QualityComparer) + .ToArray(); } else { @@ -411,18 +456,21 @@ namespace System.Net.Http.Formatting } /// - /// Sort Accept-Charset, Accept-Encoding, Accept-Language and related header field values with similar syntax rules - /// (if more than 1) in descending order based on q-factor. + /// Sort Accept-Charset, Accept-Encoding, Accept-Language and related header field values with similar syntax + /// rules (if more than 1) in descending order based on q-factor. /// /// The header values to sort. /// The sorted header values. - protected virtual IEnumerable SortStringWithQualityHeaderValuesByQFactor([NotNull] ICollection headerValues) + protected virtual IEnumerable SortStringWithQualityHeaderValuesByQFactor( + [NotNull] ICollection headerValues) { if (headerValues.Count > 1) { // Use OrderBy() instead of Array.Sort() as it performs fewer comparisons. In this case the comparisons // are quite expensive so OrderBy() performs better. - return headerValues.OrderByDescending(m => m, StringWithQualityHeaderValueComparer.QualityComparer).ToArray(); + return headerValues + .OrderByDescending(m => m, StringWithQualityHeaderValueComparer.QualityComparer) + .ToArray(); } else { @@ -431,10 +479,12 @@ namespace System.Net.Http.Formatting } /// - /// Evaluates whether a match is better than the current match and if so returns the replacement; otherwise returns the - /// current match. + /// Evaluates whether a match is better than the current match and if so returns the replacement; otherwise + /// returns the current match. /// - protected virtual MediaTypeFormatterMatch UpdateBestMatch(MediaTypeFormatterMatch current, MediaTypeFormatterMatch potentialReplacement) + protected virtual MediaTypeFormatterMatch UpdateBestMatch( + MediaTypeFormatterMatch current, + MediaTypeFormatterMatch potentialReplacement) { if (potentialReplacement == null) { @@ -452,7 +502,6 @@ namespace System.Net.Http.Formatting private static MediaTypeFormatter[] GetWritingFormatters(IEnumerable formatters) { Debug.Assert(formatters != null); - MediaTypeFormatterCollection formatterCollection = formatters as MediaTypeFormatterCollection; return formatters.AsArray(); } } diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs index c04277491a..e7b1381c10 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/FormattingUtilities.cs @@ -8,10 +8,9 @@ using System.Globalization; using System.Linq; using System.Net.Http.Formatting; using System.Net.Http.Headers; -using System.Runtime.Serialization; +using System.Reflection; using System.Xml; using Newtonsoft.Json.Linq; -using System.Reflection; namespace System.Net.Http { @@ -161,7 +160,9 @@ namespace System.Net.Http /// public static XmlDictionaryReaderQuotas CreateDefaultReaderQuotas() { -#if NETFX_CORE // MaxDepth is a DOS mitigation. We don't support MaxDepth in portable libraries because it is strictly client side. + // MaxDepth is a DOS mitigation. We don't support MaxDepth in portable libraries because it is strictly + // client side. +#if NETFX_CORE return XmlDictionaryReaderQuotas.Max; #else return new XmlDictionaryReaderQuotas() @@ -187,7 +188,9 @@ namespace System.Net.Http return token; } - if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1) + if (token.StartsWith("\"", StringComparison.Ordinal) && + token.EndsWith("\"", StringComparison.Ordinal) && + token.Length > 1) { return token.Substring(1, token.Length - 2); } diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/IContentNegotiator.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/IContentNegotiator.cs index 1909f92480..05c37ce25e 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/IContentNegotiator.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/IContentNegotiator.cs @@ -15,20 +15,27 @@ namespace System.Net.Http.Formatting public interface IContentNegotiator { /// - /// Performs content negotiating by selecting the most appropriate out of the passed in - /// for the given that can serialize an object of the given - /// . + /// Performs content negotiating by selecting the most appropriate out of the + /// passed in for the given that can serialize an + /// object of the given . /// /// - /// Implementations of this method should call + /// Implementations of this method should call /// on the selected formatter and return the result of that method. /// /// The type to be serialized. - /// Request message, which contains the header values used to perform negotiation. + /// + /// Request message, which contains the header values used to perform negotiation. + /// /// The set of objects from which to choose. - /// The result of the negotiation containing the most appropriate instance, - /// or null if there is no appropriate formatter. - ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable formatters); + /// + /// The result of the negotiation containing the most appropriate instance, + /// or null if there is no appropriate formatter. + /// + ContentNegotiationResult Negotiate( + Type type, + HttpRequestMessage request, + IEnumerable formatters); } } #endif diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeConstants.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeConstants.cs index d78f6f66aa..82532aecdc 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeConstants.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeConstants.cs @@ -12,13 +12,20 @@ namespace System.Net.Http.Formatting /// internal static class MediaTypeConstants { - private static readonly MediaTypeHeaderValue _defaultApplicationXmlMediaType = new MediaTypeHeaderValue("application/xml"); - private static readonly MediaTypeHeaderValue _defaultTextXmlMediaType = new MediaTypeHeaderValue("text/xml"); - private static readonly MediaTypeHeaderValue _defaultApplicationJsonMediaType = new MediaTypeHeaderValue("application/json"); - private static readonly MediaTypeHeaderValue _defaultTextJsonMediaType = new MediaTypeHeaderValue("text/json"); - private static readonly MediaTypeHeaderValue _defaultApplicationOctetStreamMediaType = new MediaTypeHeaderValue("application/octet-stream"); - private static readonly MediaTypeHeaderValue _defaultApplicationFormUrlEncodedMediaType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); - private static readonly MediaTypeHeaderValue _defaultApplicationBsonMediaType = new MediaTypeHeaderValue("application/bson"); + private static readonly MediaTypeHeaderValue _defaultApplicationXmlMediaType = + new MediaTypeHeaderValue("application/xml"); + private static readonly MediaTypeHeaderValue _defaultTextXmlMediaType = + new MediaTypeHeaderValue("text/xml"); + private static readonly MediaTypeHeaderValue _defaultApplicationJsonMediaType = + new MediaTypeHeaderValue("application/json"); + private static readonly MediaTypeHeaderValue _defaultTextJsonMediaType = + new MediaTypeHeaderValue("text/json"); + private static readonly MediaTypeHeaderValue _defaultApplicationOctetStreamMediaType = + new MediaTypeHeaderValue("application/octet-stream"); + private static readonly MediaTypeHeaderValue _defaultApplicationFormUrlEncodedMediaType = + new MediaTypeHeaderValue("application/x-www-form-urlencoded"); + private static readonly MediaTypeHeaderValue _defaultApplicationBsonMediaType = + new MediaTypeHeaderValue("application/bson"); /// /// Gets a instance representing application/octet-stream. diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeFormatterMatch.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeFormatterMatch.cs index 12739383c1..bd68a8dc9e 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeFormatterMatch.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeFormatterMatch.cs @@ -4,7 +4,6 @@ #if ASPNETCORE50 using System.Net.Http.Headers; -using System.Web.Http; namespace System.Net.Http.Formatting { @@ -17,10 +16,19 @@ namespace System.Net.Http.Formatting /// Initializes a new instance of the class. /// /// The matching formatter. - /// The media type. Can be null in which case the media type application/octet-stream is used. - /// The quality of the match. Can be null in which case it is considered a full match with a value of 1.0 + /// + /// The media type. Can be null in which case the media type application/octet-stream is used. + /// + /// + /// The quality of the match. Can be null in which case it is considered a full match with a value of + /// 1.0. + /// /// The kind of match. - public MediaTypeFormatterMatch(MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, double? quality, MediaTypeFormatterMatchRanking ranking) + public MediaTypeFormatterMatch( + MediaTypeFormatter formatter, + MediaTypeHeaderValue mediaType, + double? quality, + MediaTypeFormatterMatchRanking ranking) { Formatter = formatter; MediaType = mediaType != null ? mediaType : MediaTypeConstants.ApplicationOctetStreamMediaType; diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeHeaderValueExtensions.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeHeaderValueExtensions.cs index 224e6abc9c..1ad5b95486 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeHeaderValueExtensions.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeHeaderValueExtensions.cs @@ -3,12 +3,10 @@ #if ASPNETCORE50 -using Microsoft.AspNet.Mvc; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Diagnostics; -using System.Linq; using System.Net.Http.Headers; +using Microsoft.AspNet.Mvc; namespace System.Net.Http.Formatting { @@ -20,10 +18,11 @@ namespace System.Net.Http.Formatting /// /// Determines whether two instances match. The instance /// is said to match if and only if - /// is a strict subset of the values and parameters of . + /// is a strict subset of the values and parameters of + /// . /// That is, if the media type and media type parameters of are all present - /// and match those of then it is a match even though may have additional - /// parameters. + /// and match those of then it is a match even though + /// may have additional parameters. /// /// The first media type. /// The second media type. @@ -37,16 +36,23 @@ namespace System.Net.Http.Formatting /// /// Determines whether two instances match. The instance /// is said to match if and only if - /// is a strict subset of the values and parameters of . + /// is a strict subset of the values and parameters of + /// . /// That is, if the media type and media type parameters of are all present - /// and match those of then it is a match even though may have additional - /// parameters. + /// and match those of then it is a match even though + /// may have additional parameters. /// /// The first media type. /// The second media type. - /// Indicates whether is a regular media type, a subtype media range, or a full media range + /// + /// Indicates whether is a regular media type, a subtype media range, or a full + /// media range. + /// /// true if this is a subset of ; false otherwise. - public static bool IsSubsetOf(this MediaTypeHeaderValue mediaType1, MediaTypeHeaderValue mediaType2, out MediaTypeHeaderValueRange mediaType2Range) + public static bool IsSubsetOf( + this MediaTypeHeaderValue mediaType1, + MediaTypeHeaderValue mediaType2, + out MediaTypeHeaderValueRange mediaType2Range) { // Performance-sensitive Debug.Assert(mediaType1 != null); @@ -57,8 +63,8 @@ namespace System.Net.Http.Formatting return false; } - ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1); - ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2); + var parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1); + var parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2); mediaType2Range = parsedMediaType2.IsAllMediaRange ? MediaTypeHeaderValueRange.AllMediaRange : parsedMediaType2.IsSubtypeMediaRange ? MediaTypeHeaderValueRange.SubtypeMediaRange : MediaTypeHeaderValueRange.None; @@ -80,18 +86,19 @@ namespace System.Net.Http.Formatting // So far we either have a full match or a subset match. Now check that all of // mediaType1's parameters are present and equal in mediatype2 - // Optimize for the common case where the parameters inherit from Collection and cache the count which is faster for Collection. - Collection parameters1 = mediaType1.Parameters.AsCollection(); - int parameterCount1 = parameters1.Count; - Collection parameters2 = mediaType2.Parameters.AsCollection(); - int parameterCount2 = parameters2.Count; - for (int i = 0; i < parameterCount1; i++) + // Optimize for the common case where the parameters inherit from Collection and cache the count which + // is faster for Collection. + var parameters1 = mediaType1.Parameters.AsCollection(); + var parameterCount1 = parameters1.Count; + var parameters2 = mediaType2.Parameters.AsCollection(); + var parameterCount2 = parameters2.Count; + for (var i = 0; i < parameterCount1; i++) { - NameValueHeaderValue parameter1 = parameters1[i]; - bool found = false; - for (int j = 0; j < parameterCount2; j++) + var parameter1 = parameters1[i]; + var found = false; + for (var j = 0; j < parameterCount2; j++) { - NameValueHeaderValue parameter2 = parameters2[j]; + var parameter2 = parameters2[j]; if (parameter1.Equals(parameter2)) { found = true; diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeWithQualityHeaderComparer.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeWithQualityHeaderComparer.cs index 0a8034ac3a..01bafaf31d 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeWithQualityHeaderComparer.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeWithQualityHeaderComparer.cs @@ -15,7 +15,8 @@ namespace System.Net.Http.Formatting /// header field q-values. internal class MediaTypeWithQualityHeaderValueComparer : IComparer { - private static readonly MediaTypeWithQualityHeaderValueComparer _mediaTypeComparer = new MediaTypeWithQualityHeaderValueComparer(); + private static readonly MediaTypeWithQualityHeaderValueComparer _mediaTypeComparer = + new MediaTypeWithQualityHeaderValueComparer(); private MediaTypeWithQualityHeaderValueComparer() { @@ -27,11 +28,12 @@ namespace System.Net.Http.Formatting } /// - /// Compares two based on their quality value (a.k.a their "q-value"). - /// Values with identical q-values are considered equal (i.e the result is 0) with the exception that sub-type wild-cards are - /// considered less than specific media types and full wild-cards are considered less than sub-type wild-cards. This allows to - /// sort a sequence of following their q-values in the order of specific media types, - /// sub-type wildcards, and last any full wild-cards. + /// Compares two based on their quality value (a.k.a their + /// "q-value"). Values with identical q-values are considered equal (i.e the result is 0) with the exception + /// that sub-type wild-cards are considered less than specific media types and full wild-cards are considered + /// less than sub-type wild-cards. This allows to sort a sequence of + /// following their q-values in the order of specific media types, subtype wild-cards, and last any full + /// wild-cards. /// /// The first to compare. /// The second to compare. @@ -46,12 +48,11 @@ namespace System.Net.Http.Formatting return 0; } - int returnValue = CompareBasedOnQualityFactor(mediaType1, mediaType2); - + var returnValue = CompareBasedOnQualityFactor(mediaType1, mediaType2); if (returnValue == 0) { - ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1); - ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2); + var parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1); + var parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2); if (!parsedMediaType1.TypesEqual(ref parsedMediaType2)) { @@ -88,14 +89,16 @@ namespace System.Net.Http.Formatting return returnValue; } - private static int CompareBasedOnQualityFactor(MediaTypeWithQualityHeaderValue mediaType1, MediaTypeWithQualityHeaderValue mediaType2) + private static int CompareBasedOnQualityFactor( + MediaTypeWithQualityHeaderValue mediaType1, + MediaTypeWithQualityHeaderValue mediaType2) { Debug.Assert(mediaType1 != null); Debug.Assert(mediaType2 != null); - double mediaType1Quality = mediaType1.Quality ?? FormattingUtilities.Match; - double mediaType2Quality = mediaType2.Quality ?? FormattingUtilities.Match; - double qualityDifference = mediaType1Quality - mediaType2Quality; + var mediaType1Quality = mediaType1.Quality ?? FormattingUtilities.Match; + var mediaType2Quality = mediaType2.Quality ?? FormattingUtilities.Match; + var qualityDifference = mediaType1Quality - mediaType2Quality; if (qualityDifference < 0) { return -1; diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/ParsedMediaTypeHeaderValue.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/ParsedMediaTypeHeaderValue.cs index 6e3f4c2214..19d9b51724 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/ParsedMediaTypeHeaderValue.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/ParsedMediaTypeHeaderValue.cs @@ -8,7 +8,7 @@ using System.Net.Http.Headers; namespace System.Net.Http.Formatting { - // This type is instanciated by frequently called comparison methods so is very performance sensitive + // This type is instantiated by frequently called comparison methods so is very performance sensitive internal struct ParsedMediaTypeHeaderValue { private const char MediaRangeAsterisk = '*'; @@ -22,13 +22,15 @@ namespace System.Net.Http.Formatting public ParsedMediaTypeHeaderValue(MediaTypeHeaderValue mediaTypeHeaderValue) { Debug.Assert(mediaTypeHeaderValue != null); - string mediaType = _mediaType = mediaTypeHeaderValue.MediaType; + var mediaType = _mediaType = mediaTypeHeaderValue.MediaType; _delimiterIndex = mediaType.IndexOf(MediaTypeSubtypeDelimiter); - Debug.Assert(_delimiterIndex > 0, "The constructor of the MediaTypeHeaderValue would have failed if there wasn't a type and subtype."); + Debug.Assert( + _delimiterIndex > 0, + "The constructor of the MediaTypeHeaderValue would have failed if there wasn't a type and subtype."); _isAllMediaRange = false; _isSubtypeMediaRange = false; - int mediaTypeLength = mediaType.Length; + var mediaTypeLength = mediaType.Length; if (_delimiterIndex == mediaTypeLength - 2) { if (mediaType[mediaTypeLength - 1] == MediaRangeAsterisk) @@ -58,17 +60,31 @@ namespace System.Net.Http.Formatting { return false; } - return String.Compare(_mediaType, 0, other._mediaType, 0, _delimiterIndex, StringComparison.OrdinalIgnoreCase) == 0; + + return string.Compare( + strA: _mediaType, + indexA: 0, + strB: other._mediaType, + indexB: 0, + length: _delimiterIndex, + comparisonType: StringComparison.OrdinalIgnoreCase) == 0; } public bool SubTypesEqual(ref ParsedMediaTypeHeaderValue other) { - int _subTypeLength = _mediaType.Length - _delimiterIndex - 1; + var _subTypeLength = _mediaType.Length - _delimiterIndex - 1; if (_subTypeLength != other._mediaType.Length - other._delimiterIndex - 1) { return false; } - return String.Compare(_mediaType, _delimiterIndex + 1, other._mediaType, other._delimiterIndex + 1, _subTypeLength, StringComparison.OrdinalIgnoreCase) == 0; + + return string.Compare( + strA: _mediaType, + indexA: _delimiterIndex + 1, + strB: other._mediaType, + indexB: other._delimiterIndex + 1, + length: _subTypeLength, + comparisonType: StringComparison.OrdinalIgnoreCase) == 0; } } } diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/StringWithQualityHeaderValueComparer.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/StringWithQualityHeaderValueComparer.cs index e210572a59..9551bc2132 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/StringWithQualityHeaderValueComparer.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/StringWithQualityHeaderValueComparer.cs @@ -31,10 +31,10 @@ namespace System.Net.Http.Formatting } /// - /// Compares two based on their quality value (a.k.a their "q-value"). - /// Values with identical q-values are considered equal (i.e the result is 0) with the exception of wild-card - /// values (i.e. a value of "*") which are considered less than non-wild-card values. This allows to sort - /// a sequence of following their q-values ending up with any + /// Compares two based on their quality value (a.k.a their + /// "q-value"). Values with identical q-values are considered equal (i.e the result is 0) with the exception of + /// wild-card values (i.e. a value of "*") which are considered less than non-wild-card values. This allows to + /// sort a sequence of following their q-values ending up with any /// wild-cards at the end. /// /// The first value to compare. @@ -46,9 +46,9 @@ namespace System.Net.Http.Formatting Debug.Assert(stringWithQuality1 != null); Debug.Assert(stringWithQuality2 != null); - double quality1 = stringWithQuality1.Quality ?? FormattingUtilities.Match; - double quality2 = stringWithQuality2.Quality ?? FormattingUtilities.Match; - double qualityDifference = quality1 - quality2; + var quality1 = stringWithQuality1.Quality ?? FormattingUtilities.Match; + var quality2 = stringWithQuality2.Quality ?? FormattingUtilities.Match; + var qualityDifference = quality1 - quality2; if (qualityDifference < 0) { return -1; @@ -58,7 +58,7 @@ namespace System.Net.Http.Formatting return 1; } - if (!String.Equals(stringWithQuality1.Value, stringWithQuality2.Value, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(stringWithQuality1.Value, stringWithQuality2.Value, StringComparison.OrdinalIgnoreCase)) { if (String.Equals(stringWithQuality1.Value, "*", StringComparison.Ordinal)) { diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/FormDataCollectionExtensions.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/FormDataCollectionExtensions.cs index 28e99b6c8a..2520cb1998 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/FormDataCollectionExtensions.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/FormDataCollectionExtensions.cs @@ -26,7 +26,7 @@ namespace Microsoft.AspNet.Mvc.WebApiCompatShim var i = 0; while (true) { - int indexOpen = key.IndexOf('[', i); + var indexOpen = key.IndexOf('[', i); if (indexOpen < 0) { // Fast path, no normalization needed. diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpError.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpError.cs index 4adeec0ead..5e038f0978 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpError.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpError.cs @@ -29,7 +29,8 @@ namespace System.Web.Http } /// - /// Initializes a new instance of the class containing error message . + /// Initializes a new instance of the class containing error message + /// . /// /// The error message to associate with this instance. public HttpError([NotNull] string message) @@ -42,7 +43,9 @@ namespace System.Web.Http /// Initializes a new instance of the class for . /// /// The exception to use for error information. - /// true to include the exception information in the error; false otherwise + /// + /// true to include the exception information in the error;false otherwise. + /// public HttpError([NotNull] Exception exception, bool includeErrorDetail) : this() { @@ -64,7 +67,9 @@ namespace System.Web.Http /// Initializes a new instance of the class for . /// /// The invalid model state to use for error information. - /// true to include exception messages in the error; false otherwise + /// + /// true to include exception messages in the error; false otherwise. + /// public HttpError([NotNull] ModelStateDictionary modelState, bool includeErrorDetail) : this() { @@ -105,8 +110,9 @@ namespace System.Web.Http /// /// The high-level, user-visible message explaining the cause of the error. Information carried in this field - /// should be considered public in that it will go over the wire regardless of the value of error detail policy. - /// As a result care should be taken not to disclose sensitive information about the server or the application. + /// should be considered public in that it will go over the wire regardless of the value of error detail + /// policy. As a result care should be taken not to disclose sensitive information about the server or the + /// application. /// public string Message { diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpRequestMessage/HttpRequestMessageExtensions.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpRequestMessage/HttpRequestMessageExtensions.cs index 6100bc140c..8fdf16204c 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpRequestMessage/HttpRequestMessageExtensions.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpRequestMessage/HttpRequestMessageExtensions.cs @@ -20,19 +20,22 @@ namespace System.Net.Http /// public static class HttpRequestMessageExtensions { - #if !ASPNETCORE50 /// - /// Helper method for creating an message with a "416 (Requested Range Not Satisfiable)" status code. - /// This response can be used in combination with the to indicate that the requested range or - /// ranges do not overlap with the current resource. The response contains a "Content-Range" header indicating the valid upper and lower - /// bounds for requested ranges. + /// Helper method for creating an message with a "416 (Requested Range Not + /// Satisfiable)" status code. This response can be used in combination with the + /// to indicate that the requested range or + /// ranges do not overlap with the current resource. The response contains a "Content-Range" header indicating + /// the valid upper and lower bounds for requested ranges. /// /// The request. - /// An instance, typically thrown by a - /// instance. - /// An 416 (Requested Range Not Satisfiable) error response with a Content-Range header indicating the valid range. + /// An instance, typically + /// thrown by a instance. + /// + /// An 416 (Requested Range Not Satisfiable) error response with a Content-Range header indicating the valid + /// range. + /// public static HttpResponseMessage CreateErrorResponse( [NotNull] this HttpRequestMessage request, [NotNull] InvalidByteRangeException invalidByteRangeException) @@ -47,9 +50,10 @@ namespace System.Net.Http #endif /// - /// Helper method that performs content negotiation and creates a representing an error - /// with an instance of wrapping an with message . - /// If no formatter is found, this method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a + /// representing an error with an instance of wrapping an + /// with message . If no formatter is found, this method + /// returns a response with status 406 NotAcceptable. /// /// /// This method requires that has been associated with an instance of @@ -58,7 +62,10 @@ namespace System.Net.Http /// The request. /// The status code of the created response. /// The error message. - /// An error response with error message and status code . + /// + /// An error response with error message and status code + /// . + /// public static HttpResponseMessage CreateErrorResponse( [NotNull] this HttpRequestMessage request, HttpStatusCode statusCode, @@ -68,9 +75,11 @@ namespace System.Net.Http } /// - /// Helper method that performs content negotiation and creates a representing an error - /// with an instance of wrapping an with error message - /// for exception . If no formatter is found, this method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a + /// representing an error with an instance of wrapping an + /// with error message for exception + /// . If no formatter is found, this method returns a response with status 406 + /// NotAcceptable. /// /// /// This method requires that has been associated with an instance of @@ -93,9 +102,10 @@ namespace System.Net.Http } /// - /// Helper method that performs content negotiation and creates a representing an error - /// with an instance of wrapping an for exception . - /// If no formatter is found, this method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a + /// representing an error with an instance of wrapping an + /// for exception . If no formatter is found, this method + /// returns a response with status 406 NotAcceptable. /// /// /// This method requires that has been associated with an instance of @@ -104,7 +114,9 @@ namespace System.Net.Http /// The request. /// The status code of the created response. /// The exception. - /// An error response for with status code . + /// + /// An error response for with status code . + /// public static HttpResponseMessage CreateErrorResponse( [NotNull] this HttpRequestMessage request, HttpStatusCode statusCode, @@ -114,9 +126,10 @@ namespace System.Net.Http } /// - /// Helper method that performs content negotiation and creates a representing an error - /// with an instance of wrapping an for model state . - /// If no formatter is found, this method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a + /// representing an error with an instance of wrapping an + /// for model state . If no formatter is found, this + /// method returns a response with status 406 NotAcceptable. /// /// /// This method requires that has been associated with an instance of @@ -125,7 +138,9 @@ namespace System.Net.Http /// The request. /// The status code of the created response. /// The model state. - /// An error response for with status code . + /// + /// An error response for with status code . + /// public static HttpResponseMessage CreateErrorResponse( [NotNull] this HttpRequestMessage request, HttpStatusCode statusCode, @@ -135,9 +150,9 @@ namespace System.Net.Http } /// - /// Helper method that performs content negotiation and creates a representing an error - /// with an instance of wrapping as the content. If no formatter - /// is found, this method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a + /// representing an error with an instance of wrapping + /// as the content. If no formatter is found, this method returns a response with status 406 NotAcceptable. /// /// /// This method requires that has been associated with an instance of @@ -146,7 +161,9 @@ namespace System.Net.Http /// The request. /// The status code of the created response. /// The error to wrap. - /// An error response wrapping with status code . + /// + /// An error response wrapping with status code . + /// public static HttpResponseMessage CreateErrorResponse( [NotNull] this HttpRequestMessage request, HttpStatusCode statusCode, @@ -156,9 +173,10 @@ namespace System.Net.Http } /// - /// Helper method that performs content negotiation and creates a with an instance - /// of as the content and as the status code - /// if a formatter can be found. If no formatter is found, this method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a with an + /// instance of as the content and + /// as the status code if a formatter can be found. If no formatter is found, this method returns a response + /// with status 406 NotAcceptable. /// /// /// This method requires that has been associated with an instance of @@ -167,16 +185,18 @@ namespace System.Net.Http /// The type of the value. /// The request. /// The value to wrap. Can be null. - /// A response wrapping with status code. + /// + /// A response wrapping with status code. + /// public static HttpResponseMessage CreateResponse([NotNull] this HttpRequestMessage request, T value) { return request.CreateResponse(HttpStatusCode.OK, value, formatters: null); } /// - /// Helper method that performs content negotiation and creates a with an instance - /// of as the content if a formatter can be found. If no formatter is found, this - /// method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a with an + /// instance of as the content if a formatter can be found. If no formatter is + /// found, this method returns a response with status 406 NotAcceptable. /// configuration. /// /// @@ -188,15 +208,18 @@ namespace System.Net.Http /// The status code of the created response. /// The value to wrap. Can be null. /// A response wrapping with . - public static HttpResponseMessage CreateResponse(this HttpRequestMessage request, HttpStatusCode statusCode, T value) + public static HttpResponseMessage CreateResponse( + this HttpRequestMessage request, + HttpStatusCode statusCode, + T value) { return request.CreateResponse(statusCode, value, formatters: null); } /// - /// Helper method that performs content negotiation and creates a with an instance - /// of as the content if a formatter can be found. If no formatter is found, this - /// method returns a response with status 406 NotAcceptable. + /// Helper method that performs content negotiation and creates a with an + /// instance of as the content if a formatter can be found. If no formatter is + /// found, this method returns a response with status 406 NotAcceptable. /// /// /// This method will use the provided or it will get the @@ -238,29 +261,39 @@ namespace System.Net.Http } /// - /// Helper method that creates a with an instance containing the provided - /// . The given is used to find an instance of . + /// Helper method that creates a with an + /// instance containing the provided . The given is used + /// to find an instance of . /// /// The type of the value. /// The request. /// The status code of the created response. /// The value to wrap. Can be null. - /// The media type used to look up an instance of . + /// + /// The media type used to look up an instance of . + /// /// A response wrapping with . - public static HttpResponseMessage CreateResponse(this HttpRequestMessage request, HttpStatusCode statusCode, T value, string mediaType) + public static HttpResponseMessage CreateResponse( + this HttpRequestMessage request, + HttpStatusCode statusCode, + T value, + string mediaType) { return request.CreateResponse(statusCode, value, new MediaTypeHeaderValue(mediaType)); } /// - /// Helper method that creates a with an instance containing the provided - /// . The given is used to find an instance of . + /// Helper method that creates a with an + /// instance containing the provided . The given is used + /// to find an instance of . /// /// The type of the value. /// The request. /// The status code of the created response. /// The value to wrap. Can be null. - /// The media type used to look up an instance of . + /// + /// The media type used to look up an instance of . + /// /// A response wrapping with . public static HttpResponseMessage CreateResponse( [NotNull] this HttpRequestMessage request, @@ -287,8 +320,8 @@ namespace System.Net.Http } /// - /// Helper method that creates a with an instance containing the provided - /// and the given . + /// Helper method that creates a with an + /// instance containing the provided and the given . /// /// The type of the value. /// The request. @@ -306,15 +339,17 @@ namespace System.Net.Http } /// - /// Helper method that creates a with an instance containing the provided - /// and the given . + /// Helper method that creates a with an + /// instance containing the provided and the given . /// /// The type of the value. /// The request. /// The status code of the created response. /// The value to wrap. Can be null. /// The formatter to use. - /// The media type override to set on the response's content. Can be null. + /// + /// The media type override to set on the response's content. Can be null. + /// /// A response wrapping with . public static HttpResponseMessage CreateResponse( [NotNull] this HttpRequestMessage request, @@ -328,15 +363,17 @@ namespace System.Net.Http } /// - /// Helper method that creates a with an instance containing the provided - /// and the given . + /// Helper method that creates a with an + /// instance containing the provided and the given . /// /// The type of the value. /// The request. /// The status code of the created response. /// The value to wrap. Can be null. /// The formatter to use. - /// The media type override to set on the response's content. Can be null. + /// + /// The media type override to set on the response's content. Can be null. + /// /// A response wrapping with . public static HttpResponseMessage CreateResponse( [NotNull] this HttpRequestMessage request, diff --git a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/WebApiCompatShimOptionsSetup.cs b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/WebApiCompatShimOptionsSetup.cs index c9c26e7cc2..e4f774386f 100644 --- a/src/Microsoft.AspNet.Mvc.WebApiCompatShim/WebApiCompatShimOptionsSetup.cs +++ b/src/Microsoft.AspNet.Mvc.WebApiCompatShim/WebApiCompatShimOptionsSetup.cs @@ -6,9 +6,10 @@ using Microsoft.Framework.OptionsModel; namespace Microsoft.AspNet.Mvc.WebApiCompatShim { - public class WebApiCompatShimOptionsSetup : IConfigureOptions, IConfigureOptions + public class WebApiCompatShimOptionsSetup + : IConfigureOptions, IConfigureOptions { - public readonly static string DefaultAreaName = "api"; + public static readonly string DefaultAreaName = "api"; public int Order { diff --git a/src/Microsoft.AspNet.Mvc/IAfterCompileContext.cs b/src/Microsoft.AspNet.Mvc/IAfterCompileContext.cs new file mode 100644 index 0000000000..b5a5b296c1 --- /dev/null +++ b/src/Microsoft.AspNet.Mvc/IAfterCompileContext.cs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Microsoft.Framework.Runtime +{ + [AssemblyNeutral] + public interface IAfterCompileContext + { + CSharpCompilation CSharpCompilation { get; set; } + + IList Diagnostics { get; } + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Mvc/ICompileModule.cs b/src/Microsoft.AspNet.Mvc/ICompileModule.cs new file mode 100644 index 0000000000..2ae33db743 --- /dev/null +++ b/src/Microsoft.AspNet.Mvc/ICompileModule.cs @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Framework.Runtime +{ + [AssemblyNeutral] + public interface ICompileModule + { + void BeforeCompile(IBeforeCompileContext context); + + void AfterCompile(IAfterCompileContext context); + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Mvc/MvcServices.cs b/src/Microsoft.AspNet.Mvc/MvcServices.cs index 6c7b832146..64c9ec3d3d 100644 --- a/src/Microsoft.AspNet.Mvc/MvcServices.cs +++ b/src/Microsoft.AspNet.Mvc/MvcServices.cs @@ -26,19 +26,19 @@ namespace Microsoft.AspNet.Mvc { var describe = new ServiceDescriber(configuration); - // // Options and core services. - // + yield return describe.Transient, MvcOptionsSetup>(); yield return describe.Transient, RazorViewEngineOptionsSetup>(); yield return describe.Transient(); yield return describe.Transient(typeof(INestedProviderManager<>), typeof(NestedProviderManager<>)); - yield return describe.Transient(typeof(INestedProviderManagerAsync<>), typeof(NestedProviderManagerAsync<>)); + yield return describe.Transient( + typeof(INestedProviderManagerAsync<>), + typeof(NestedProviderManagerAsync<>)); yield return describe.Transient(); - // // Core action discovery, filters and action execution. - // + // These are consumed only when creating action descriptors, then they can be de-allocated yield return describe.Transient(); yield return describe.Transient(); @@ -74,9 +74,8 @@ namespace Microsoft.AspNet.Mvc yield return describe.Transient, DefaultFilterProvider>(); - // // Dataflow - ModelBinding, Validation and Formatting - // + yield return describe.Transient(); yield return describe.Scoped(); @@ -93,11 +92,10 @@ namespace Microsoft.AspNet.Mvc yield return describe.Transient(); yield return describe.Scoped(); yield return describe.Transient(); - yield return describe.Transient(); + yield return describe.Transient(); - // // Razor, Views and runtime compilation - // // The provider is inexpensive to initialize and provides ViewEngines that may require request // specific services. @@ -135,9 +133,7 @@ namespace Microsoft.AspNet.Mvc // Virtual path view factory needs to stay scoped so views can get get scoped services. yield return describe.Scoped(); - // // View and rendering helpers - // yield return describe.Transient(); yield return describe.Transient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>)); @@ -157,9 +153,7 @@ namespace Microsoft.AspNet.Mvc DefaultViewComponentInvokerProvider>(); yield return describe.Transient(); - // // Security and Authorization - // yield return describe.Transient(); yield return describe.Singleton(); @@ -167,9 +161,7 @@ namespace Microsoft.AspNet.Mvc yield return describe.Singleton(); - // // Api Description - // yield return describe.Singleton(); diff --git a/src/Microsoft.AspNet.Mvc/RazorPreCompileModule.cs b/src/Microsoft.AspNet.Mvc/RazorPreCompileModule.cs index e4f5298c1a..d749009194 100644 --- a/src/Microsoft.AspNet.Mvc/RazorPreCompileModule.cs +++ b/src/Microsoft.AspNet.Mvc/RazorPreCompileModule.cs @@ -48,7 +48,9 @@ namespace Microsoft.AspNet.Mvc } // TODO: KILL THIS - private static IServiceProvider BuildFallbackServiceProvider(IEnumerable services, IServiceProvider fallback) + private static IServiceProvider BuildFallbackServiceProvider( + IEnumerable services, + IServiceProvider fallback) { var sc = HostingServices.Create(fallback); sc.Add(services); @@ -58,7 +60,8 @@ namespace Microsoft.AspNet.Mvc && t.ServiceType != typeof(IServiceManifest) && t.ServiceType != typeof(IServiceProvider)) .Select(t => t.ServiceType).Distinct(); - sc.AddInstance(new ServiceManifest(manifestTypes, fallback.GetRequiredService())); + sc.AddInstance( + new ServiceManifest(manifestTypes, fallback.GetRequiredService())); return sc.BuildServiceProvider(); } @@ -77,22 +80,3 @@ namespace Microsoft.AspNet.Mvc } } } - -namespace Microsoft.Framework.Runtime -{ - [AssemblyNeutral] - public interface ICompileModule - { - void BeforeCompile(IBeforeCompileContext context); - - void AfterCompile(IAfterCompileContext context); - } - - [AssemblyNeutral] - public interface IAfterCompileContext - { - CSharpCompilation CSharpCompilation { get; set; } - - IList Diagnostics { get; } - } -} \ No newline at end of file diff --git a/test/Microsoft.AspNet.Mvc.Core.Test/ControllerTests.cs b/test/Microsoft.AspNet.Mvc.Core.Test/ControllerTests.cs index d6ee18e53a..91e33776d9 100644 --- a/test/Microsoft.AspNet.Mvc.Core.Test/ControllerTests.cs +++ b/test/Microsoft.AspNet.Mvc.Core.Test/ControllerTests.cs @@ -994,17 +994,16 @@ namespace Microsoft.AspNet.Mvc.Test // Assert binder.Verify(); } - + [Fact] public async Task TryUpdateModel_PredicateOverload_UsesPassedArguments() { // Arrange var modelName = "mymodel"; - Func includePredicate = - (context, propertyName) => - string.Equals(propertyName, "include1", StringComparison.OrdinalIgnoreCase) || - string.Equals(propertyName, "include2", StringComparison.OrdinalIgnoreCase); + Func includePredicate = (context, propertyName) => + string.Equals(propertyName, "include1", StringComparison.OrdinalIgnoreCase) || + string.Equals(propertyName, "include2", StringComparison.OrdinalIgnoreCase); var binder = new Mock(); var valueProvider = Mock.Of(); diff --git a/test/Microsoft.AspNet.Mvc.Core.Test/ViewComponents/ViewViewComponentResultTest.cs b/test/Microsoft.AspNet.Mvc.Core.Test/ViewComponents/ViewViewComponentResultTest.cs index 07f076ce18..db3158b473 100644 --- a/test/Microsoft.AspNet.Mvc.Core.Test/ViewComponents/ViewViewComponentResultTest.cs +++ b/test/Microsoft.AspNet.Mvc.Core.Test/ViewComponents/ViewViewComponentResultTest.cs @@ -227,7 +227,7 @@ namespace Microsoft.AspNet.Mvc var viewEngine = new Mock(MockBehavior.Strict); viewEngine.Setup(e => e.FindPartialView(It.IsAny(), It.IsAny())) .Returns(ViewEngineResult.NotFound( - "Components/Object/some-view", + "Components/Object/some-view", new[] { "view-location1", "view-location2" })) .Verifiable(); diff --git a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTests.cs b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTests.cs index 332e5b1d8c..5842d66890 100644 --- a/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTests.cs +++ b/test/Microsoft.AspNet.Mvc.FunctionalTests/ModelBindingTests.cs @@ -1056,7 +1056,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Assert var user = JsonConvert.DeserializeObject(response); - // Should not update any not explicitly mentioned properties. + // Should not update any not explicitly mentioned properties. Assert.NotEqual("SomeName", user.UserName); Assert.NotEqual(123, user.Key); @@ -1079,7 +1079,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests // Assert var user = JsonConvert.DeserializeObject(response); - // Should not update any not explicitly mentioned properties. + // Should not update any not explicitly mentioned properties. Assert.Equal("SomeName", user.UserName); Assert.Equal(123, user.Key); diff --git a/test/Microsoft.AspNet.Mvc.WebApiCompatShimTest/TestUtils/MediaTypeConstants.cs b/test/Microsoft.AspNet.Mvc.WebApiCompatShimTest/TestUtils/MediaTypeConstants.cs index 191406571b..f7a6e50d43 100644 --- a/test/Microsoft.AspNet.Mvc.WebApiCompatShimTest/TestUtils/MediaTypeConstants.cs +++ b/test/Microsoft.AspNet.Mvc.WebApiCompatShimTest/TestUtils/MediaTypeConstants.cs @@ -10,13 +10,20 @@ namespace System.Net.Http.Formatting /// internal static class MediaTypeConstants { - private static readonly MediaTypeHeaderValue _defaultApplicationXmlMediaType = new MediaTypeHeaderValue("application/xml"); - private static readonly MediaTypeHeaderValue _defaultTextXmlMediaType = new MediaTypeHeaderValue("text/xml"); - private static readonly MediaTypeHeaderValue _defaultApplicationJsonMediaType = new MediaTypeHeaderValue("application/json"); - private static readonly MediaTypeHeaderValue _defaultTextJsonMediaType = new MediaTypeHeaderValue("text/json"); - private static readonly MediaTypeHeaderValue _defaultApplicationOctetStreamMediaType = new MediaTypeHeaderValue("application/octet-stream"); - private static readonly MediaTypeHeaderValue _defaultApplicationFormUrlEncodedMediaType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); - private static readonly MediaTypeHeaderValue _defaultApplicationBsonMediaType = new MediaTypeHeaderValue("application/bson"); + private static readonly MediaTypeHeaderValue _defaultApplicationXmlMediaType = + new MediaTypeHeaderValue("application/xml"); + private static readonly MediaTypeHeaderValue _defaultTextXmlMediaType = + new MediaTypeHeaderValue("text/xml"); + private static readonly MediaTypeHeaderValue _defaultApplicationJsonMediaType = + new MediaTypeHeaderValue("application/json"); + private static readonly MediaTypeHeaderValue _defaultTextJsonMediaType = + new MediaTypeHeaderValue("text/json"); + private static readonly MediaTypeHeaderValue _defaultApplicationOctetStreamMediaType = + new MediaTypeHeaderValue("application/octet-stream"); + private static readonly MediaTypeHeaderValue _defaultApplicationFormUrlEncodedMediaType = + new MediaTypeHeaderValue("application/x-www-form-urlencoded"); + private static readonly MediaTypeHeaderValue _defaultApplicationBsonMediaType = + new MediaTypeHeaderValue("application/bson"); /// /// Gets a instance representing application/octet-stream. diff --git a/test/WebSites/ModelBindingWebSite/Controllers/FromAttributesController.cs b/test/WebSites/ModelBindingWebSite/Controllers/FromAttributesController.cs index 85d9d060a5..5f9a554447 100644 --- a/test/WebSites/ModelBindingWebSite/Controllers/FromAttributesController.cs +++ b/test/WebSites/ModelBindingWebSite/Controllers/FromAttributesController.cs @@ -44,7 +44,7 @@ namespace ModelBindingWebSite.Controllers } // User_FromForm has a FromForm property. - public User_FromForm MultipleFromFormParameterAndProperty(User_FromForm user, + public User_FromForm MultipleFromFormParameterAndProperty(User_FromForm user, [FromForm] Address defaultAddress) { user.HomeAddress = defaultAddress; diff --git a/test/WebSites/ModelBindingWebSite/Models/Department.cs b/test/WebSites/ModelBindingWebSite/Models/Department.cs index 238e6f7894..249ce62aca 100644 --- a/test/WebSites/ModelBindingWebSite/Models/Department.cs +++ b/test/WebSites/ModelBindingWebSite/Models/Department.cs @@ -5,7 +5,7 @@ namespace ModelBindingWebSite { public class Department { - // A single property marked with a binder metadata attribute makes it a binder metadata poco. + // A single property marked with a binder metadata attribute makes it a binder metadata poco. [FromTest] public string Name { get; set; } } diff --git a/test/WebSites/ModelBindingWebSite/Models/MixedUser_FromBody.cs b/test/WebSites/ModelBindingWebSite/Models/MixedUser_FromBody.cs index 8538419cd2..bf3eea2d3c 100644 --- a/test/WebSites/ModelBindingWebSite/Models/MixedUser_FromBody.cs +++ b/test/WebSites/ModelBindingWebSite/Models/MixedUser_FromBody.cs @@ -16,7 +16,7 @@ namespace ModelBindingWebSite [FromQuery] public Address ShippingAddress { get; set; } - // Should get it from the first value provider which + // Should get it from the first value provider which // can provide values for this. public Address DefaultAddress { get; set; } }