Replacing NotNullAttribute with thrown exceptions

This commit is contained in:
Pranav K 2015-09-21 07:27:50 -07:00
parent 00c436b0e1
commit 66a04c2fd6
72 changed files with 1368 additions and 329 deletions

View File

@ -8,7 +8,6 @@ using System.Reflection;
using Microsoft.AspNet.JsonPatch.Exceptions;
using Microsoft.AspNet.JsonPatch.Helpers;
using Microsoft.AspNet.JsonPatch.Operations;
using Microsoft.Framework.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
@ -23,9 +22,14 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// <param name="contractResolver">The <see cref="IContractResolver"/>.</param>
/// <param name="logErrorAction">The <see cref="Action"/> for logging <see cref="JsonPatchError"/>.</param>
public ObjectAdapter(
[NotNull] IContractResolver contractResolver,
IContractResolver contractResolver,
Action<JsonPatchError> logErrorAction)
{
if (contractResolver == null)
{
throw new ArgumentNullException(nameof(contractResolver));
}
ContractResolver = contractResolver;
LogErrorAction = logErrorAction;
}
@ -100,8 +104,18 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// </summary>
/// <param name="operation">The add operation.</param>
/// <param name="objectToApplyTo">Object to apply the operation to.</param>
public void Add([NotNull] Operation operation, [NotNull] object objectToApplyTo)
public void Add(Operation operation, object objectToApplyTo)
{
if (operation == null)
{
throw new ArgumentNullException(nameof(operation));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
Add(operation.path, operation.value, objectToApplyTo, operation);
}
@ -110,11 +124,26 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// This method allows code reuse yet reporting the correct operation on error
/// </summary>
private void Add(
[NotNull] string path,
string path,
object value,
[NotNull] object objectToApplyTo,
[NotNull] Operation operationToReport)
object objectToApplyTo,
Operation operationToReport)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (operationToReport == null)
{
throw new ArgumentNullException(nameof(operationToReport));
}
// first up: if the path ends in a numeric value, we're inserting in a list and
// that value represents the position; if the path ends in "-", we're appending
// to the list.
@ -357,8 +386,18 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// </summary>
/// <param name="operation">The move operation.</param>
/// <param name="objectToApplyTo">Object to apply the operation to.</param>
public void Move([NotNull] Operation operation, [NotNull] object objectToApplyTo)
public void Move(Operation operation, object objectToApplyTo)
{
if (operation == null)
{
throw new ArgumentNullException(nameof(operation));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
var valueAtFromLocationResult = GetValueAtLocation(operation.from, objectToApplyTo, operation);
if (valueAtFromLocationResult.HasError)
@ -399,8 +438,18 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// </summary>
/// <param name="operation">The remove operation.</param>
/// <param name="objectToApplyTo">Object to apply the operation to.</param>
public void Remove([NotNull] Operation operation, [NotNull] object objectToApplyTo)
public void Remove(Operation operation, object objectToApplyTo)
{
if (operation == null)
{
throw new ArgumentNullException(nameof(operation));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
Remove(operation.path, objectToApplyTo, operation);
}
@ -661,8 +710,18 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// </summary>
/// <param name="operation">The replace operation.</param>
/// <param name="objectToApplyTo">Object to apply the operation to.</param>
public void Replace([NotNull] Operation operation, [NotNull] object objectToApplyTo)
public void Replace(Operation operation, object objectToApplyTo)
{
if (operation == null)
{
throw new ArgumentNullException(nameof(operation));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
var removeResult = Remove(operation.path, objectToApplyTo, operation);
if (removeResult.HasError)
@ -672,7 +731,7 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
}
if (!removeResult.HasError && removeResult.ActualType == null)
{
{
// the remove operation completed succesfully, but we could not determine the type.
LogError(new JsonPatchError(
objectToApplyTo,
@ -718,8 +777,18 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// </summary>
/// <param name="operation">The copy operation.</param>
/// <param name="objectToApplyTo">Object to apply the operation to.</param>
public void Copy([NotNull] Operation operation, [NotNull] object objectToApplyTo)
public void Copy(Operation operation, object objectToApplyTo)
{
if (operation == null)
{
throw new ArgumentNullException(nameof(operation));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
// get value at from location and add that value to the path location
var valueAtFromLocationResult = GetValueAtLocation(operation.from, objectToApplyTo, operation);
@ -743,10 +812,25 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
/// <param name="operationToReport">Operation to report in case of an error</param>
/// <returns>GetValueResult containing value and a bool signifying a possible error</returns>
private GetValueResult GetValueAtLocation(
[NotNull] string location,
[NotNull] object objectToGetValueFrom,
[NotNull] Operation operationToReport)
string location,
object objectToGetValueFrom,
Operation operationToReport)
{
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
if (objectToGetValueFrom == null)
{
throw new ArgumentNullException(nameof(objectToGetValueFrom));
}
if (operationToReport == null)
{
throw new ArgumentNullException(nameof(operationToReport));
}
// get path result
var pathResult = GetActualPropertyPath(
location,
@ -801,7 +885,7 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
// get the array
var array = (IList)treeAnalysisResult.Container.GetValueForCaseInsensitiveKey(
treeAnalysisResult.PropertyPathInParent);
if (positionAsInteger >= array.Count)
{
LogError(new JsonPatchError(
@ -815,12 +899,12 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
if (getAtEndOfList)
{
return new GetValueResult(array[array.Count-1], false);
return new GetValueResult(array[array.Count - 1], false);
}
else
{
return new GetValueResult(array[positionAsInteger], false);
}
}
}
else
{
@ -829,7 +913,7 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
treeAnalysisResult.PropertyPathInParent);
return new GetValueResult(propertyValueAtLocation, false);
}
}
}
else
{
@ -846,7 +930,7 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
Resources.FormatInvalidIndexForArrayProperty(operationToReport.op, location)));
return new GetValueResult(null, true);
}
if (!patchProperty.Property.Readable)
{
LogError(new JsonPatchError(
@ -877,7 +961,7 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
else
{
return new GetValueResult(array[positionAsInteger], false);
}
}
}
else
{
@ -886,9 +970,9 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
LogError(new JsonPatchError(
objectToGetValueFrom,
operationToReport,
Resources.FormatCannotReadProperty(
Resources.FormatCannotReadProperty(
location)));
return new GetValueResult(null, true);
return new GetValueResult(null, true);
}
var propertyValueAtLocation = patchProperty.Property.ValueProvider
@ -965,10 +1049,25 @@ namespace Microsoft.AspNet.JsonPatch.Adapters
}
private ActualPropertyPathResult GetActualPropertyPath(
[NotNull] string propertyPath,
[NotNull] object objectToApplyTo,
[NotNull] Operation operationToReport)
string propertyPath,
object objectToApplyTo,
Operation operationToReport)
{
if (propertyPath == null)
{
throw new ArgumentNullException(nameof(propertyPath));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (operationToReport == null)
{
throw new ArgumentNullException(nameof(operationToReport));
}
if (propertyPath.EndsWith("/-"))
{
return new ActualPropertyPathResult(-1, propertyPath.Substring(0, propertyPath.Length - 2), true);

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal;
using System;
using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNet.JsonPatch
@ -14,8 +14,18 @@ namespace Microsoft.AspNet.JsonPatch
/// <summary>
/// Initializes a new instance.
/// </summary>
public JsonPatchProperty([NotNull] JsonProperty property, [NotNull] object parent)
public JsonPatchProperty(JsonProperty property, object parent)
{
if (property == null)
{
throw new ArgumentNullException(nameof(property));
}
if (parent == null)
{
throw new ArgumentNullException(nameof(parent));
}
Property = property;
Parent = parent;
}

View File

@ -1,14 +1,12 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. 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 Microsoft.AspNet.JsonPatch.Adapters;
using Microsoft.AspNet.JsonPatch.Converters;
using Microsoft.AspNet.JsonPatch.Exceptions;
using Microsoft.AspNet.JsonPatch.Helpers;
using Microsoft.AspNet.JsonPatch.Operations;
using Microsoft.Framework.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
@ -24,15 +22,25 @@ namespace Microsoft.AspNet.JsonPatch
[JsonIgnore]
public IContractResolver ContractResolver { get; set; }
public JsonPatchDocument()
{
Operations = new List<Operation>();
ContractResolver = new DefaultContractResolver();
ContractResolver = new DefaultContractResolver();
}
public JsonPatchDocument([NotNull] List<Operation> operations, [NotNull] IContractResolver contractResolver)
public JsonPatchDocument(List<Operation> operations, IContractResolver contractResolver)
{
if (operations == null)
{
throw new ArgumentNullException(nameof(operations));
}
if (contractResolver == null)
{
throw new ArgumentNullException(nameof(contractResolver));
}
Operations = operations;
ContractResolver = contractResolver;
}
@ -44,8 +52,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <param name="value">value</param>
/// <returns></returns>
public JsonPatchDocument Add([NotNull] string path, object value)
public JsonPatchDocument Add(string path, object value)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation("add", PathHelpers.NormalizePath(path), null, value));
return this;
}
@ -56,8 +69,13 @@ namespace Microsoft.AspNet.JsonPatch
/// </summary>
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument Remove([NotNull] string path)
public JsonPatchDocument Remove(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation("remove", PathHelpers.NormalizePath(path), null, null));
return this;
}
@ -69,8 +87,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <param name="value">value</param>
/// <returns></returns>
public JsonPatchDocument Replace([NotNull] string path, object value)
public JsonPatchDocument Replace(string path, object value)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation("replace", PathHelpers.NormalizePath(path), null, value));
return this;
}
@ -82,8 +105,18 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="from">source location</param>
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument Move([NotNull] string from, [NotNull] string path)
public JsonPatchDocument Move(string from, string path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation("move", PathHelpers.NormalizePath(path), PathHelpers.NormalizePath(from)));
return this;
}
@ -95,8 +128,18 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="from">source location</param>
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument Copy([NotNull] string from, [NotNull] string path)
public JsonPatchDocument Copy(string from, string path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation("copy", PathHelpers.NormalizePath(path), PathHelpers.NormalizePath(from)));
return this;
}
@ -105,8 +148,13 @@ namespace Microsoft.AspNet.JsonPatch
/// Apply this JsonPatchDocument
/// </summary>
/// <param name="objectToApplyTo">Object to apply the JsonPatchDocument to</param>
public void ApplyTo([NotNull] object objectToApplyTo)
public void ApplyTo(object objectToApplyTo)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
ApplyTo(objectToApplyTo, new ObjectAdapter(ContractResolver, logErrorAction: null));
}
@ -115,8 +163,13 @@ namespace Microsoft.AspNet.JsonPatch
/// </summary>
/// <param name="objectToApplyTo">Object to apply the JsonPatchDocument to</param>
/// <param name="logErrorAction">Action to log errors</param>
public void ApplyTo([NotNull] object objectToApplyTo, Action<JsonPatchError> logErrorAction)
public void ApplyTo(object objectToApplyTo, Action<JsonPatchError> logErrorAction)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
ApplyTo(objectToApplyTo, new ObjectAdapter(ContractResolver, logErrorAction));
}
@ -125,15 +178,25 @@ namespace Microsoft.AspNet.JsonPatch
/// </summary>
/// <param name="objectToApplyTo">Object to apply the JsonPatchDocument to</param>
/// <param name="adapter">IObjectAdapter instance to use when applying</param>
public void ApplyTo([NotNull] object objectToApplyTo, [NotNull] IObjectAdapter adapter)
public void ApplyTo(object objectToApplyTo, IObjectAdapter adapter)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (adapter == null)
{
throw new ArgumentNullException(nameof(adapter));
}
// apply each operation in order
foreach (var op in Operations)
{
op.Apply(objectToApplyTo, adapter);
}
}
IList<Operation> IJsonPatchDocument.GetOperations()
{
var allOps = new List<Operation>();

View File

@ -8,7 +8,6 @@ using Microsoft.AspNet.JsonPatch.Adapters;
using Microsoft.AspNet.JsonPatch.Converters;
using Microsoft.AspNet.JsonPatch.Helpers;
using Microsoft.AspNet.JsonPatch.Operations;
using Microsoft.Framework.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
@ -33,8 +32,18 @@ namespace Microsoft.AspNet.JsonPatch
}
// Create from list of operations
public JsonPatchDocument([NotNull] List<Operation<TModel>> operations, [NotNull] IContractResolver contractResolver)
public JsonPatchDocument(List<Operation<TModel>> operations, IContractResolver contractResolver)
{
if (operations == null)
{
throw new ArgumentNullException(nameof(operations));
}
if (contractResolver == null)
{
throw new ArgumentNullException(nameof(contractResolver));
}
Operations = operations;
ContractResolver = contractResolver;
}
@ -47,8 +56,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <param name="value">value</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Add<TProp>([NotNull] Expression<Func<TModel, TProp>> path, TProp value)
public JsonPatchDocument<TModel> Add<TProp>(Expression<Func<TModel, TProp>> path, TProp value)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"add",
ExpressionHelpers.GetPath(path).ToLowerInvariant(),
@ -67,10 +81,15 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="position">position</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Add<TProp>(
[NotNull] Expression<Func<TModel, IList<TProp>>> path,
Expression<Func<TModel, IList<TProp>>> path,
TProp value,
int position)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"add",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/" + position,
@ -87,8 +106,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <param name="value">value</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Add<TProp>([NotNull] Expression<Func<TModel, IList<TProp>>> path, TProp value)
public JsonPatchDocument<TModel> Add<TProp>(Expression<Func<TModel, IList<TProp>>> path, TProp value)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"add",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/-",
@ -104,8 +128,13 @@ namespace Microsoft.AspNet.JsonPatch
/// </summary>
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Remove<TProp>([NotNull] Expression<Func<TModel, TProp>> path)
public JsonPatchDocument<TModel> Remove<TProp>(Expression<Func<TModel, TProp>> path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>("remove", ExpressionHelpers.GetPath(path).ToLowerInvariant(), from: null));
return this;
@ -118,8 +147,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <param name="position">position</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Remove<TProp>([NotNull] Expression<Func<TModel, IList<TProp>>> path, int position)
public JsonPatchDocument<TModel> Remove<TProp>(Expression<Func<TModel, IList<TProp>>> path, int position)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"remove",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/" + position,
@ -134,8 +168,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <typeparam name="TProp">value type</typeparam>
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Remove<TProp>([NotNull] Expression<Func<TModel, IList<TProp>>> path)
public JsonPatchDocument<TModel> Remove<TProp>(Expression<Func<TModel, IList<TProp>>> path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"remove",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/-",
@ -151,8 +190,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <param name="value">value</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Replace<TProp>([NotNull] Expression<Func<TModel, TProp>> path, TProp value)
public JsonPatchDocument<TModel> Replace<TProp>(Expression<Func<TModel, TProp>> path, TProp value)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"replace",
ExpressionHelpers.GetPath(path).ToLowerInvariant(),
@ -170,9 +214,14 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="value">value</param>
/// <param name="position">position</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Replace<TProp>([NotNull] Expression<Func<TModel, IList<TProp>>> path,
public JsonPatchDocument<TModel> Replace<TProp>(Expression<Func<TModel, IList<TProp>>> path,
TProp value, int position)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"replace",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/" + position,
@ -189,8 +238,13 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <param name="value">value</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Replace<TProp>([NotNull] Expression<Func<TModel, IList<TProp>>> path, TProp value)
public JsonPatchDocument<TModel> Replace<TProp>(Expression<Func<TModel, IList<TProp>>> path, TProp value)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"replace",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/-",
@ -208,9 +262,19 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Move<TProp>(
[NotNull] Expression<Func<TModel, TProp>> from,
[NotNull] Expression<Func<TModel, TProp>> path)
Expression<Func<TModel, TProp>> from,
Expression<Func<TModel, TProp>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"move",
ExpressionHelpers.GetPath(path).ToLowerInvariant(),
@ -228,10 +292,20 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Move<TProp>(
[NotNull] Expression<Func<TModel, IList<TProp>>> from,
Expression<Func<TModel, IList<TProp>>> from,
int positionFrom,
[NotNull] Expression<Func<TModel, TProp>> path)
Expression<Func<TModel, TProp>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"move",
ExpressionHelpers.GetPath(path).ToLowerInvariant(),
@ -249,10 +323,20 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="positionTo">position</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Move<TProp>(
[NotNull] Expression<Func<TModel, TProp>> from,
[NotNull] Expression<Func<TModel, IList<TProp>>> path,
Expression<Func<TModel, TProp>> from,
Expression<Func<TModel, IList<TProp>>> path,
int positionTo)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"move",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/" + positionTo,
@ -271,11 +355,21 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="positionTo">position (target)</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Move<TProp>(
[NotNull] Expression<Func<TModel, IList<TProp>>> from,
Expression<Func<TModel, IList<TProp>>> from,
int positionFrom,
[NotNull] Expression<Func<TModel, IList<TProp>>> path,
Expression<Func<TModel, IList<TProp>>> path,
int positionTo)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"move",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/" + positionTo,
@ -293,10 +387,20 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Move<TProp>(
[NotNull] Expression<Func<TModel, IList<TProp>>> from,
Expression<Func<TModel, IList<TProp>>> from,
int positionFrom,
[NotNull] Expression<Func<TModel, IList<TProp>>> path)
Expression<Func<TModel, IList<TProp>>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"move",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/-",
@ -313,9 +417,19 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Move<TProp>(
[NotNull] Expression<Func<TModel, TProp>> from,
[NotNull] Expression<Func<TModel, IList<TProp>>> path)
Expression<Func<TModel, TProp>> from,
Expression<Func<TModel, IList<TProp>>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"move",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/-",
@ -332,9 +446,19 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Copy<TProp>(
[NotNull] Expression<Func<TModel, TProp>> from,
[NotNull] Expression<Func<TModel, TProp>> path)
Expression<Func<TModel, TProp>> from,
Expression<Func<TModel, TProp>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"copy",
ExpressionHelpers.GetPath(path).ToLowerInvariant()
@ -352,10 +476,20 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Copy<TProp>(
[NotNull] Expression<Func<TModel, IList<TProp>>> from,
Expression<Func<TModel, IList<TProp>>> from,
int positionFrom,
[NotNull] Expression<Func<TModel, TProp>> path)
Expression<Func<TModel, TProp>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"copy",
ExpressionHelpers.GetPath(path).ToLowerInvariant(),
@ -373,10 +507,20 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="positionTo">position</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Copy<TProp>(
[NotNull] Expression<Func<TModel, TProp>> from,
[NotNull] Expression<Func<TModel, IList<TProp>>> path,
Expression<Func<TModel, TProp>> from,
Expression<Func<TModel, IList<TProp>>> path,
int positionTo)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"copy",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/" + positionTo,
@ -395,11 +539,21 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="positionTo">position (target)</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Copy<TProp>(
[NotNull] Expression<Func<TModel, IList<TProp>>> from,
Expression<Func<TModel, IList<TProp>>> from,
int positionFrom,
[NotNull] Expression<Func<TModel, IList<TProp>>> path,
Expression<Func<TModel, IList<TProp>>> path,
int positionTo)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"copy",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/" + positionTo,
@ -417,10 +571,20 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Copy<TProp>(
[NotNull] Expression<Func<TModel, IList<TProp>>> from,
Expression<Func<TModel, IList<TProp>>> from,
int positionFrom,
[NotNull] Expression<Func<TModel, IList<TProp>>> path)
Expression<Func<TModel, IList<TProp>>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"copy",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/-",
@ -437,9 +601,19 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="path">target location</param>
/// <returns></returns>
public JsonPatchDocument<TModel> Copy<TProp>(
[NotNull] Expression<Func<TModel, TProp>> from,
[NotNull] Expression<Func<TModel, IList<TProp>>> path)
Expression<Func<TModel, TProp>> from,
Expression<Func<TModel, IList<TProp>>> path)
{
if (from == null)
{
throw new ArgumentNullException(nameof(from));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
Operations.Add(new Operation<TModel>(
"copy",
ExpressionHelpers.GetPath(path).ToLowerInvariant() + "/-",
@ -452,8 +626,13 @@ namespace Microsoft.AspNet.JsonPatch
/// Apply this JsonPatchDocument
/// </summary>
/// <param name="objectToApplyTo">Object to apply the JsonPatchDocument to</param>
public void ApplyTo([NotNull] TModel objectToApplyTo)
public void ApplyTo(TModel objectToApplyTo)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
ApplyTo(objectToApplyTo, new ObjectAdapter(ContractResolver, logErrorAction: null));
}
@ -462,8 +641,13 @@ namespace Microsoft.AspNet.JsonPatch
/// </summary>
/// <param name="objectToApplyTo">Object to apply the JsonPatchDocument to</param>
/// <param name="logErrorAction">Action to log errors</param>
public void ApplyTo([NotNull] TModel objectToApplyTo, Action<JsonPatchError> logErrorAction)
public void ApplyTo(TModel objectToApplyTo, Action<JsonPatchError> logErrorAction)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
ApplyTo(objectToApplyTo, new ObjectAdapter(ContractResolver, logErrorAction));
}
@ -472,8 +656,18 @@ namespace Microsoft.AspNet.JsonPatch
/// </summary>
/// <param name="objectToApplyTo">Object to apply the JsonPatchDocument to</param>
/// <param name="adapter">IObjectAdapter instance to use when applying</param>
public void ApplyTo([NotNull] TModel objectToApplyTo, [NotNull] IObjectAdapter adapter)
public void ApplyTo(TModel objectToApplyTo, IObjectAdapter adapter)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (adapter == null)
{
throw new ArgumentNullException(nameof(adapter));
}
// apply each operation in order
foreach (var op in Operations)
{

View File

@ -1,15 +1,15 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.JsonPatch.Operations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.JsonPatch
{
/// <summary>
/// Captures error message and the related entity and the operation that caused it.
/// </summary>
public class JsonPatchError
public class JsonPatchError
{
/// <summary>
/// Initializes a new instance of <see cref="JsonPatchError"/>.
@ -18,10 +18,15 @@ namespace Microsoft.AspNet.JsonPatch
/// <param name="operation">The <see cref="Operation"/> that caused the error.</param>
/// <param name="errorMessage">The error message.</param>
public JsonPatchError(
object affectedObject,
Operation operation,
[NotNull] string errorMessage)
object affectedObject,
Operation operation,
string errorMessage)
{
if (errorMessage == null)
{
throw new ArgumentNullException(nameof(errorMessage));
}
AffectedObject = affectedObject;
Operation = operation;
ErrorMessage = errorMessage;

View File

@ -3,7 +3,6 @@
using System;
using Microsoft.AspNet.JsonPatch.Adapters;
using Microsoft.Framework.Internal;
using Newtonsoft.Json;
namespace Microsoft.AspNet.JsonPatch.Operations
@ -18,20 +17,29 @@ namespace Microsoft.AspNet.JsonPatch.Operations
}
public Operation([NotNull] string op, [NotNull] string path, string from, object value)
public Operation(string op, string path, string from, object value)
: base(op, path, from)
{
this.value = value;
}
public Operation([NotNull] string op, [NotNull] string path, string from)
public Operation(string op, string path, string from)
: base(op, path, from)
{
}
public void Apply([NotNull] object objectToApplyTo, [NotNull] IObjectAdapter adapter)
public void Apply(object objectToApplyTo, IObjectAdapter adapter)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (adapter == null)
{
throw new ArgumentNullException(nameof(adapter));
}
switch (OperationType)
{
case OperationType.Add:

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 Microsoft.Framework.Internal;
using Newtonsoft.Json;
namespace Microsoft.AspNet.JsonPatch.Operations
@ -32,8 +31,18 @@ namespace Microsoft.AspNet.JsonPatch.Operations
}
public OperationBase([NotNull] string op, [NotNull] string path, string from)
public OperationBase(string op, string path, string from)
{
if (op == null)
{
throw new ArgumentNullException(nameof(op));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
this.op = op;
this.path = path;
this.from = from;

View File

@ -3,7 +3,6 @@
using System;
using Microsoft.AspNet.JsonPatch.Adapters;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.JsonPatch.Operations
{
@ -14,20 +13,48 @@ namespace Microsoft.AspNet.JsonPatch.Operations
}
public Operation([NotNull] string op, [NotNull] string path, string from, object value)
public Operation(string op, string path, string from, object value)
: base(op, path, from)
{
if (op == null)
{
throw new ArgumentNullException(nameof(op));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
this.value = value;
}
public Operation([NotNull] string op, [NotNull] string path, string from)
public Operation(string op, string path, string from)
: base(op, path, from)
{
if (op == null)
{
throw new ArgumentNullException(nameof(op));
}
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
}
public void Apply([NotNull] TModel objectToApplyTo, [NotNull] IObjectAdapter adapter)
public void Apply(TModel objectToApplyTo, IObjectAdapter adapter)
{
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (adapter == null)
{
throw new ArgumentNullException(nameof(adapter));
}
switch (OperationType)
{
case OperationType.Add:

View File

@ -6,7 +6,6 @@
},
"dependencies": {
"Microsoft.AspNet.Http.Extensions": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "version": "1.0.0-*", "type": "build" },
"Microsoft.Framework.PropertyHelper.Sources": { "version": "1.0.0-*", "type": "build" },
"Newtonsoft.Json": "6.0.6"
},

View File

@ -1,23 +1,32 @@
// Copyright (c) .NET Foundation. 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.ComponentModel.DataAnnotations;
using System.Globalization;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
public class CompareAttributeAdapter : DataAnnotationsClientModelValidator<CompareAttribute>
{
public CompareAttributeAdapter([NotNull] CompareAttribute attribute)
public CompareAttributeAdapter(CompareAttribute attribute)
: base(new CompareAttributeWrapper(attribute))
{
if (attribute == null)
{
throw new ArgumentNullException(nameof(attribute));
}
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var errorMessage = ((CompareAttributeWrapper)Attribute).FormatErrorMessage(context);
var clientRule = new ModelClientValidationEqualToRule(errorMessage,
FormatPropertyForClientValidation(Attribute.OtherProperty));

View File

@ -4,7 +4,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -42,8 +41,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
/// <param name="modelMetadata">The <see cref="ModelMetadata"/> associated with the model annotated with
/// <see cref="Attribute"/>.</param>
/// <returns>Formatted error string.</returns>
protected virtual string GetErrorMessage([NotNull] ModelMetadata modelMetadata)
protected virtual string GetErrorMessage(ModelMetadata modelMetadata)
{
if (modelMetadata == null)
{
throw new ArgumentNullException(nameof(modelMetadata));
}
return Attribute.FormatErrorMessage(modelMetadata.GetDisplayName());
}
}

View File

@ -32,11 +32,16 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
/// <inheritdoc />
public void GetValidators(ClientValidatorProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var hasRequiredAttribute = false;
foreach (var attribute in context.ValidatorMetadata.OfType<ValidationAttribute>())
{
hasRequiredAttribute |= attribute is RequiredAttribute;
hasRequiredAttribute |= attribute is RequiredAttribute;
DataAnnotationsClientModelValidationFactory factory;
if (_attributeFactories.TryGetValue(attribute.GetType(), out factory))

View File

@ -6,7 +6,6 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
{
@ -20,8 +19,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
IValidationMetadataProvider
{
/// <inheritdoc />
public void GetBindingMetadata([NotNull] BindingMetadataProviderContext context)
public void GetBindingMetadata(BindingMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var editableAttribute = context.Attributes.OfType<EditableAttribute>().FirstOrDefault();
if (editableAttribute != null)
{
@ -30,8 +34,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
}
/// <inheritdoc />
public void GetDisplayMetadata([NotNull] DisplayMetadataProviderContext context)
public void GetDisplayMetadata(DisplayMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var attributes = context.Attributes;
var dataTypeAttribute = attributes.OfType<DataTypeAttribute>().FirstOrDefault();
var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault();
@ -205,8 +214,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
}
/// <inheritdoc />
public void GetValidationMetadata([NotNull] ValidationMetadataProviderContext context)
public void GetValidationMetadata(ValidationMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// RequiredAttribute marks a property as required by validation - this means that it
// must have a non-null value on the model during validation.
var requiredAttribute = context.Attributes.OfType<RequiredAttribute>().FirstOrDefault();

View File

@ -5,14 +5,18 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
public class DataAnnotationsModelValidator : IModelValidator
{
public DataAnnotationsModelValidator([NotNull] ValidationAttribute attribute)
public DataAnnotationsModelValidator(ValidationAttribute attribute)
{
if (attribute == null)
{
throw new ArgumentNullException(nameof(attribute));
}
Attribute = attribute;
}

View File

@ -5,7 +5,6 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Mvc.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -17,9 +16,14 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
public DataTypeAttributeAdapter(
DataTypeAttribute attribute,
[NotNull] string ruleName)
string ruleName)
: base(attribute)
{
if (ruleName == null)
{
throw new ArgumentNullException(nameof(ruleName));
}
if (string.IsNullOrEmpty(ruleName))
{
throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(ruleName));
@ -30,8 +34,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
public string RuleName { get; private set; }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var errorMessage = GetErrorMessage(context.ModelMetadata);
return new[] { new ModelClientValidationRule(RuleName, errorMessage) };
}

View File

@ -1,6 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
// Copyright (c) .NET Foundation. 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.Validation
{
/// <summary>
@ -15,6 +19,11 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
/// <inheritdoc />
public void GetValidators(ClientValidatorProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
foreach (var metadata in context.ValidatorMetadata)
{
var validator = metadata as IClientModelValidator;

View File

@ -1,18 +1,23 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.DataAnnotations.Internal;
using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.Framework.DependencyInjection
{
public static class MvcDataAnnotationsMvcCoreBuilderExtensions
{
public static IMvcCoreBuilder AddDataAnnotations([NotNull] this IMvcCoreBuilder builder)
public static IMvcCoreBuilder AddDataAnnotations(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddDataAnnotationsServices(builder.Services);
return builder;
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. 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.ComponentModel.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -15,8 +15,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var message = GetErrorMessage(context.ModelMetadata);
return new[] { new ModelClientValidationMaxLengthRule(message, Attribute.Length) };
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. 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.ComponentModel.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -15,8 +15,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var message = GetErrorMessage(context.ModelMetadata);
return new[] { new ModelClientValidationMinLengthRule(message, Attribute.Length) };
}

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal;
using System;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -14,10 +14,15 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
private const string EqualToValidationParameter = "other";
public ModelClientValidationEqualToRule(
[NotNull] string errorMessage,
[NotNull] object other)
string errorMessage,
object other)
: base(EqualToValidationType, errorMessage)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
ValidationParameters[EqualToValidationParameter] = other;
}
}

View File

@ -1,8 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
public class ModelClientValidationMaxLengthRule : ModelClientValidationRule
@ -10,7 +8,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
private const string MaxLengthValidationType = "maxlength";
private const string MaxLengthValidationParameter = "max";
public ModelClientValidationMaxLengthRule([NotNull] string errorMessage, int maximumLength)
public ModelClientValidationMaxLengthRule(string errorMessage, int maximumLength)
: base(MaxLengthValidationType, errorMessage)
{
ValidationParameters[MaxLengthValidationParameter] = maximumLength;

View File

@ -1,8 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
public class ModelClientValidationMinLengthRule : ModelClientValidationRule
@ -10,7 +8,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
private const string MinLengthValidationType = "minlength";
private const string MinLengthValidationParameter = "min";
public ModelClientValidationMinLengthRule([NotNull] string errorMessage, int minimumLength)
public ModelClientValidationMinLengthRule(string errorMessage, int minimumLength)
: base(MinLengthValidationType, errorMessage)
{
ValidationParameters[MinLengthValidationParameter] = minimumLength;

View File

@ -1,8 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
/// <summary>
@ -17,7 +15,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
/// with the given <paramref name="errorMessage"/>.
/// </summary>
/// <param name="errorMessage">The error message to be displayed.</param>
public ModelClientValidationNumericRule([NotNull] string errorMessage)
public ModelClientValidationNumericRule(string errorMessage)
: base(NumericValidationType, errorMessage)
{
}

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal;
using System;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -12,11 +12,21 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
private const string MaxValidationParameter = "max";
public ModelClientValidationRangeRule(
[NotNull] string errorMessage,
[NotNull] object minValue,
[NotNull] object maxValue)
string errorMessage,
object minValue,
object maxValue)
: base(RangeValidationType, errorMessage)
{
if (minValue == null)
{
throw new ArgumentNullException(nameof(minValue));
}
if (maxValue == null)
{
throw new ArgumentNullException(nameof(maxValue));
}
ValidationParameters[MinValidationParameter] = minValue;
ValidationParameters[MaxValidationParameter] = maxValue;
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. 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 Microsoft.AspNet.Mvc.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -16,11 +16,21 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
/// <inheritdoc />
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
return new[] { new ModelClientValidationNumericRule(GetErrorMessage(context.ModelMetadata)) };
}
private string GetErrorMessage([NotNull] ModelMetadata modelMetadata)
private string GetErrorMessage(ModelMetadata modelMetadata)
{
if (modelMetadata == null)
{
throw new ArgumentNullException(nameof(modelMetadata));
}
return Resources.FormatNumericClientModelValidator_FieldMustBeNumber(modelMetadata.GetDisplayName());
}
}

View File

@ -1,6 +1,8 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
/// <summary>
@ -12,6 +14,11 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
/// <inheritdoc />
public void GetValidators(ClientValidatorProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var typeToValidate = context.ModelMetadata.UnderlyingOrModelType;
// Check only the numeric types for which we set type='text'.

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. 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.ComponentModel.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -15,8 +15,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var errorMessage = GetErrorMessage(context.ModelMetadata);
return new[] { new ModelClientValidationRangeRule(errorMessage, Attribute.Minimum, Attribute.Maximum) };
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. 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.ComponentModel.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -15,8 +15,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var errorMessage = GetErrorMessage(context.ModelMetadata);
return new[] { new ModelClientValidationRegexRule(errorMessage, Attribute.Pattern) };
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. 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.ComponentModel.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -15,8 +15,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var errorMessage = GetErrorMessage(context.ModelMetadata);
return new[] { new ModelClientValidationRequiredRule(errorMessage) };
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. 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.ComponentModel.DataAnnotations;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
{
@ -15,8 +15,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var errorMessage = GetErrorMessage(context.ModelMetadata);
var rule = new ModelClientValidationStringLengthRule(errorMessage,
Attribute.MinimumLength,

View File

@ -11,8 +11,7 @@
"dependencies": {
"Microsoft.AspNet.Mvc.Core": "6.0.0-*",
"Microsoft.Framework.ClosedGenericMatcher.Sources": { "version": "1.0.0-*", "type": "build" },
"Microsoft.Framework.CopyOnWriteDictionary.Sources": { "version": "1.0.0-*", "type": "build" },
"Microsoft.Framework.NotNullAttribute.Sources": { "version": "1.0.0-*", "type": "build" }
"Microsoft.Framework.CopyOnWriteDictionary.Sources": { "version": "1.0.0-*", "type": "build" }
},
"frameworks": {

View File

@ -1,9 +1,8 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
@ -18,9 +17,19 @@ namespace Microsoft.Framework.DependencyInjection
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">The <see cref="MvcJsonOptions"/> which need to be configured.</param>
public static IMvcBuilder AddJsonOptions(
[NotNull] this IMvcBuilder builder,
[NotNull] Action<MvcJsonOptions> setupAction)
this IMvcBuilder builder,
Action<MvcJsonOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
builder.Services.Configure(setupAction);
return builder;
}

View File

@ -1,11 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Formatters.Json.Internal;
using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
using Newtonsoft.Json;
@ -13,16 +12,31 @@ namespace Microsoft.Framework.DependencyInjection
{
public static class MvcJsonMvcCoreBuilderExtensions
{
public static IMvcCoreBuilder AddJsonFormatters([NotNull] this IMvcCoreBuilder builder)
public static IMvcCoreBuilder AddJsonFormatters(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddJsonFormatterServices(builder.Services);
return builder;
}
public static IMvcCoreBuilder AddJsonFormatters(
[NotNull] this IMvcCoreBuilder builder,
[NotNull] Action<JsonSerializerSettings> setupAction)
this IMvcCoreBuilder builder,
Action<JsonSerializerSettings> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
AddJsonFormatterServices(builder.Services);
if (setupAction != null)

View File

@ -6,7 +6,6 @@ using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.Framework.Internal;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
@ -21,8 +20,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
{
}
public JsonInputFormatter([NotNull] JsonSerializerSettings serializerSettings)
public JsonInputFormatter(JsonSerializerSettings serializerSettings)
{
if (serializerSettings == null)
{
throw new ArgumentNullException(nameof(serializerSettings));
}
_serializerSettings = serializerSettings;
SupportedEncodings.Add(UTF8EncodingWithoutBOM);
@ -41,16 +45,25 @@ namespace Microsoft.AspNet.Mvc.Formatters
{
return _serializerSettings;
}
[param: NotNull]
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_serializerSettings = value;
}
}
/// <inheritdoc />
public override Task<InputFormatterResult> ReadRequestBodyAsync([NotNull] InputFormatterContext context)
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Get the character encoding for the content.
var effectiveEncoding = SelectCharacterEncoding(context);
if (effectiveEncoding == null)
@ -128,10 +141,25 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// <param name="effectiveEncoding">The <see cref="Encoding"/> to use when reading.</param>
/// <returns>The <see cref="JsonReader"/> used during deserialization.</returns>
protected virtual JsonReader CreateJsonReader(
[NotNull] InputFormatterContext context,
[NotNull] Stream readStream,
[NotNull] Encoding effectiveEncoding)
InputFormatterContext context,
Stream readStream,
Encoding effectiveEncoding)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (readStream == null)
{
throw new ArgumentNullException(nameof(readStream));
}
if (effectiveEncoding == null)
{
throw new ArgumentNullException(nameof(effectiveEncoding));
}
return new JsonTextReader(new StreamReader(readStream, effectiveEncoding));
}

View File

@ -1,11 +1,11 @@
// Copyright (c) .NET Foundation. 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.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.Framework.Internal;
using Newtonsoft.Json;
namespace Microsoft.AspNet.Mvc.Formatters
@ -22,8 +22,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
{
}
public JsonOutputFormatter([NotNull] JsonSerializerSettings serializerSettings)
public JsonOutputFormatter(JsonSerializerSettings serializerSettings)
{
if (serializerSettings == null)
{
throw new ArgumentNullException(nameof(serializerSettings));
}
_serializerSettings = serializerSettings;
SupportedEncodings.Add(Encoding.UTF8);
@ -41,15 +46,24 @@ namespace Microsoft.AspNet.Mvc.Formatters
{
return _serializerSettings;
}
[param: NotNull]
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_serializerSettings = value;
}
}
public void WriteObject([NotNull] TextWriter writer, object value)
public void WriteObject(TextWriter writer, object value)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
using (var jsonWriter = CreateJsonWriter(writer))
{
var jsonSerializer = CreateJsonSerializer();
@ -62,8 +76,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// </summary>
/// <param name="writer">The <see cref="TextWriter"/> used to write.</param>
/// <returns>The <see cref="JsonWriter"/> used during serialization.</returns>
protected virtual JsonWriter CreateJsonWriter([NotNull] TextWriter writer)
protected virtual JsonWriter CreateJsonWriter(TextWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
var jsonWriter = new JsonTextWriter(writer);
jsonWriter.CloseOutput = false;
@ -81,6 +100,11 @@ namespace Microsoft.AspNet.Mvc.Formatters
public override Task WriteResponseBodyAsync(OutputFormatterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var response = context.HttpContext.Response;
var selectedEncoding = context.SelectedEncoding;

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.JsonPatch;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc
{
@ -19,10 +19,25 @@ namespace Microsoft.AspNet.Mvc
/// <param name="objectToApplyTo">The entity on which <see cref="JsonPatchDocument{T}"/> is applied.</param>
/// <param name="modelState">The <see cref="ModelStateDictionary"/> to add errors.</param>
public static void ApplyTo<T>(
[NotNull] this JsonPatchDocument<T> patchDoc,
[NotNull] T objectToApplyTo,
[NotNull] ModelStateDictionary modelState) where T : class
this JsonPatchDocument<T> patchDoc,
T objectToApplyTo,
ModelStateDictionary modelState) where T : class
{
if (patchDoc == null)
{
throw new ArgumentNullException(nameof(patchDoc));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState));
}
patchDoc.ApplyTo(objectToApplyTo, modelState, prefix: string.Empty);
}
@ -34,11 +49,26 @@ namespace Microsoft.AspNet.Mvc
/// <param name="modelState">The <see cref="ModelStateDictionary"/> to add errors.</param>
/// <param name="prefix">The prefix to use when looking up values in <see cref="ModelStateDictionary"/>.</param>
public static void ApplyTo<T>(
[NotNull] this JsonPatchDocument<T> patchDoc,
[NotNull] T objectToApplyTo,
[NotNull] ModelStateDictionary modelState,
this JsonPatchDocument<T> patchDoc,
T objectToApplyTo,
ModelStateDictionary modelState,
string prefix) where T : class
{
if (patchDoc == null)
{
throw new ArgumentNullException(nameof(patchDoc));
}
if (objectToApplyTo == null)
{
throw new ArgumentNullException(nameof(objectToApplyTo));
}
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState));
}
patchDoc.ApplyTo(objectToApplyTo, jsonPatchError =>
{
var affectedObjectName = jsonPatchError.AffectedObject.GetType().Name;

View File

@ -1,10 +1,10 @@
// Copyright (c) .NET Foundation. 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.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNet.JsonPatch;
using Microsoft.Framework.Internal;
using Microsoft.AspNet.Mvc.Internal;
using Newtonsoft.Json;
@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Mvc.Formatters
{
}
public JsonPatchInputFormatter([NotNull] JsonSerializerSettings serializerSettings)
public JsonPatchInputFormatter(JsonSerializerSettings serializerSettings)
: base(serializerSettings)
{
// Clear all values and only include json-patch+json value.
@ -27,8 +27,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
}
/// <inheritdoc />
public async override Task<InputFormatterResult> ReadRequestBodyAsync([NotNull] InputFormatterContext context)
public async override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var result = await base.ReadRequestBodyAsync(context);
if (!result.HasError)
{

View File

@ -1,11 +1,10 @@
// Copyright (c) .NET Foundation. 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.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.Actions;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
@ -39,8 +38,13 @@ namespace Microsoft.AspNet.Mvc
/// <param name="value">The value to format as JSON.</param>
/// <param name="serializerSettings">The <see cref="JsonSerializerSettings"/> to be used by
/// the formatter.</param>
public JsonResult(object value, [NotNull] JsonSerializerSettings serializerSettings)
public JsonResult(object value, JsonSerializerSettings serializerSettings)
{
if (serializerSettings == null)
{
throw new ArgumentNullException(nameof(serializerSettings));
}
Value = value;
_serializerSettings = serializerSettings;
}
@ -61,8 +65,13 @@ namespace Microsoft.AspNet.Mvc
public object Value { get; set; }
/// <inheritdoc />
public override Task ExecuteResultAsync([NotNull] ActionContext context)
public override Task ExecuteResultAsync(ActionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var response = context.HttpContext.Response;
var contentTypeHeader = ContentType;

View File

@ -15,10 +15,6 @@
"version": "1.0.0-*",
"type": "build"
},
"Microsoft.Framework.NotNullAttribute.Sources": {
"version": "1.0.0-*",
"type": "build"
},
"Newtonsoft.Json": "6.0.6"
},

View File

@ -5,7 +5,6 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters.Xml
{
@ -39,8 +38,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// </summary>
/// <param name="source">The <see cref="IEnumerable{T}"/> instance to get the enumerator from.</param>
/// <param name="elementWrapperProvider">The wrapper provider for wrapping individual elements.</param>
public DelegatingEnumerable([NotNull] IEnumerable<TDeclared> source, IWrapperProvider elementWrapperProvider)
public DelegatingEnumerable(IEnumerable<TDeclared> source, IWrapperProvider elementWrapperProvider)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
_source = source;
_wrapperProvider = elementWrapperProvider;
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. 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;
using System.Collections.Generic;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters.Xml
{
@ -25,8 +25,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// </summary>
/// <param name="inner">The original enumerator.</param>
/// <param name="wrapperProvider">The wrapper provider to wrap individual elements.</param>
public DelegatingEnumerator([NotNull] IEnumerator<TDeclared> inner, IWrapperProvider wrapperProvider)
public DelegatingEnumerator(IEnumerator<TDeclared> inner, IWrapperProvider wrapperProvider)
{
if (inner == null)
{
throw new ArgumentNullException(nameof(inner));
}
_inner = inner;
_wrapperProvider = wrapperProvider;
}

View File

@ -1,10 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Formatters.Xml.Internal;
using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.Framework.DependencyInjection
@ -19,8 +19,13 @@ namespace Microsoft.Framework.DependencyInjection
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddXmlDataContractSerializerFormatters([NotNull] this IMvcBuilder builder)
public static IMvcBuilder AddXmlDataContractSerializerFormatters(this IMvcBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddXmlDataContractSerializerFormatterServices(builder.Services);
return builder;
}
@ -30,8 +35,13 @@ namespace Microsoft.Framework.DependencyInjection
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddXmlSerializerFormatters([NotNull] this IMvcBuilder builder)
public static IMvcBuilder AddXmlSerializerFormatters(this IMvcBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddXmlSerializerFormatterServices(builder.Services);
return builder;
}

View File

@ -1,10 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Formatters.Xml.Internal;
using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.Framework.DependencyInjection
@ -19,8 +19,13 @@ namespace Microsoft.Framework.DependencyInjection
/// </summary>
/// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
/// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
public static IMvcCoreBuilder AddXmlDataContractSerializerFormatters([NotNull] this IMvcCoreBuilder builder)
public static IMvcCoreBuilder AddXmlDataContractSerializerFormatters(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddXmlDataContractSerializerFormatterServices(builder.Services);
return builder;
}
@ -30,8 +35,13 @@ namespace Microsoft.Framework.DependencyInjection
/// </summary>
/// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
/// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
public static IMvcCoreBuilder AddXmlSerializerFormatters([NotNull] this IMvcCoreBuilder builder)
public static IMvcCoreBuilder AddXmlSerializerFormatters(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddXmlSerializerFormatterServices(builder.Services);
return builder;
}

View File

@ -25,9 +25,14 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// <param name="elementWrapperProvider">The <see cref="IWrapperProvider"/> for the element type.
/// Can be null.</param>
public EnumerableWrapperProvider(
[NotNull] Type sourceEnumerableOfT,
Type sourceEnumerableOfT,
IWrapperProvider elementWrapperProvider)
{
if (sourceEnumerableOfT == null)
{
throw new ArgumentNullException(nameof(sourceEnumerableOfT));
}
var enumerableOfT = ClosedGenericMatcher.ExtractGenericInterface(
sourceEnumerableOfT,
typeof(IEnumerable<>));

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. 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.Reflection;
using Microsoft.Framework.Internal;
@ -20,8 +21,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// <see cref="IWrapperProviderFactory"/>.
/// </summary>
/// <param name="wrapperProviderFactories">List of <see cref="IWrapperProviderFactory"/>.</param>
public EnumerableWrapperProviderFactory([NotNull] IEnumerable<IWrapperProviderFactory> wrapperProviderFactories)
public EnumerableWrapperProviderFactory(IEnumerable<IWrapperProviderFactory> wrapperProviderFactories)
{
if (wrapperProviderFactories == null)
{
throw new ArgumentNullException(nameof(wrapperProviderFactories));
}
_wrapperProviderFactories = wrapperProviderFactories;
}
@ -31,8 +37,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// <param name="context">The <see cref="WrapperProviderContext"/>.</param>
/// <returns>An instance of <see cref="EnumerableWrapperProvider"/> if the declared type is
/// an interface and implements <see cref="IEnumerable{T}"/>.</returns>
public IWrapperProvider GetProvider([NotNull] WrapperProviderContext context)
public IWrapperProvider GetProvider(WrapperProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.IsSerialization)
{
// Example: IEnumerable<SerializableError>

View File

@ -1,10 +1,10 @@
// Copyright (c) .NET Foundation. 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.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
{
@ -14,8 +14,13 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
public class DataMemberRequiredBindingMetadataProvider : IBindingMetadataProvider
{
/// <inheritdoc />
public void GetBindingMetadata([NotNull] BindingMetadataProviderContext context)
public void GetBindingMetadata(BindingMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Types cannot be required; only properties can
if (context.Key.MetadataKind != ModelMetadataKind.Property)
{

View File

@ -5,7 +5,6 @@ using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters.Xml
{
@ -25,8 +24,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// Initializes a new instance of the <see cref="SerializableErrorWrapper"/> class.
/// </summary>
/// <param name="error">The <see cref="SerializableError"/> object that needs to be wrapped.</param>
public SerializableErrorWrapper([NotNull] SerializableError error)
public SerializableErrorWrapper(SerializableError error)
{
if (error == null)
{
throw new ArgumentNullException(nameof(error));
}
SerializableError = error;
}
@ -88,8 +92,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
}
/// <inheritdoc />
public object Unwrap([NotNull] Type declaredType)
public object Unwrap(Type declaredType)
{
if (declaredType == null)
{
throw new ArgumentNullException(nameof(declaredType));
}
return SerializableError;
}
}

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 Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters.Xml
{
@ -21,15 +20,20 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
}
/// <inheritdoc />
public object Wrap([NotNull] object original)
public object Wrap(object original)
{
if (original == null)
{
throw new ArgumentNullException(nameof(original));
}
var error = original as SerializableError;
if (error == null)
{
throw new ArgumentException(
Resources.FormatWrapperProvider_MismatchType(
typeof(SerializableErrorWrapper).Name,
original.GetType().Name),
typeof(SerializableErrorWrapper).Name,
original.GetType().Name),
nameof(original));
}

View File

@ -1,7 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal;
using System;
namespace Microsoft.AspNet.Mvc.Formatters.Xml
{
@ -21,8 +21,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// <see cref="WrapperProviderContext.DeclaredType"/> is
/// <see cref="Microsoft.AspNet.Mvc.SerializableError"/>; otherwise <c>null</c>.
/// </returns>
public IWrapperProvider GetProvider([NotNull] WrapperProviderContext context)
public IWrapperProvider GetProvider(WrapperProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.DeclaredType == typeof(SerializableError))
{
return new SerializableErrorWrapperProvider();

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 Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters.Xml
{
@ -17,8 +16,13 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// <param name="declaredType">The declared type of the object that needs to be wrapped.</param>
/// <param name="isSerialization"><see langword="true"/> if the wrapper provider is invoked during
/// serialization, otherwise <see langword="false"/>.</param>
public WrapperProviderContext([NotNull] Type declaredType, bool isSerialization)
public WrapperProviderContext(Type declaredType, bool isSerialization)
{
if (declaredType == null)
{
throw new ArgumentNullException(nameof(declaredType));
}
DeclaredType = declaredType;
IsSerialization = isSerialization;
}

View File

@ -3,7 +3,6 @@
using System;
using System.Collections.Generic;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters.Xml
{
@ -21,9 +20,19 @@ namespace Microsoft.AspNet.Mvc.Formatters.Xml
/// <returns>An instance of <see cref="IWrapperProvider"/> if there is a wrapping provider for the
/// supplied type, else null.</returns>
public static IWrapperProvider GetWrapperProvider(
[NotNull] this IEnumerable<IWrapperProviderFactory> wrapperProviderFactories,
[NotNull] WrapperProviderContext wrapperProviderContext)
this IEnumerable<IWrapperProviderFactory> wrapperProviderFactories,
WrapperProviderContext wrapperProviderContext)
{
if (wrapperProviderFactories == null)
{
throw new ArgumentNullException(nameof(wrapperProviderFactories));
}
if (wrapperProviderContext == null)
{
throw new ArgumentNullException(nameof(wrapperProviderContext));
}
foreach (var wrapperProviderFactory in wrapperProviderFactories)
{
var wrapperProvider = wrapperProviderFactory.GetProvider(wrapperProviderContext);

View File

@ -12,7 +12,6 @@ using System.Xml;
using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Mvc.Formatters.Xml.Internal;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.Framework.Internal;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNet.Mvc.Formatters
@ -118,8 +117,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
}
/// <inheritdoc />
protected override bool CanReadType([NotNull] Type type)
protected override bool CanReadType(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return GetCachedSerializer(GetSerializableType(type)) != null;
}
@ -129,8 +133,18 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
/// <param name="encoding">The <see cref="Encoding"/> used to read the stream.</param>
/// <returns>The <see cref="XmlReader"/> used during deserialization.</returns>
protected virtual XmlReader CreateXmlReader([NotNull] Stream readStream, [NotNull] Encoding encoding)
protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding)
{
if (readStream == null)
{
throw new ArgumentNullException(nameof(readStream));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
return XmlDictionaryReader.CreateTextReader(readStream, encoding, _readerQuotas, onClose: null);
}
@ -139,8 +153,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// </summary>
/// <param name="declaredType">The declared type.</param>
/// <returns>The type to which the XML will be deserialized.</returns>
protected virtual Type GetSerializableType([NotNull] Type declaredType)
protected virtual Type GetSerializableType(Type declaredType)
{
if (declaredType == null)
{
throw new ArgumentNullException(nameof(declaredType));
}
var wrapperProvider = WrapperProviderFactories.GetWrapperProvider(
new WrapperProviderContext(declaredType, isSerialization: false));
@ -152,8 +171,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// </summary>
/// <param name="type">The type of object for which the serializer should be created.</param>
/// <returns>The <see cref="DataContractSerializer"/> used during deserialization.</returns>
protected virtual DataContractSerializer CreateSerializer([NotNull] Type type)
protected virtual DataContractSerializer CreateSerializer(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
try
{
// If the serializer does not support this type it will throw an exception.

View File

@ -11,7 +11,6 @@ using System.Threading.Tasks;
using System.Xml;
using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Mvc.Formatters.Xml.Internal;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters
{
@ -37,8 +36,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// Initializes a new instance of <see cref="XmlDataContractSerializerOutputFormatter"/>
/// </summary>
/// <param name="writerSettings">The settings to be used by the <see cref="DataContractSerializer"/>.</param>
public XmlDataContractSerializerOutputFormatter([NotNull] XmlWriterSettings writerSettings)
public XmlDataContractSerializerOutputFormatter(XmlWriterSettings writerSettings)
{
if (writerSettings == null)
{
throw new ArgumentNullException(nameof(writerSettings));
}
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
@ -132,8 +136,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// </summary>
/// <param name="type">The type of object for which the serializer should be created.</param>
/// <returns>A new instance of <see cref="DataContractSerializer"/></returns>
protected virtual DataContractSerializer CreateSerializer([NotNull] Type type)
protected virtual DataContractSerializer CreateSerializer(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
try
{
#if DNX451
@ -157,17 +166,32 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// <param name="writeStream">The stream on which the XmlWriter should operate on.</param>
/// <returns>A new instance of <see cref="XmlWriter"/></returns>
public virtual XmlWriter CreateXmlWriter(
[NotNull] Stream writeStream,
[NotNull] XmlWriterSettings xmlWriterSettings)
Stream writeStream,
XmlWriterSettings xmlWriterSettings)
{
if (writeStream == null)
{
throw new ArgumentNullException(nameof(writeStream));
}
if (xmlWriterSettings == null)
{
throw new ArgumentNullException(nameof(xmlWriterSettings));
}
return XmlWriter.Create(
new HttpResponseStreamWriter(writeStream, xmlWriterSettings.Encoding),
xmlWriterSettings);
}
/// <inheritdoc />
public override Task WriteResponseBodyAsync([NotNull] OutputFormatterContext context)
public override Task WriteResponseBodyAsync(OutputFormatterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var tempWriterSettings = WriterSettings.Clone();
tempWriterSettings.Encoding = context.SelectedEncoding;

View File

@ -12,7 +12,6 @@ using System.Xml.Serialization;
using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Mvc.Formatters.Xml.Internal;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.Framework.Internal;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNet.Mvc.Formatters
@ -98,8 +97,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
}
/// <inheritdoc />
protected override bool CanReadType([NotNull] Type type)
protected override bool CanReadType(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return GetCachedSerializer(GetSerializableType(type)) != null;
}
@ -108,8 +112,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// </summary>
/// <param name="declaredType">The declared type.</param>
/// <returns>The type to which the XML will be deserialized.</returns>
protected virtual Type GetSerializableType([NotNull] Type declaredType)
protected virtual Type GetSerializableType(Type declaredType)
{
if (declaredType == null)
{
throw new ArgumentNullException(nameof(declaredType));
}
var wrapperProvider = WrapperProviderFactories.GetWrapperProvider(
new WrapperProviderContext(declaredType, isSerialization: false));
@ -122,8 +131,18 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
/// <param name="encoding">The <see cref="Encoding"/> used to read the stream.</param>
/// <returns>The <see cref="XmlReader"/> used during deserialization.</returns>
protected virtual XmlReader CreateXmlReader([NotNull] Stream readStream, [NotNull] Encoding encoding)
protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding)
{
if (readStream == null)
{
throw new ArgumentNullException(nameof(readStream));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
return XmlDictionaryReader.CreateTextReader(readStream, encoding, _readerQuotas, onClose: null);
}
@ -162,7 +181,7 @@ namespace Microsoft.AspNet.Mvc.Formatters
}
}
return (XmlSerializer) serializer;
return (XmlSerializer)serializer;
}
}
}

View File

@ -11,7 +11,6 @@ using System.Xml;
using System.Xml.Serialization;
using Microsoft.AspNet.Mvc.Formatters.Xml;
using Microsoft.AspNet.Mvc.Formatters.Xml.Internal;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Formatters
{
@ -36,8 +35,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// Initializes a new instance of <see cref="XmlSerializerOutputFormatter"/>
/// </summary>
/// <param name="writerSettings">The settings to be used by the <see cref="XmlSerializer"/>.</param>
public XmlSerializerOutputFormatter([NotNull] XmlWriterSettings writerSettings)
public XmlSerializerOutputFormatter(XmlWriterSettings writerSettings)
{
if (writerSettings == null)
{
throw new ArgumentNullException(nameof(writerSettings));
}
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
@ -111,8 +115,13 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// </summary>
/// <param name="type">The type of object for which the serializer should be created.</param>
/// <returns>A new instance of <see cref="XmlSerializer"/></returns>
protected virtual XmlSerializer CreateSerializer([NotNull] Type type)
protected virtual XmlSerializer CreateSerializer(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
try
{
// If the serializer does not support this type it will throw an exception.
@ -132,17 +141,32 @@ namespace Microsoft.AspNet.Mvc.Formatters
/// <param name="writeStream">The stream on which the XmlWriter should operate on.</param>
/// <returns>A new instance of <see cref="XmlWriter"/></returns>
public virtual XmlWriter CreateXmlWriter(
[NotNull] Stream writeStream,
[NotNull] XmlWriterSettings xmlWriterSettings)
Stream writeStream,
XmlWriterSettings xmlWriterSettings)
{
if (writeStream == null)
{
throw new ArgumentNullException(nameof(writeStream));
}
if (xmlWriterSettings == null)
{
throw new ArgumentNullException(nameof(xmlWriterSettings));
}
return XmlWriter.Create(
new HttpResponseStreamWriter(writeStream, xmlWriterSettings.Encoding),
xmlWriterSettings);
}
/// <inheritdoc />
public override Task WriteResponseBodyAsync([NotNull] OutputFormatterContext context)
public override Task WriteResponseBodyAsync(OutputFormatterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var response = context.HttpContext.Response;
var tempWriterSettings = WriterSettings.Clone();

View File

@ -11,7 +11,6 @@
"dependencies": {
"Microsoft.AspNet.Mvc.Core": "6.0.0-*",
"Microsoft.Framework.ClosedGenericMatcher.Sources": { "version": "1.0.0-*", "type": "build" },
"Microsoft.Framework.NotNullAttribute.Sources": { "version": "1.0.0-*", "type": "build" },
"Microsoft.Framework.PropertyHelper.Sources": { "version": "1.0.0-*", "type": "build" }
},
"frameworks": {

View File

@ -1,14 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Localization;
using System;
using Microsoft.AspNet.Mvc.Localization.Internal;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
using Microsoft.Framework.WebEncoders;
namespace Microsoft.Framework.DependencyInjection
{
@ -22,8 +17,13 @@ namespace Microsoft.Framework.DependencyInjection
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddViewLocalization([NotNull] this IMvcBuilder builder)
public static IMvcBuilder AddViewLocalization(this IMvcBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix);
}
@ -34,9 +34,14 @@ namespace Microsoft.Framework.DependencyInjection
/// <param name="format">The view format for localized views.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddViewLocalization(
[NotNull] this IMvcBuilder builder,
this IMvcBuilder builder,
LanguageViewLocationExpanderFormat format)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
MvcLocalizationServices.AddLocalizationServices(builder.Services, format);
return builder;
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc.Localization.Internal;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
@ -22,8 +22,13 @@ namespace Microsoft.Framework.DependencyInjection
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcCoreBuilder AddViewLocalization([NotNull] this IMvcCoreBuilder builder)
public static IMvcCoreBuilder AddViewLocalization(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix);
}
@ -39,9 +44,14 @@ namespace Microsoft.Framework.DependencyInjection
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcCoreBuilder AddViewLocalization(
[NotNull] this IMvcCoreBuilder builder,
this IMvcCoreBuilder builder,
LanguageViewLocationExpanderFormat format)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.AddViews();
builder.AddRazorViewEngine();

View File

@ -1,12 +1,10 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. 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.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Localization;
using Microsoft.Framework.WebEncoders;
@ -27,51 +25,125 @@ namespace Microsoft.AspNet.Mvc.Localization
/// </summary>
/// <param name="localizer">The <see cref="IStringLocalizer"/> to read strings from.</param>
/// <param name="encoder">The <see cref="IHtmlEncoder"/>.</param>
public HtmlLocalizer([NotNull] IStringLocalizer localizer, [NotNull] IHtmlEncoder encoder)
public HtmlLocalizer(IStringLocalizer localizer, IHtmlEncoder encoder)
{
if (localizer == null)
{
throw new ArgumentNullException(nameof(localizer));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
_localizer = localizer;
_encoder = encoder;
}
/// <inheritdoc />
public virtual LocalizedString this[[NotNull] string key] => _localizer[key];
public virtual LocalizedString this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer[key];
}
}
/// <inheritdoc />
public virtual LocalizedString this[[NotNull] string key, params object[] arguments] =>
_localizer[key, arguments];
public virtual LocalizedString this[string key, params object[] arguments]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer[key, arguments];
}
}
/// <summary>
/// Creates a new <see cref="IHtmlLocalizer"/> for a specific <see cref="CultureInfo"/>.
/// </summary>
/// <param name="culture">The <see cref="CultureInfo"/> to use.</param>
/// <returns>A culture-specific <see cref="IHtmlLocalizer"/>.</returns>
public virtual IHtmlLocalizer WithCulture([NotNull] CultureInfo culture) =>
new HtmlLocalizer(_localizer.WithCulture(culture), _encoder);
public virtual IHtmlLocalizer WithCulture(CultureInfo culture)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return new HtmlLocalizer(_localizer.WithCulture(culture), _encoder);
}
/// <summary>
/// Creates a new <see cref="IStringLocalizer"/> for a specific <see cref="CultureInfo"/>.
/// </summary>
/// <param name="culture">The <see cref="CultureInfo"/> to use.</param>
/// <returns>A culture-specific <see cref="IStringLocalizer"/>.</returns>
IStringLocalizer IStringLocalizer.WithCulture([NotNull] CultureInfo culture) => WithCulture(culture);
IStringLocalizer IStringLocalizer.WithCulture(CultureInfo culture)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return new HtmlLocalizer(_localizer.WithCulture(culture), _encoder);
}
/// <inheritdoc />
public virtual LocalizedString GetString([NotNull] string key) => _localizer.GetString(key);
public virtual LocalizedString GetString(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer.GetString(key);
}
/// <inheritdoc />
public virtual LocalizedString GetString([NotNull] string key, params object[] arguments) =>
_localizer.GetString(key, arguments);
public virtual LocalizedString GetString(string key, params object[] arguments)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer.GetString(key, arguments);
}
/// <inheritdoc />
public virtual IEnumerable<LocalizedString> GetAllStrings(bool includeAncestorCultures) =>
_localizer.GetAllStrings(includeAncestorCultures);
/// <inheritdoc />
public virtual LocalizedHtmlString Html([NotNull] string key) => ToHtmlString(_localizer.GetString(key));
public virtual LocalizedHtmlString Html(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return ToHtmlString(_localizer.GetString(key));
}
/// <inheritdoc />
public virtual LocalizedHtmlString Html([NotNull] string key, params object[] arguments)
public virtual LocalizedHtmlString Html(string key, params object[] arguments)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var stringValue = _localizer[key].Value;
return ToHtmlString(new LocalizedString(key, EncodeArguments(stringValue, arguments)));
@ -90,8 +162,18 @@ namespace Microsoft.AspNet.Mvc.Localization
/// <param name="resourceString">The resourceString whose arguments need to be encoded.</param>
/// <param name="arguments">The array of objects to encode.</param>
/// <returns>The string with encoded arguments.</returns>
protected virtual string EncodeArguments([NotNull] string resourceString, [NotNull] object[] arguments)
protected virtual string EncodeArguments(string resourceString, object[] arguments)
{
if (resourceString == null)
{
throw new ArgumentNullException(nameof(resourceString));
}
if (arguments == null)
{
throw new ArgumentNullException(nameof(arguments));
}
var position = 0;
var length = resourceString.Length;
char currentCharacter;

View File

@ -1,8 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Localization;
using Microsoft.Framework.WebEncoders;
@ -21,8 +20,18 @@ namespace Microsoft.AspNet.Mvc.Localization
/// </summary>
/// <param name="localizerFactory">The <see cref="IStringLocalizerFactory"/>.</param>
/// <param name="encoder">The <see cref="IHtmlEncoder"/>.</param>
public HtmlLocalizerFactory([NotNull] IStringLocalizerFactory localizerFactory, [NotNull] IHtmlEncoder encoder)
public HtmlLocalizerFactory(IStringLocalizerFactory localizerFactory, IHtmlEncoder encoder)
{
if (localizerFactory == null)
{
throw new ArgumentNullException(nameof(localizerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
_factory = localizerFactory;
_encoder = encoder;
}
@ -35,6 +44,11 @@ namespace Microsoft.AspNet.Mvc.Localization
/// <returns>The <see cref="HtmlLocalizer"/>.</returns>
public virtual IHtmlLocalizer Create(Type resourceSource)
{
if (resourceSource == null)
{
throw new ArgumentNullException(nameof(resourceSource));
}
return new HtmlLocalizer(_factory.Create(resourceSource), _encoder);
}
@ -46,6 +60,16 @@ namespace Microsoft.AspNet.Mvc.Localization
/// <returns>The <see cref="HtmlLocalizer"/>.</returns>
public virtual IHtmlLocalizer Create(string baseName, string location)
{
if (baseName == null)
{
throw new ArgumentNullException(nameof(baseName));
}
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
var localizer = _factory.Create(baseName, location);
return new HtmlLocalizer(localizer, _encoder);
}

View File

@ -1,9 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. 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.Globalization;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Localization;
namespace Microsoft.AspNet.Mvc.Localization
@ -26,32 +26,98 @@ namespace Microsoft.AspNet.Mvc.Localization
}
/// <inheritdoc />
public virtual LocalizedString this[[NotNull] string key] => _localizer[key];
public virtual LocalizedString this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer[key];
}
}
/// <inheritdoc />
public virtual LocalizedString this[[NotNull] string key, params object[] arguments] =>
_localizer[key, arguments];
public virtual LocalizedString this[string key, params object[] arguments]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer[key, arguments];
}
}
/// <inheritdoc />
public virtual IHtmlLocalizer WithCulture([NotNull] CultureInfo culture) => _localizer.WithCulture(culture);
public virtual IHtmlLocalizer WithCulture(CultureInfo culture)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return _localizer.WithCulture(culture);
}
/// <inheritdoc />
IStringLocalizer IStringLocalizer.WithCulture([NotNull] CultureInfo culture) =>
_localizer.WithCulture(culture);
IStringLocalizer IStringLocalizer.WithCulture(CultureInfo culture)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return _localizer.WithCulture(culture);
}
/// <inheritdoc />
public virtual LocalizedString GetString([NotNull] string key) => _localizer.GetString(key);
public virtual LocalizedString GetString(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer.GetString(key);
}
/// <inheritdoc />
public virtual LocalizedString GetString([NotNull] string key, params object[] arguments) =>
_localizer.GetString(key, arguments);
public virtual LocalizedString GetString(string key, params object[] arguments)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer.GetString(key, arguments);
}
/// <inheritdoc />
public virtual LocalizedHtmlString Html([NotNull] string key) => _localizer.Html(key);
public virtual LocalizedHtmlString Html(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer.Html(key);
}
/// <inheritdoc />
public virtual LocalizedHtmlString Html([NotNull] string key, params object[] arguments) =>
_localizer.Html(key, arguments);
public virtual LocalizedHtmlString Html(string key, params object[] arguments)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer.Html(key, arguments);
}
/// <inheritdoc />
public virtual IEnumerable<LocalizedString> GetAllStrings(bool includeAncestorCultures) =>

View File

@ -1,8 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Globalization;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Localization;
namespace Microsoft.AspNet.Mvc.Localization
@ -18,14 +17,14 @@ namespace Microsoft.AspNet.Mvc.Localization
/// </summary>
/// <param name="culture">The <see cref="CultureInfo"/> to use.</param>
/// <returns>A culture-specific <see cref="IHtmlLocalizer"/>.</returns>
new IHtmlLocalizer WithCulture([NotNull] CultureInfo culture);
new IHtmlLocalizer WithCulture(CultureInfo culture);
/// <summary>
/// Gets the <see cref="LocalizedHtmlString"/> resource for a specific key.
/// </summary>
/// <param name="key">The key to use.</param>
/// <returns>The <see cref="LocalizedHtmlString"/> resource.</returns>
LocalizedHtmlString Html([NotNull] string key);
LocalizedHtmlString Html(string key);
/// <summary>
/// Gets the <see cref="LocalizedHtmlString"/> resource for a specific key.
@ -33,6 +32,6 @@ namespace Microsoft.AspNet.Mvc.Localization
/// <param name="key">The key to use.</param>
/// <param name="arguments">The values to format the string with.</param>
/// <returns>The <see cref="LocalizedHtmlString"/> resource.</returns>
LocalizedHtmlString Html([NotNull] string key, params object[] arguments);
LocalizedHtmlString Html(string key, params object[] arguments);
}
}

View File

@ -1,8 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Localization
{
@ -17,7 +16,7 @@ namespace Microsoft.AspNet.Mvc.Localization
/// </summary>
/// <param name="resourceSource">The <see cref="Type"/>.</param>
/// <returns>The <see cref="IHtmlLocalizer"/>.</returns>
IHtmlLocalizer Create([NotNull] Type resourceSource);
IHtmlLocalizer Create(Type resourceSource);
/// <summary>
/// Creates an <see cref="IHtmlLocalizer"/>.
@ -25,6 +24,6 @@ namespace Microsoft.AspNet.Mvc.Localization
/// <param name="baseName">The base name of the resource to load strings from.</param>
/// <param name="location">The location to load resources from.</param>
/// <returns>The <see cref="IHtmlLocalizer"/>.</returns>
IHtmlLocalizer Create([NotNull] string baseName, [NotNull] string location);
IHtmlLocalizer Create(string baseName, string location);
}
}

View File

@ -1,11 +1,11 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. 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.Globalization;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Mvc.ViewFeatures.Internal;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Localization;
using Microsoft.Dnx.Runtime;
@ -26,41 +26,78 @@ namespace Microsoft.AspNet.Mvc.Localization
/// <param name="localizerFactory">The <see cref="IHtmlLocalizerFactory"/>.</param>
/// <param name="applicationEnvironment">The <see cref="IApplicationEnvironment"/>.</param>
public ViewLocalizer(
[NotNull] IHtmlLocalizerFactory localizerFactory,
[NotNull] IApplicationEnvironment applicationEnvironment)
IHtmlLocalizerFactory localizerFactory,
IApplicationEnvironment applicationEnvironment)
{
if (localizerFactory == null)
{
throw new ArgumentNullException(nameof(localizerFactory));
}
if (applicationEnvironment == null)
{
throw new ArgumentNullException(nameof(applicationEnvironment));
}
_applicationName = applicationEnvironment.ApplicationName;
_localizerFactory = localizerFactory;
}
/// <inheritdoc />
public LocalizedString this[[NotNull] string name] => _localizer[name];
public virtual LocalizedString this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer[key];
}
}
/// <inheritdoc />
public LocalizedString this[[NotNull] string name, params object[] arguments] => _localizer[name, arguments];
public virtual LocalizedString this[string key, params object[] arguments]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _localizer[key, arguments];
}
}
/// <inheritdoc />
public LocalizedString GetString([NotNull] string name) => _localizer.GetString(name);
public LocalizedString GetString(string name) => _localizer.GetString(name);
/// <inheritdoc />
public LocalizedString GetString([NotNull] string name, params object[] values) =>
public LocalizedString GetString(string name, params object[] values) =>
_localizer.GetString(name, values);
/// <inheritdoc />
public LocalizedHtmlString Html([NotNull] string key) => _localizer.Html(key);
public LocalizedHtmlString Html(string key) => _localizer.Html(key);
/// <inheritdoc />
public LocalizedHtmlString Html([NotNull] string key, params object[] arguments) =>
public LocalizedHtmlString Html(string key, params object[] arguments) =>
_localizer.Html(key, arguments);
/// <inheritdoc />
public IStringLocalizer WithCulture([NotNull] CultureInfo culture) => _localizer.WithCulture(culture);
public IStringLocalizer WithCulture(CultureInfo culture) => _localizer.WithCulture(culture);
/// <inheritdoc />
IHtmlLocalizer IHtmlLocalizer.WithCulture([NotNull] CultureInfo culture) => _localizer.WithCulture(culture);
IHtmlLocalizer IHtmlLocalizer.WithCulture(CultureInfo culture) => _localizer.WithCulture(culture);
public void Contextualize(ViewContext viewContext)
{
if (viewContext == null)
{
throw new ArgumentNullException(nameof(viewContext));
}
var baseName = viewContext.View.Path.Replace('/', '.').Replace('\\', '.');
if (baseName.StartsWith("."))
{

View File

@ -9,10 +9,6 @@
"Microsoft.AspNet.Mvc.Razor": "6.0.0-*",
"Microsoft.Framework.DependencyInjection": "1.0.0-*",
"Microsoft.Framework.Localization": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": {
"version": "1.0.0-*",
"type": "build"
},
"Microsoft.Framework.PropertyHelper.Sources": {
"version": "1.0.0-*",
"type": "build"

View File

@ -5,11 +5,8 @@ using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using Microsoft.AspNet.Testing;
using Microsoft.Framework.Internal;
using Xunit;
namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
@ -1044,7 +1041,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Metadata
new ModelAttributes(_attributes.Concat(entry.ModelAttributes.TypeAttributes).ToArray()));
}
protected override DefaultMetadataDetails[] CreatePropertyDetails([NotNull] ModelMetadataIdentity key)
protected override DefaultMetadataDetails[] CreatePropertyDetails(ModelMetadataIdentity key)
{
var entries = base.CreatePropertyDetails(key);
return entries.Select(e =>

View File

@ -17,7 +17,7 @@ using Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.Caching;
using Microsoft.Framework.Caching.Memory;
using Microsoft.Framework.WebEncoders.Testing;
using Moq;
@ -303,6 +303,8 @@ namespace Microsoft.AspNet.Mvc.TagHelpers
.Returns(emptyDirectoryContents.Object);
mockFileProvider.Setup(fp => fp.GetFileInfo(It.IsAny<string>()))
.Returns(mockFile.Object);
mockFileProvider.Setup(fp => fp.Watch(It.IsAny<string>()))
.Returns(new TestFileTrigger());
var hostingEnvironment = new Mock<IHostingEnvironment>();
hostingEnvironment.Setup(h => h.WebRootFileProvider).Returns(mockFileProvider.Object);

View File

@ -7,7 +7,6 @@ using System.Text;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Testing.xunit;
using Microsoft.Framework.Caching;
using Microsoft.Framework.Caching.Memory;
using Moq;
@ -54,6 +53,8 @@ namespace Microsoft.AspNet.Mvc.TagHelpers.Internal
var mockFileProvider = new Mock<IFileProvider>();
mockFileProvider.Setup(fp => fp.GetFileInfo(It.IsAny<string>()))
.Returns(mockFile.Object);
mockFileProvider.Setup(fp => fp.Watch(It.IsAny<string>()))
.Returns(new TestFileTrigger());
var hostingEnvironment = new Mock<IHostingEnvironment>();
hostingEnvironment.Setup(h => h.WebRootFileProvider).Returns(mockFileProvider.Object);
@ -195,6 +196,9 @@ namespace Microsoft.AspNet.Mvc.TagHelpers.Internal
.Returns(fileDoesNotExist? nonExistingMockFile.Object : existingMockFile.Object);
}
mockFileProvider.Setup(fp => fp.Watch(It.IsAny<string>()))
.Returns(new TestFileTrigger());
var hostingEnvironment = new Mock<IHostingEnvironment>();
hostingEnvironment.Setup(h => h.WebRootFileProvider).Returns(mockFileProvider.Object);

View File

@ -18,8 +18,8 @@ using Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Testing.xunit;
using Microsoft.Dnx.Runtime;
using Microsoft.Framework.Caching;
using Microsoft.Framework.Caching.Memory;
using Microsoft.Framework.Logging;
using Microsoft.Framework.WebEncoders.Testing;
@ -870,6 +870,8 @@ namespace Microsoft.AspNet.Mvc.TagHelpers
.Returns(emptyDirectoryContents.Object);
mockFileProvider.Setup(fp => fp.GetFileInfo(It.IsAny<string>()))
.Returns(mockFile.Object);
mockFileProvider.Setup(fp => fp.Watch(It.IsAny<string>()))
.Returns(new TestFileTrigger());
var hostingEnvironment = new Mock<IHostingEnvironment>();
hostingEnvironment.Setup(h => h.WebRootFileProvider).Returns(mockFileProvider.Object);

View File

@ -18,7 +18,6 @@ using Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Testing.xunit;
using Microsoft.Dnx.Runtime;
using Microsoft.Framework.Caching;
using Microsoft.Framework.Caching.Memory;
@ -964,6 +963,8 @@ namespace Microsoft.AspNet.Mvc.TagHelpers
.Returns(emptyDirectoryContents.Object);
mockFileProvider.Setup(fp => fp.GetFileInfo(It.IsAny<string>()))
.Returns(mockFile.Object);
mockFileProvider.Setup(fp => fp.Watch(It.IsAny<string>()))
.Returns(new TestFileTrigger());
var hostingEnvironment = new Mock<IHostingEnvironment>();
hostingEnvironment.Setup(h => h.WebRootFileProvider).Returns(mockFileProvider.Object);

View File

@ -2,9 +2,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.Caching;
namespace Microsoft.AspNet.Mvc.Razor
namespace Microsoft.Framework.Caching
{
internal class TestFileTrigger : IExpirationTrigger
{

View File

@ -11,12 +11,14 @@ namespace FiltersWebSite
public class AuthorizeBasicMiddleware : AuthenticationMiddleware<BasicOptions>
{
public AuthorizeBasicMiddleware(
RequestDelegate next,
RequestDelegate next,
ILoggerFactory loggerFactory,
IUrlEncoder encoder,
string authScheme) :
base(next, new BasicOptions { AuthenticationScheme = authScheme }, loggerFactory,
encoder, configureOptions: null)
string authScheme) :
base(next,
new BasicOptions { AuthenticationScheme = authScheme },
loggerFactory,
encoder)
{
}