More Stylecop cleanup for ModelBinding and Razor

This commit is contained in:
Pranav K 2014-06-09 14:27:12 -07:00
parent 59e419ba0a
commit cc0dadc6b6
20 changed files with 82 additions and 86 deletions

View File

@ -19,7 +19,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
IEnumerable<KeyValuePair<TKey, TValue>> incomingElements,
Func<IDictionary<TKey, TValue>> creator)
{
IDictionary<TKey, TValue> dictionary = bindingContext.Model as IDictionary<TKey, TValue>;
var dictionary = bindingContext.Model as IDictionary<TKey, TValue>;
if (dictionary == null || dictionary.IsReadOnly)
{
dictionary = creator();

View File

@ -39,7 +39,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Internal
}
else
{
char charAfterPrefix = key[prefix.Length];
var charAfterPrefix = key[prefix.Length];
switch (charAfterPrefix)
{
case '[':

View File

@ -67,7 +67,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
Func<object> modelAccessor = null;
if (container != null)
{
Func<object, object> propertyGetter = propertyInfo.ValueAccessor;
var propertyGetter = propertyInfo.ValueAccessor;
modelAccessor = () => propertyGetter(container);
}
yield return CreatePropertyMetadata(modelAccessor, propertyInfo);

View File

@ -185,17 +185,6 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
return PropertyName ?? ModelType.Name;
}
// TODO: Revive ModelValidators
//public virtual IEnumerable<ModelValidator> GetValidators(IEnumerable<ModelValidatorProvider> validatorProviders)
//{
// if (validatorProviders == null)
// {
// throw Error.ArgumentNull("validatorProviders");
// }
// return validatorProviders.SelectMany(provider => provider.GetValidators(this, validatorProviders));
//}
protected virtual string ComputeSimpleDisplayText()
{
if (Model == null)
@ -228,10 +217,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
return Convert.ToString(firstProperty.Model, CultureInfo.CurrentCulture);
}
private static EfficientTypePropertyKey<Type, string> CreateCacheKey(Type containerType, Type modelType, string propertyName)
private static EfficientTypePropertyKey<Type, string> CreateCacheKey(Type containerType,
Type modelType,
string propertyName)
{
// If metadata is for a property then containerType != null && propertyName != null
// If metadata is for a type then containerType == null && propertyName == null, so we have to use modelType for the cache key.
// If metadata is for a type then containerType == null && propertyName == null,
// so we have to use modelType for the cache key.
return new EfficientTypePropertyKey<Type, string>(containerType ?? modelType, propertyName);
}
}

View File

@ -25,8 +25,9 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
private IEnumerable<IModelValidator> GetValidatorsForProperty(ModelMetadata metadata)
{
var propertyName = metadata.PropertyName;
var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase;
var property = metadata.ContainerType
.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
.GetProperty(propertyName, bindingFlags);
if (property == null)
{

View File

@ -19,7 +19,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
{
var errorMessage = ((CompareAttributeWrapper)Attribute).FormatErrorMessage(context);
var clientRule = new ModelClientValidationEqualToRule(errorMessage,
FormatPropertyForClientValidation(Attribute.OtherProperty));
FormatPropertyForClientValidation(Attribute.OtherProperty));
return new[] { clientRule };
}
@ -58,9 +58,9 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
private string GetOtherPropertyDisplayName(ClientModelValidationContext context)
{
// The System.ComponentModel.DataAnnotations.CompareAttribute doesn't populate the OtherPropertyDisplayName
// until after IsValid() is called. Therefore, by the time we get the error message for client validation,
// the display name is not populated and won't be used.
// The System.ComponentModel.DataAnnotations.CompareAttribute doesn't populate the
// OtherPropertyDisplayName until after IsValid() is called. Therefore, by the time we get
// the error message for client validation, the display name is not populated and won't be used.
var metadata = context.ModelMetadata;
var otherPropertyDisplayName = OtherPropertyDisplayName;
if (otherPropertyDisplayName == null && metadata.ContainerType != null)

View File

@ -50,7 +50,8 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
}
}
private static ModelValidationResult CreateSubPropertyResult(ModelMetadata propertyMetadata, ModelValidationResult propertyResult)
private static ModelValidationResult CreateSubPropertyResult(ModelMetadata propertyMetadata,
ModelValidationResult propertyResult)
{
return new ModelValidationResult(propertyMetadata.PropertyName + '.' + propertyResult.MemberName,
propertyResult.Message);

View File

@ -37,13 +37,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
var result = Attribute.GetValidationResult(metadata.Model, context);
if (result != ValidationResult.Success)
{
// ModelValidationResult.MemberName is used by invoking validators (such as ModelValidator) to
// construct the ModelKey for ModelStateDictionary. When validating at type level we want to append the
// returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the
// ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want
// (person.Name.Name). However the invoking validator does not have a way to distinguish between these two
// cases. Consequently we'll only set MemberName if this validation returns a MemberName that is different
// from the property being validated.
// ModelValidationResult.MemberName is used by invoking validators (such as ModelValidator) to
// construct the ModelKey for ModelStateDictionary. When validating at type level we want to append
// the returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the
// ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want
// (person.Name.Name). However the invoking validator does not have a way to distinguish between these
// two cases. Consequently we'll only set MemberName if this validation returns a MemberName that is
// different from the property being validated.
var errorMemberName = result.MemberNames.FirstOrDefault();
if (string.Equals(errorMemberName, memberName, StringComparison.Ordinal))

View File

@ -48,7 +48,8 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
set { _addImplicitRequiredAttributeForValueTypes = value; }
}
protected override IEnumerable<IModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<Attribute> attributes)
protected override IEnumerable<IModelValidator> GetValidators(ModelMetadata metadata,
IEnumerable<Attribute> attributes)
{
var results = new List<IModelValidator>();
@ -104,9 +105,10 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
return dict;
}
private static void AddValidationAttributeAdapter(Dictionary<Type, DataAnnotationsModelValidationFactory> dictionary,
Type validationAttributeType,
DataAnnotationsModelValidationFactory factory)
private static void AddValidationAttributeAdapter(
Dictionary<Type, DataAnnotationsModelValidationFactory> dictionary,
Type validationAttributeType,
DataAnnotationsModelValidationFactory factory)
{
if (validationAttributeType != null)
{
@ -114,9 +116,10 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
}
}
private static void AddDataTypeAttributeAdapter(Dictionary<Type, DataAnnotationsModelValidationFactory> dictionary,
Type attributeType,
string ruleName)
private static void AddDataTypeAttributeAdapter(
Dictionary<Type, DataAnnotationsModelValidationFactory> dictionary,
Type attributeType,
string ruleName)
{
AddValidationAttributeAdapter(
dictionary,

View File

@ -10,7 +10,8 @@ using System.Runtime.Serialization;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
/// <summary>
/// This <see cref="ModelValidatorProvider"/> provides a required ModelValidator for members marked as [DataMember(IsRequired=true)].
/// This <see cref="ModelValidatorProvider"/> provides a required ModelValidator for members marked
/// as [DataMember(IsRequired=true)].
/// </summary>
public class DataMemberModelValidatorProvider : AssociatedValidatorProvider
{
@ -38,10 +39,10 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
if (dataMemberAttribute != null)
{
// isDataContract == true iff the container type has at least one DataContractAttribute
bool isDataContract = containerType.GetTypeInfo()
.GetCustomAttributes()
.OfType<DataContractAttribute>()
.Any();
var isDataContract = containerType.GetTypeInfo()
.GetCustomAttributes()
.OfType<DataContractAttribute>()
.Any();
if (isDataContract && dataMemberAttribute.IsRequired)
{
return true;

View File

@ -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.AspNet.Routing;
using System.Globalization;
using Microsoft.AspNet.Routing;
namespace Microsoft.AspNet.Mvc.ModelBinding
{

View File

@ -108,7 +108,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
if (valueAsArray != null)
{
// case 1: both destination + source type are arrays, so convert each element
IList converted = Array.CreateInstance(destinationElementType, valueAsArray.Length);
var converted = (IList)Array.CreateInstance(destinationElementType, valueAsArray.Length);
for (var i = 0; i < valueAsArray.Length; i++)
{
converted[i] = ConvertSimpleType(culture, valueAsArray.GetValue(i), destinationElementType);
@ -117,9 +117,10 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
}
else
{
// case 2: destination type is array but source is single element, so wrap element in array + convert
// case 2: destination type is array but source is single element, so wrap element in
// array + convert
var element = ConvertSimpleType(culture, value, destinationElementType);
IList converted = Array.CreateInstance(destinationElementType, 1);
var converted = (IList)Array.CreateInstance(destinationElementType, 1);
converted[0] = element;
return converted;
}

View File

@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.AspNet.Mvc.Razor
{
@ -21,25 +20,23 @@ namespace Microsoft.AspNet.Mvc.Razor
public bool Literal { get; private set; }
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "We are using tuples here to avoid dependencies from Razor to WebPages")]
public static AttributeValue FromTuple(Tuple<Tuple<string, int>, Tuple<object, int>, bool> value)
{
return new AttributeValue(value.Item1, value.Item2, value.Item3);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "We are using tuples here to avoid dependencies from Razor to WebPages")]
public static AttributeValue FromTuple(Tuple<Tuple<string, int>, Tuple<string, int>, bool> value)
{
return new AttributeValue(value.Item1, new PositionTagged<object>(value.Item2.Item1, value.Item2.Item2), value.Item3);
return new AttributeValue(value.Item1,
new PositionTagged<object>(value.Item2.Item1, value.Item2.Item2),
value.Item3);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "We are using tuples here to avoid dependencies from Razor to WebPages")]
public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<object, int>, bool> value)
{
return FromTuple(value);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "We are using tuples here to avoid dependencies from Razor to WebPages")]
public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<string, int>, bool> value)
{
return FromTuple(value);

View File

@ -19,12 +19,12 @@ namespace Microsoft.AspNet.Mvc.Razor
public CompilationResult GetOrAdd(IFileInfo file, Func<CompilationResult> compile)
{
// Generate a content id
string contentId = file.PhysicalPath + '|' + file.LastModified.Ticks;
var contentId = file.PhysicalPath + '|' + file.LastModified.Ticks;
Type compiledType;
if (!_cache.TryGetValue(contentId, out compiledType))
{
CompilationResult result = compile();
var result = compile();
_cache.TryAdd(contentId, result.CompiledType);
return result;

View File

@ -2,23 +2,23 @@
// 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.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.Framework.Runtime;
namespace Microsoft.AspNet.Mvc.Razor.Compilation
{
public class RoslynCompilationService : ICompilationService
{
private static readonly ConcurrentDictionary<string, MetadataReference> _metadataFileCache = new ConcurrentDictionary<string, MetadataReference>(StringComparer.OrdinalIgnoreCase);
private static readonly ConcurrentDictionary<string, MetadataReference> _metadataFileCache =
new ConcurrentDictionary<string, MetadataReference>(StringComparer.OrdinalIgnoreCase);
private readonly ILibraryManager _libraryManager;
private readonly IApplicationEnvironment _environment;
private readonly IAssemblyLoaderEngine _loader;
@ -50,13 +50,13 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
{
using (var pdb = new MemoryStream())
{
EmitResult result = null;
EmitResult result;
if (PlatformHelper.IsMono)
{
result = compilation.Emit(ms, pdbStream: null);
}
else
else
{
result = compilation.Emit(ms, pdbStream: pdb);
}
@ -65,12 +65,15 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
{
var formatter = new DiagnosticFormatter();
var messages = result.Diagnostics.Where(IsError).Select(d => GetCompilationMessage(formatter, d)).ToList();
var messages = result.Diagnostics
.Where(IsError)
.Select(d => GetCompilationMessage(formatter, d))
.ToList();
return CompilationResult.Failed(content, messages);
}
Assembly assembly = null;
Assembly assembly;
ms.Seek(0, SeekOrigin.Begin);
if (PlatformHelper.IsMono)
@ -86,7 +89,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
var type = assembly.GetExportedTypes()
.First();
return CompilationResult.Successful(String.Empty, type);
return CompilationResult.Successful(string.Empty, type);
}
}
}
@ -121,7 +124,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
private MetadataReference CreateMetadataFileReference(string path)
{
return _metadataFileCache.GetOrAdd(path, _ =>
return _metadataFileCache.GetOrAdd(path, _ =>
{
// TODO: What about access to the file system? We need to be able to
// read files from anywhere on disk, not just under the web root

View File

@ -7,7 +7,8 @@ namespace System.Collections.Generic
{
internal static class DictionaryExtensions
{
public static T GetValueOrDefault<T>([NotNull] this IDictionary<string, object> dictionary, [NotNull] string key)
public static T GetValueOrDefault<T>([NotNull] this IDictionary<string, object> dictionary,
[NotNull] string key)
{
object valueAsObject;
if (dictionary.TryGetValue(key, out valueAsObject))

View File

@ -29,7 +29,7 @@ namespace Microsoft.AspNet.Mvc.Razor
_appRoot = EnsureTrailingSlash(environment.ApplicationBasePath);
}
public CompilationResult Compile([NotNull]IFileInfo file)
public CompilationResult Compile([NotNull] IFileInfo file)
{
return _cache.GetOrAdd(file, () => CompileCore(file));
}
@ -38,7 +38,7 @@ namespace Microsoft.AspNet.Mvc.Razor
public CompilationResult CompileCore(IFileInfo file)
{
GeneratorResults results;
using (Stream inputStream = file.CreateReadStream())
using (var inputStream = file.CreateReadStream())
{
Contract.Assert(file.PhysicalPath.StartsWith(_appRoot, StringComparison.OrdinalIgnoreCase));
var rootRelativePath = file.PhysicalPath.Substring(_appRoot.Length);

View File

@ -159,7 +159,6 @@ namespace Microsoft.AspNet.Mvc.Razor
if (helperResult != null)
{
helperResult.WriteTo(writer);
}
else
{
@ -203,8 +202,8 @@ namespace Microsoft.AspNet.Mvc.Razor
PositionTagged<string> suffix,
params AttributeValue[] values)
{
bool first = true;
bool wroteSomething = false;
var first = true;
var wroteSomething = false;
if (values.Length == 0)
{
// Explicitly empty attribute, so write the prefix and suffix
@ -213,11 +212,11 @@ namespace Microsoft.AspNet.Mvc.Razor
}
else
{
for (int i = 0; i < values.Length; i++)
for (var i = 0; i < values.Length; i++)
{
AttributeValue attrVal = values[i];
PositionTagged<object> val = attrVal.Value;
PositionTagged<string> next = i == values.Length - 1 ?
var attrVal = values[i];
var val = attrVal.Value;
var next = i == values.Length - 1 ?
suffix : // End of the list, grab the suffix
values[i + 1].Prefix; // Still in the list, grab the next prefix
@ -228,12 +227,11 @@ namespace Microsoft.AspNet.Mvc.Razor
}
// The special cases here are that the value we're writing might already be a string, or that the
// value might be a bool. If the value is the bool 'true' we want to write the attribute name instead
// of the string 'true'. If the value is the bool 'false' we don't want to write anything.
//
// Otherwise the value is another object (perhaps an HtmlString), and we'll ask it to format itself.
// value might be a bool. If the value is the bool 'true' we want to write the attribute name
// instead of the string 'true'. If the value is the bool 'false' we don't want to write anything.
// Otherwise the value is another object (perhaps an HtmlString) and we'll ask it to format itself.
string stringValue;
bool? boolValue = val.Value as bool?;
var boolValue = val.Value as bool?;
if (boolValue == true)
{
stringValue = name;
@ -258,7 +256,7 @@ namespace Microsoft.AspNet.Mvc.Razor
}
// Calculate length of the source span by the position of the next value (or suffix)
int sourceLength = next.Position - attrVal.Value.Position;
var sourceLength = next.Position - attrVal.Value.Position;
if (attrVal.Literal)
{
@ -360,7 +358,8 @@ namespace Microsoft.AspNet.Mvc.Razor
{
if (BodyContent != null)
{
var sectionsNotRendered = PreviousSectionWriters.Keys.Except(_renderedSections, StringComparer.OrdinalIgnoreCase);
var sectionsNotRendered = PreviousSectionWriters.Keys.Except(_renderedSections,
StringComparer.OrdinalIgnoreCase);
if (sectionsNotRendered.Any())
{
var sectionNames = String.Join(", ", sectionsNotRendered);

View File

@ -89,7 +89,6 @@ namespace Microsoft.AspNet.Mvc.Razor
private static bool IsSpecificPath(string name)
{
char c = name[0];
return name[0] == '~' || name[0] == '/';
}
@ -109,8 +108,7 @@ namespace Microsoft.AspNet.Mvc.Razor
}
var formattedPaths = unformattedPaths.Select(path =>
string.Format(CultureInfo.InvariantCulture, path, viewName, controllerName, areaName)
);
string.Format(CultureInfo.InvariantCulture, path, viewName, controllerName, areaName));
return formattedPaths;
}

View File

@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.FileSystems;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Framework.DependencyInjection;
@ -34,7 +33,7 @@ namespace Microsoft.AspNet.Mvc.Razor
IFileInfo fileInfo;
if (_fileSystem.TryGetFileInfo(virtualPath, out fileInfo))
{
CompilationResult result = _compilationService.Compile(fileInfo);
var result = _compilationService.Compile(fileInfo);
return (IView)_activator.CreateInstance(_serviceProvider, result.CompiledType);
}