// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
///
/// A which can repesent multiple value-provider data sources.
///
public class CompositeBindingSource : BindingSource
{
///
/// Creates a new .
///
///
/// The set of entries.
/// Must be value-provider sources and user input.
///
/// The display name for the composite source.
/// A .
public static CompositeBindingSource Create(
[NotNull] IEnumerable bindingSources,
string displayName)
{
foreach (var bindingSource in bindingSources)
{
if (bindingSource.IsGreedy)
{
var message = Resources.FormatBindingSource_CannotBeGreedy(
bindingSource.DisplayName,
nameof(CompositeBindingSource));
throw new ArgumentException(message, nameof(bindingSources));
}
if (!bindingSource.IsFromRequest)
{
var message = Resources.FormatBindingSource_MustBeFromRequest(
bindingSource.DisplayName,
nameof(CompositeBindingSource));
throw new ArgumentException(message, nameof(bindingSources));
}
if (bindingSource is CompositeBindingSource)
{
var message = Resources.FormatBindingSource_CannotBeComposite(
bindingSource.DisplayName,
nameof(CompositeBindingSource));
throw new ArgumentException(message, nameof(bindingSources));
}
}
var id = string.Join("&", bindingSources.Select(s => s.Id).OrderBy(s => s, StringComparer.Ordinal));
return new CompositeBindingSource(id, displayName, bindingSources);
}
private CompositeBindingSource(
[NotNull] string id,
string displayName,
[NotNull] IEnumerable bindingSources)
: base(id, displayName, isGreedy: false, isFromRequest: true)
{
BindingSources = bindingSources;
}
///
/// Gets the set of entries.
///
public IEnumerable BindingSources { get; }
///
public override bool CanAcceptDataFrom([NotNull] BindingSource bindingSource)
{
if (bindingSource is CompositeBindingSource)
{
var message = Resources.FormatBindingSource_CannotBeComposite(
bindingSource.DisplayName,
nameof(CanAcceptDataFrom));
throw new ArgumentException(message, nameof(bindingSource));
}
foreach (var source in BindingSources)
{
if (source.CanAcceptDataFrom(bindingSource))
{
return true;
}
}
return false;
}
}
}