diff options
Diffstat (limited to 'src/DotNetOpenAuth.Core')
54 files changed, 242 insertions, 320 deletions
diff --git a/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs b/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs index 346917f..27ba80e 100644 --- a/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.Configuration { using System.Configuration; using System.Diagnostics.Contracts; using System.Text.RegularExpressions; + using Validation; /// <summary> /// Represents a collection of child elements that describe host names either as literal host names or regex patterns. diff --git a/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs index 96f60bf..3f19d8c 100644 --- a/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Configuration { using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A configuration collection of trusted OP Endpoints. diff --git a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs index adb2620..274622e 100644 --- a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Configuration { using System.Linq; using System.Text; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A collection of <see cref="TypeConfigurationElement<T>"/>. diff --git a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj index dc47259..12952f1 100644 --- a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj +++ b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj @@ -116,6 +116,7 @@ <None Include="Messaging\Bindings\Bindings.cd" /> <None Include="Messaging\Exceptions.cd" /> <None Include="Messaging\Messaging.cd" /> + <None Include="packages.config" /> </ItemGroup> <ItemGroup> <Compile Include="Configuration\DotNetOpenAuthSection.cs" /> @@ -137,7 +138,7 @@ <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Messaging\ReadOnlyDictionary.cs" /> <Compile Include="Reporting.cs" /> - <Compile Include="Requires.cs" /> + <Compile Include="RequiresEx.cs" /> <Compile Include="Strings.Designer.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> @@ -173,6 +174,9 @@ <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> </Reference> + <Reference Include="Validation"> + <HintPath>..\packages\Validation.2.0.0.12319\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> + </Reference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" /> diff --git a/src/DotNetOpenAuth.Core/Logger.cs b/src/DotNetOpenAuth.Core/Logger.cs index 975b391..512c237 100644 --- a/src/DotNetOpenAuth.Core/Logger.cs +++ b/src/DotNetOpenAuth.Core/Logger.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth { using DotNetOpenAuth.Loggers; using DotNetOpenAuth.Messaging; using log4net.Core; + using Validation; /// <summary> /// A general logger for the entire DotNetOpenAuth library. diff --git a/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs b/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs index 4f4bf0e..b50d249 100644 --- a/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs +++ b/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs @@ -14,6 +14,7 @@ namespace DotNetOpenAuth.Messaging { using System.Security.Cryptography; using System.Text; using DotNetOpenAuth.Messaging.Bindings; + using Validation; /// <summary> /// A compact binary <see cref="DataBag"/> serialization class. @@ -45,7 +46,7 @@ namespace DotNetOpenAuth.Messaging { /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param> protected internal BinaryDataBagFormatter(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) : base(cryptoKeyStore, bucket, signed, encrypted, compressed, minimumAge, maximumAge, decodeOnceOnly) { - Requires.True((cryptoKeyStore != null && bucket != null) || (!signed && !encrypted), null); + Requires.That((cryptoKeyStore != null && bucket != null) || (!signed && !encrypted), null, "Signing or encryption requires a crypto key store and bucket."); } /// <summary> diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs index 42eea15..edf62c4 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs @@ -13,6 +13,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System.Security.Cryptography; using System.Text; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// Provides RSA encryption of symmetric keys to protect them from a theft of @@ -42,7 +43,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { public AsymmetricCryptoKeyStoreWrapper(ICryptoKeyStore dataStore, RSACryptoServiceProvider asymmetricCrypto) { Requires.NotNull(dataStore, "dataStore"); Requires.NotNull(asymmetricCrypto, "asymmetricCrypto"); - Requires.True(!asymmetricCrypto.PublicOnly, "asymmetricCrypto"); + Requires.That(!asymmetricCrypto.PublicOnly, "asymmetricCrypto", "Private key required."); this.dataStore = dataStore; this.asymmetricCrypto = asymmetricCrypto; } @@ -140,7 +141,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { : base(decrypted.Key, decrypted.ExpiresUtc) { Requires.NotNull(encrypted, "encrypted"); Requires.NotNull(decrypted, "decrypted"); - Requires.True(encrypted.ExpiresUtc == decrypted.ExpiresUtc); + Requires.That(encrypted.ExpiresUtc == decrypted.ExpiresUtc, "encrypted", "encrypted and decrypted expirations must equal."); this.EncryptedKey = encrypted.Key; } diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs index 3fa50d4..b4a5129 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System.Linq; using System.Text; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A cryptographic key and metadata concerning it. @@ -34,7 +35,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// <param name="expiresUtc">The expires UTC.</param> public CryptoKey(byte[] key, DateTime expiresUtc) { Requires.NotNull(key, "key"); - Requires.True(expiresUtc.Kind == DateTimeKind.Utc, "expiresUtc"); + Requires.That(expiresUtc.Kind == DateTimeKind.Utc, "expiresUtc", "Time must be expressed in UTC."); this.key = key; this.expiresUtc = expiresUtc; } diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs index 88b8fed..6e6d3bc 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System; using System.Diagnostics.Contracts; using System.Globalization; + using Validation; /// <summary> /// An exception thrown when a message is received that exceeds the maximum message age limit. @@ -21,7 +22,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// <param name="faultedMessage">The expired message.</param> public ExpiredMessageException(DateTime utcExpirationDate, IProtocolMessage faultedMessage) : base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.ExpiredMessage, utcExpirationDate.ToLocalTime(), DateTime.Now), faultedMessage) { - Requires.True(utcExpirationDate.Kind == DateTimeKind.Utc, "utcExpirationDate"); + Requires.Argument(utcExpirationDate.Kind == DateTimeKind.Utc, "utcExpirationDate", "Time must be expressed as UTC."); } /// <summary> diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs index 2e43bba..7493b19 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System.Linq; using System.Text; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A persistent store for rotating symmetric cryptographic keys. diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs index 7e39536..8c2afec 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System; using System.Diagnostics; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A binding element that checks/verifies a nonce message part. diff --git a/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs index 16e92a8..322586a 100644 --- a/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging { using System.IO; using System.Net; using System.Text; + using Validation; /// <summary> /// Cached details on the response from a direct web request to a remote party. diff --git a/src/DotNetOpenAuth.Core/Messaging/Channel.cs b/src/DotNetOpenAuth.Core/Messaging/Channel.cs index f8ac6a1..09a203e 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Channel.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Channel.cs @@ -24,6 +24,7 @@ namespace DotNetOpenAuth.Messaging { using System.Web; using System.Xml; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// Manages sending direct messages to a remote party and receiving responses. @@ -201,7 +202,7 @@ namespace DotNetOpenAuth.Messaging { } set { - Requires.InRange(value >= 500 && value <= 4096, "value"); + Requires.Range(value >= 500 && value <= 4096, "value"); this.maximumIndirectMessageUrlLength = value; } } @@ -308,7 +309,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public void Send(IProtocolMessage message) { - Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); + RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); Requires.NotNull(message, "message"); this.PrepareResponse(message).Respond(HttpContext.Current, true); } @@ -327,7 +328,7 @@ namespace DotNetOpenAuth.Messaging { /// Use the <see cref="Send"/> method instead for web forms. /// </remarks> public void Respond(IProtocolMessage message) { - Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); + RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); Requires.NotNull(message, "message"); this.PrepareResponse(message).Respond(); } @@ -620,7 +621,7 @@ namespace DotNetOpenAuth.Messaging { /// <returns>An HttpContextBase instance.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Allocates memory")] protected internal virtual HttpContextBase GetHttpContext() { - Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); return new HttpContextWrapper(HttpContext.Current); } @@ -634,7 +635,7 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Costly call should not be a property.")] protected internal virtual HttpRequestBase GetRequestFromContext() { - Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); Contract.Ensures(Contract.Result<HttpRequestBase>() != null); Contract.Assume(HttpContext.Current.Request.Url != null); @@ -729,7 +730,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual IProtocolMessage RequestCore(IDirectedProtocolMessage request) { Requires.NotNull(request, "request"); - Requires.True(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); HttpWebRequest webRequest = this.CreateHttpRequest(request); var directRequest = request as IHttpDirectRequest; @@ -837,8 +838,8 @@ namespace DotNetOpenAuth.Messaging { /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> protected virtual OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) { Requires.NotNull(message, "message"); - Requires.True(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); - Requires.True((message.HttpMethods & (HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest)) != 0, "message"); + Requires.That(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That((message.HttpMethods & (HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest)) != 0, "message", "GET or POST expected."); Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); Contract.Assert(message != null && message.Recipient != null); @@ -887,7 +888,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] protected virtual OutgoingWebResponse Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) { Requires.NotNull(message, "message"); - Requires.True(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); Requires.NotNull(fields, "fields"); Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); @@ -924,7 +925,7 @@ namespace DotNetOpenAuth.Messaging { [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")] protected virtual OutgoingWebResponse CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) { Requires.NotNull(message, "message"); - Requires.True(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); Requires.NotNull(fields, "fields"); Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); @@ -973,7 +974,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { Requires.NotNull(request, "request"); - Requires.True(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); Contract.Ensures(Contract.Result<HttpWebRequest>() != null); throw new NotImplementedException(); } @@ -1086,7 +1087,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual HttpWebRequest InitializeRequestAsGet(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); - Requires.True(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient); var messageAccessor = this.MessageDescriptions.GetAccessor(requestMessage); var fields = messageAccessor.Serialize(); @@ -1110,7 +1111,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual HttpWebRequest InitializeRequestAsHead(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); - Requires.True(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient); HttpWebRequest request = this.InitializeRequestAsGet(requestMessage); request.Method = "HEAD"; @@ -1350,7 +1351,7 @@ namespace DotNetOpenAuth.Messaging { /// <returns>The properly ordered list of elements.</returns> /// <exception cref="ProtocolException">Thrown when the binding elements are incomplete or inconsistent with each other.</exception> private static IEnumerable<IChannelBindingElement> ValidateAndPrepareBindingElements(IEnumerable<IChannelBindingElement> elements) { - Requires.NullOrWithNoNullElements(elements, "elements"); + Requires.NullOrNotNullElements(elements, "elements"); Contract.Ensures(Contract.Result<IEnumerable<IChannelBindingElement>>() != null); if (elements == null) { return new IChannelBindingElement[0]; diff --git a/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs b/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs index b48d45b..82f2955 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// Code contract for the <see cref="Channel"/> class. diff --git a/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs b/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs index f3ebc04..5cf74ad 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs @@ -7,6 +7,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// The data packet sent with Channel events. diff --git a/src/DotNetOpenAuth.Core/Messaging/DataBag.cs b/src/DotNetOpenAuth.Core/Messaging/DataBag.cs index cdf4033..66b83ac 100644 --- a/src/DotNetOpenAuth.Core/Messaging/DataBag.cs +++ b/src/DotNetOpenAuth.Core/Messaging/DataBag.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.Messaging { using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A collection of message parts that will be serialized into a single string, diff --git a/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs b/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs index e7ac254..f60423b 100644 --- a/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs +++ b/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs @@ -17,6 +17,7 @@ namespace DotNetOpenAuth.Messaging { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// A serializer for <see cref="DataBag"/>-derived types @@ -110,8 +111,8 @@ namespace DotNetOpenAuth.Messaging { /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param> protected DataBagFormatterBase(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) : this(signed, encrypted, compressed, maximumAge, decodeOnceOnly) { - Requires.True(!string.IsNullOrEmpty(bucket) || cryptoKeyStore == null, null); - Requires.True(cryptoKeyStore != null || (!signed && !encrypted), null); + Requires.That(!string.IsNullOrEmpty(bucket) || cryptoKeyStore == null, "bucket", "Bucket name required when cryptoKeyStore is non-null."); + Requires.That(cryptoKeyStore != null || (!signed && !encrypted), "cryptoKeyStore", "cryptoKeyStore required if signing or encrypting."); this.cryptoKeyStore = cryptoKeyStore; this.cryptoKeyBucket = bucket; @@ -129,8 +130,8 @@ namespace DotNetOpenAuth.Messaging { /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param> /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param> private DataBagFormatterBase(bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) { - Requires.True(signed || decodeOnceOnly == null, null); - Requires.True(maximumAge.HasValue || decodeOnceOnly == null, null); + Requires.That(signed || decodeOnceOnly == null, "decodeOnceOnly", "Nonce only valid with signing."); + Requires.That(maximumAge.HasValue || decodeOnceOnly == null, "decodeOnceOnly", "Nonce requires a maximum message age."); this.signed = signed; this.maximumAge = maximumAge; @@ -303,7 +304,7 @@ namespace DotNetOpenAuth.Messaging { [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")] private byte[] CalculateSignature(byte[] bytesToSign, string symmetricSecretHandle) { Requires.NotNull(bytesToSign, "bytesToSign"); - Requires.ValidState(this.asymmetricSigning != null || this.cryptoKeyStore != null); + RequiresEx.ValidState(this.asymmetricSigning != null || this.cryptoKeyStore != null); Contract.Ensures(Contract.Result<byte[]>() != null); if (this.asymmetricSigning != null) { @@ -328,7 +329,7 @@ namespace DotNetOpenAuth.Messaging { /// The encrypted value. /// </returns> private byte[] Encrypt(byte[] value, out string symmetricSecretHandle) { - Requires.ValidState(this.asymmetricEncrypting != null || this.cryptoKeyStore != null); + Assumes.True(this.asymmetricEncrypting != null || this.cryptoKeyStore != null); if (this.asymmetricEncrypting != null) { symmetricSecretHandle = null; @@ -349,7 +350,7 @@ namespace DotNetOpenAuth.Messaging { /// The decrypted value. /// </returns> private byte[] Decrypt(byte[] value, string symmetricSecretHandle) { - Requires.ValidState(this.asymmetricEncrypting != null || symmetricSecretHandle != null); + RequiresEx.ValidState(this.asymmetricEncrypting != null || symmetricSecretHandle != null); if (this.asymmetricEncrypting != null) { return this.asymmetricEncrypting.DecryptWithRandomSymmetricKey(value); diff --git a/src/DotNetOpenAuth.Core/Messaging/EnumerableCacheExtensions.cs b/src/DotNetOpenAuth.Core/Messaging/EnumerableCacheExtensions.cs index 5e9cf93..f5c4b36 100644 --- a/src/DotNetOpenAuth.Core/Messaging/EnumerableCacheExtensions.cs +++ b/src/DotNetOpenAuth.Core/Messaging/EnumerableCacheExtensions.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Messaging { using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// Extension methods for <see cref="IEnumerable<T>"/> types. diff --git a/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs b/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs index 2237cc7..95c87f1 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.Messaging { using System.Diagnostics.Contracts; using System.Globalization; using System.Web; + using Validation; /// <summary> /// A collection of error checking and reporting methods. diff --git a/src/DotNetOpenAuth.Core/Messaging/HmacAlgorithms.cs b/src/DotNetOpenAuth.Core/Messaging/HmacAlgorithms.cs index 872b4ac..c80ebfe 100644 --- a/src/DotNetOpenAuth.Core/Messaging/HmacAlgorithms.cs +++ b/src/DotNetOpenAuth.Core/Messaging/HmacAlgorithms.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Messaging { using System.Linq; using System.Security.Cryptography; using System.Text; + using Validation; /// <summary> /// HMAC-SHA algorithm names that can be passed to the <see cref="HMAC.Create(string)"/> method. diff --git a/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs b/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs index 75da833..465ed43 100644 --- a/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs +++ b/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs @@ -20,6 +20,7 @@ namespace DotNetOpenAuth.Messaging { using System.Net.Mime; using System.ServiceModel.Channels; using System.Web; + using Validation; /// <summary> /// A property store of details of an incoming HTTP request. diff --git a/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs index 1047ec5..d52e1d5 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs @@ -7,6 +7,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// An interface that must be implemented by message transforms/validators in order @@ -114,7 +115,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> MessageProtections? IChannelBindingElement.ProcessOutgoingMessage(IProtocolMessage message) { Requires.NotNull(message, "message"); - Requires.ValidState(((IChannelBindingElement)this).Channel != null); + Assumes.True(((IChannelBindingElement)this).Channel != null); throw new NotImplementedException(); } @@ -137,7 +138,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> MessageProtections? IChannelBindingElement.ProcessIncomingMessage(IProtocolMessage message) { Requires.NotNull(message, "message"); - Requires.ValidState(((IChannelBindingElement)this).Channel != null); + RequiresEx.ValidState(((IChannelBindingElement)this).Channel != null); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs b/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs index 0d1ab03..65badc1 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs @@ -7,6 +7,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A serializer for <see cref="DataBag"/>-derived types diff --git a/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs index 7878405..3a60280 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.Messaging { using System.IO; using System.Net; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A contract for <see cref="HttpWebRequest"/> handling. @@ -165,7 +166,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) { Requires.NotNull(request, "request"); - Requires.Support(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported); + RequiresEx.Support(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported); ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name)); throw new System.NotImplementedException(); } @@ -212,7 +213,7 @@ namespace DotNetOpenAuth.Messaging { Requires.NotNull(request, "request"); Contract.Ensures(Contract.Result<IncomingWebResponse>() != null); Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null); - Requires.Support(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported); + RequiresEx.Support(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported); ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name)); throw new System.NotImplementedException(); diff --git a/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs index e45ac1d..49b9086 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A tool to analyze an incoming message to figure out what concrete class diff --git a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs index cdb26ae..285eddd 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs @@ -13,6 +13,7 @@ namespace DotNetOpenAuth.Messaging { using System.Net; using System.Net.Mime; using System.Text; + using Validation; /// <summary> /// Details on the incoming response from a direct web request to a remote party. diff --git a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs index 5c94e47..6798ed3 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics.Contracts; using System.IO; + using Validation; /// <summary> /// Code contract for the <see cref="IncomingWebResponse"/> class. @@ -45,8 +46,8 @@ namespace DotNetOpenAuth.Messaging { /// be the self same instance. /// </remarks> internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) { - Requires.InRange(maximumBytesToCache >= 0, "maximumBytesToCache"); - Requires.ValidState(this.RequestUri != null); + Requires.Range(maximumBytesToCache >= 0, "maximumBytesToCache"); + RequiresEx.ValidState(this.RequestUri != null); Contract.Ensures(Contract.Result<CachedDirectWebResponse>() != null); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs b/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs index d0988c8..daf780e 100644 --- a/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs +++ b/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.ObjectModel; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A KeyedCollection whose item -> key transform is provided via a delegate diff --git a/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs b/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs index cf5ea92..808d42b 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// An immutable description of a URL that receives messages. @@ -23,8 +24,8 @@ namespace DotNetOpenAuth.Messaging { public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method) : this(new Uri(locationUri), method) { Requires.NotNull(locationUri, "locationUri"); - Requires.InRange(method != HttpDeliveryMethods.None, "method"); - Requires.InRange((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired); + Requires.Range(method != HttpDeliveryMethods.None, "method"); + Requires.Range((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired); } /// <summary> @@ -34,8 +35,8 @@ namespace DotNetOpenAuth.Messaging { /// <param name="method">The HTTP method(s) allowed.</param> public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method) { Requires.NotNull(location, "location"); - Requires.InRange(method != HttpDeliveryMethods.None, "method"); - Requires.InRange((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired); + Requires.Range(method != HttpDeliveryMethods.None, "method"); + Requires.Range((method & HttpDeliveryMethods.HttpVerbMask) != 0, "method", MessagingStrings.GetOrPostFlagsRequired); this.Location = location; this.AllowedMethods = method; diff --git a/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs b/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs index 7391867..81ae8df 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs @@ -14,6 +14,7 @@ namespace DotNetOpenAuth.Messaging { using System.Reflection; using System.Xml; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// Serializes/deserializes OAuth messages for/from transit. @@ -33,7 +34,7 @@ namespace DotNetOpenAuth.Messaging { /// that will be serialized and deserialized using this class.</param> [ContractVerification(false)] // bugs/limitations in CC static analysis private MessageSerializer(Type messageType) { - Requires.NotNullSubtype<IMessage>(messageType, "messageType"); + RequiresEx.NotNullSubtype<IMessage>(messageType, "messageType"); Contract.Ensures(this.messageType != null); this.messageType = messageType; } @@ -45,7 +46,7 @@ namespace DotNetOpenAuth.Messaging { /// <returns>A message serializer for the given message type.</returns> [ContractVerification(false)] // bugs/limitations in CC static analysis internal static MessageSerializer Get(Type messageType) { - Requires.NotNullSubtype<IMessage>(messageType, "messageType"); + RequiresEx.NotNullSubtype<IMessage>(messageType, "messageType"); return new MessageSerializer(messageType); } diff --git a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs index e859162..8abe3d7 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs @@ -29,6 +29,7 @@ namespace DotNetOpenAuth.Messaging { using System.Xml; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// A grab-bag of utility methods useful for the channel stack of the protocol. @@ -198,7 +199,7 @@ namespace DotNetOpenAuth.Messaging { [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "The Uri merging requires use of a string value.")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Expensive call should not be a property.")] public static Uri GetRequestUrlFromContext() { - Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); return new HttpRequestWrapper(HttpContext.Current.Request).GetPublicFacingUrl(); } @@ -695,8 +696,8 @@ namespace DotNetOpenAuth.Messaging { /// <param name="allowableCharacters">The allowable characters.</param> /// <returns>A random string.</returns> internal static string GetRandomString(int length, string allowableCharacters) { - Requires.InRange(length >= 0, "length"); - Requires.True(allowableCharacters != null && allowableCharacters.Length >= 2, "allowableCharacters"); + Requires.Range(length >= 0, "length"); + Requires.That(allowableCharacters != null && allowableCharacters.Length >= 2, "allowableCharacters", "At least two allowable characters required."); char[] randomString = new char[length]; var random = NonCryptoRandomDataGenerator; @@ -936,7 +937,7 @@ namespace DotNetOpenAuth.Messaging { internal static KeyValuePair<string, CryptoKey> GetCurrentKey(this ICryptoKeyStore cryptoKeyStore, string bucket, TimeSpan minimumRemainingLife, int keySize = 256) { Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); Requires.NotNullOrEmpty(bucket, "bucket"); - Requires.True(keySize % 8 == 0, "keySize"); + Requires.That(keySize % 8 == 0, "keySize", "Key size must be a multiple of 8."); var cryptoKeyPair = cryptoKeyStore.GetKeys(bucket).FirstOrDefault(pair => pair.Value.Key.Length == keySize / 8); if (cryptoKeyPair.Value == null || cryptoKeyPair.Value.ExpiresUtc < DateTime.UtcNow + minimumRemainingLife) { @@ -992,7 +993,7 @@ namespace DotNetOpenAuth.Messaging { compressingStream = new GZipStream(ms, CompressionMode.Compress, true); break; default: - Requires.InRange(false, "method"); + Requires.Range(false, "method"); break; } @@ -1030,7 +1031,7 @@ namespace DotNetOpenAuth.Messaging { decompressingStream = new GZipStream(compressedDataStream, CompressionMode.Decompress, true); break; default: - Requires.InRange(false, "method"); + Requires.Range(false, "method"); break; } @@ -1158,8 +1159,8 @@ namespace DotNetOpenAuth.Messaging { internal static int CopyTo(this Stream copyFrom, Stream copyTo) { Requires.NotNull(copyFrom, "copyFrom"); Requires.NotNull(copyTo, "copyTo"); - Requires.True(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable); - Requires.True(copyTo.CanWrite, "copyTo", MessagingStrings.StreamUnwritable); + Requires.That(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable); + Requires.That(copyTo.CanWrite, "copyTo", MessagingStrings.StreamUnwritable); return CopyUpTo(copyFrom, copyTo, int.MaxValue); } #endif @@ -1178,8 +1179,8 @@ namespace DotNetOpenAuth.Messaging { internal static int CopyUpTo(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy) { Requires.NotNull(copyFrom, "copyFrom"); Requires.NotNull(copyTo, "copyTo"); - Requires.True(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable); - Requires.True(copyTo.CanWrite, "copyTo", MessagingStrings.StreamUnwritable); + Requires.That(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable); + Requires.That(copyTo.CanWrite, "copyTo", MessagingStrings.StreamUnwritable); byte[] buffer = new byte[1024]; int readBytes; @@ -1201,7 +1202,7 @@ namespace DotNetOpenAuth.Messaging { /// <returns>A seekable stream with the same contents as the original.</returns> internal static Stream CreateSnapshot(this Stream copyFrom) { Requires.NotNull(copyFrom, "copyFrom"); - Requires.True(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable); + Requires.That(copyFrom.CanRead, "copyFrom", MessagingStrings.StreamUnreadable); MemoryStream copyTo = new MemoryStream(copyFrom.CanSeek ? (int)copyFrom.Length : 4 * 1024); try { @@ -1221,7 +1222,7 @@ namespace DotNetOpenAuth.Messaging { /// <returns>The newly created instance.</returns> internal static HttpWebRequest Clone(this HttpWebRequest request) { Requires.NotNull(request, "request"); - Requires.True(request.RequestUri != null, "request"); + Requires.That(request.RequestUri != null, "request", "request.RequestUri cannot be null."); return Clone(request, request.RequestUri); } @@ -1771,7 +1772,7 @@ namespace DotNetOpenAuth.Messaging { /// <returns>The read buffer.</returns> internal static byte[] ReadBuffer(this BinaryReader reader, int maxBufferSize) { Requires.NotNull(reader, "reader"); - Requires.InRange(maxBufferSize > 0 && maxBufferSize < 1024 * 1024, "maxBufferSize"); + Requires.Range(maxBufferSize > 0 && maxBufferSize < 1024 * 1024, "maxBufferSize"); int length = reader.ReadInt32(); ErrorUtilities.VerifyProtocol(length <= maxBufferSize, MessagingStrings.DataCorruptionDetected); byte[] buffer = new byte[length]; diff --git a/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs b/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs index 055e4b9..8a175d6 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging { using System.IO; using System.Net; using System.Text; + using Validation; /// <summary> /// Represents a single part in a HTTP multipart POST request. diff --git a/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs index 2c3ddac..2ad6cfc 100644 --- a/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.Messaging { using System.IO; using System.Net; using System.Text; + using Validation; /// <summary> /// A live network HTTP response diff --git a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs index e1e9d53..2e99e4c 100644 --- a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs @@ -16,6 +16,7 @@ namespace DotNetOpenAuth.Messaging { using System.Text; using System.Threading; using System.Web; + using Validation; /// <summary> /// A protocol message (request or response) that passes from this @@ -136,7 +137,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public virtual void Send() { - Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); this.Send(HttpContext.Current); } @@ -178,7 +179,7 @@ namespace DotNetOpenAuth.Messaging { /// Use the <see cref="Send()"/> method instead for web forms. /// </remarks> public virtual void Respond() { - Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); this.Respond(HttpContext.Current); } diff --git a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs index 7691cc4..d8bb1a6 100644 --- a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs +++ b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.Messaging { using System.Diagnostics.Contracts; using System.Web.Mvc; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// An ASP.NET MVC structure to represent the response to send diff --git a/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs b/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs index c2dc34e..4d5c418 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.Messaging { using System.Collections.Generic; using System.Linq; using System.Text; + using Validation; /// <summary> /// An exception to represent errors in the local or remote implementation of the protocol diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/DefaultEncoderAttribute.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/DefaultEncoderAttribute.cs index d827972..adf0f33 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/DefaultEncoderAttribute.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/DefaultEncoderAttribute.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System.Collections.Generic; using System.Linq; using System.Text; + using Validation; /// <summary> /// Allows a custom class or struct to be serializable between itself and a string representation. @@ -21,7 +22,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// <param name="converterType">The <see cref="IMessagePartEncoder"/> implementing type to use for serializing this type.</param> public DefaultEncoderAttribute(Type converterType) { Requires.NotNull(converterType, "converterType"); - Requires.True(typeof(IMessagePartEncoder).IsAssignableFrom(converterType), "Argument must be a type that implements {0}.", typeof(IMessagePartEncoder).Name); + Requires.That(typeof(IMessagePartEncoder).IsAssignableFrom(converterType), "Argument must be a type that implements {0}.", typeof(IMessagePartEncoder).Name); this.Encoder = (IMessagePartEncoder)Activator.CreateInstance(converterType); } diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs index 6186cd7..98c9cce 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System.Diagnostics.Contracts; using System.Linq; using System.Text; + using Validation; /// <summary> /// An interface describing how various objects can be serialized and deserialized between their object and string forms. diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs index 7e67842..8a34be6 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System.Globalization; using System.Linq; using System.Reflection; + using Validation; /// <summary> /// A mapping between serialized key names and <see cref="MessagePart"/> instances describing @@ -30,7 +31,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// <param name="messageType">Type of the message.</param> /// <param name="messageVersion">The message version.</param> internal MessageDescription(Type messageType, Version messageVersion) { - Requires.NotNullSubtype<IMessage>(messageType, "messageType"); + RequiresEx.NotNullSubtype<IMessage>(messageType, "messageType"); Requires.NotNull(messageVersion, "messageVersion"); this.MessageType = messageType; diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs index 3517abc..e3d612e 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; + using Validation; /// <summary> /// A cache of <see cref="MessageDescription"/> instances. @@ -68,7 +69,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Assume(System.Boolean,System.String,System.String)", Justification = "No localization required.")] [Pure] internal MessageDescription Get(Type messageType, Version messageVersion) { - Requires.NotNullSubtype<IMessage>(messageType, "messageType"); + RequiresEx.NotNullSubtype<IMessage>(messageType, "messageType"); Requires.NotNull(messageVersion, "messageVersion"); Contract.Ensures(Contract.Result<MessageDescription>() != null); diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs index cf44863..c3e6f65 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// Wraps an <see cref="IMessage"/> instance in a dictionary that diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs index a6e8da2..6c9aef3 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs @@ -16,6 +16,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System.Reflection; using System.Xml; using DotNetOpenAuth.Configuration; + using Validation; /// <summary> /// Describes an individual member of a message and assists in its serialization. @@ -106,7 +107,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Unavoidable"), SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code contracts requires it.")] internal MessagePart(MemberInfo member, MessagePartAttribute attribute) { Requires.NotNull(member, "member"); - Requires.True(member is FieldInfo || member is PropertyInfo, "member"); + Requires.That(member is FieldInfo || member is PropertyInfo, "member", "Member must be a property or field."); Requires.NotNull(attribute, "attribute"); this.field = member as FieldInfo; @@ -203,7 +204,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// </summary> internal string StaticConstantValue { get { - Requires.ValidState(this.IsConstantValueAvailableStatically); + RequiresEx.ValidState(this.IsConstantValueAvailableStatically); return this.ToString(this.field.GetValue(null), false); } } diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs index 4139f52..7acff7e 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs @@ -7,6 +7,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System; using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A pair of conversion functions to map some type to a string and back again. diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs index 762b54b..37ab864 100644 --- a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs +++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging { using System.Reflection; using System.Text; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// A message factory that automatically selects the message type based on the incoming data. @@ -42,7 +43,7 @@ namespace DotNetOpenAuth.Messaging { /// <param name="messageTypes">The message types that this factory may instantiate.</param> public virtual void AddMessageTypes(IEnumerable<MessageDescription> messageTypes) { Requires.NotNull(messageTypes, "messageTypes"); - Requires.True(messageTypes.All(msg => msg != null), "messageTypes"); + Requires.NullOrNotNullElements(messageTypes, "messageTypes"); var unsupportedMessageTypes = new List<MessageDescription>(0); foreach (MessageDescription messageDescription in messageTypes) { @@ -249,7 +250,7 @@ namespace DotNetOpenAuth.Messaging { private static int GetDerivationDistance(Type assignableType, Type derivedType) { Requires.NotNull(assignableType, "assignableType"); Requires.NotNull(derivedType, "derivedType"); - Requires.True(assignableType.IsAssignableFrom(derivedType), "assignableType"); + Requires.That(assignableType.IsAssignableFrom(derivedType), "assignableType", "Types are not related as required."); // If this is the two types are equivalent... if (derivedType.IsAssignableFrom(assignableType)) diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs index 7ca5d45..2c9f0ce 100644 --- a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs +++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.Messaging { using System.Linq; using System.Text; using Reflection; + using Validation; /// <summary> /// A channel that uses the standard message factory. diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs index adca925..2383a5b 100644 --- a/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs +++ b/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs @@ -13,6 +13,7 @@ namespace DotNetOpenAuth.Messaging { using System.Net.Sockets; using System.Reflection; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// The default handler for transmitting <see cref="HttpWebRequest"/> instances diff --git a/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs index 25a7bbb..be0182d 100644 --- a/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs +++ b/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs @@ -17,6 +17,7 @@ namespace DotNetOpenAuth.Messaging { using System.Text.RegularExpressions; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A paranoid HTTP get/post request engine. It helps to protect against attacks from remote @@ -112,7 +113,7 @@ namespace DotNetOpenAuth.Messaging { } set { - Requires.InRange(value >= 2048, "value"); + Requires.Range(value >= 2048, "value"); this.maximumBytesToRead = value; } } @@ -127,7 +128,7 @@ namespace DotNetOpenAuth.Messaging { } set { - Requires.InRange(value >= 0, "value"); + Requires.Range(value >= 0, "value"); this.maximumRedirections = value; } } diff --git a/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs b/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs index 242175e..b5ae6bc 100644 --- a/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs +++ b/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs @@ -15,6 +15,7 @@ namespace DotNetOpenAuth.Messaging { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// A serializer for <see cref="DataBag"/>-derived types @@ -46,7 +47,7 @@ namespace DotNetOpenAuth.Messaging { /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param> protected internal UriStyleMessageFormatter(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) : base(cryptoKeyStore, bucket, signed, encrypted, compressed, minimumAge, maximumAge, decodeOnceOnly) { - Requires.True((cryptoKeyStore != null && !string.IsNullOrEmpty(bucket)) || (!signed && !encrypted), null); + Requires.That((cryptoKeyStore != null && !string.IsNullOrEmpty(bucket)) || (!signed && !encrypted), null, "Signing or encryption requires a cryptoKeyStore and bucket."); } /// <summary> diff --git a/src/DotNetOpenAuth.Core/Reporting.cs b/src/DotNetOpenAuth.Core/Reporting.cs index c682717..dc8482f 100644 --- a/src/DotNetOpenAuth.Core/Reporting.cs +++ b/src/DotNetOpenAuth.Core/Reporting.cs @@ -23,6 +23,7 @@ namespace DotNetOpenAuth { using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; + using Validation; /// <summary> /// The statistical reporting mechanism used so this library's project authors @@ -567,7 +568,7 @@ namespace DotNetOpenAuth { /// </remarks> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")] private static Guid GetOrCreateOriginIdentity() { - Requires.ValidState(file != null); + RequiresEx.ValidState(file != null, "file not set."); Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); Guid identityGuid = Guid.Empty; diff --git a/src/DotNetOpenAuth.Core/Requires.cs b/src/DotNetOpenAuth.Core/Requires.cs deleted file mode 100644 index 7d4d5be..0000000 --- a/src/DotNetOpenAuth.Core/Requires.cs +++ /dev/null @@ -1,255 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="Requires.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.Globalization; - using System.Linq; - using System.Text; - using DotNetOpenAuth.Messaging; - - /// <summary> - /// Argument validation checks that throw some kind of ArgumentException when they fail (unless otherwise noted). - /// </summary> - internal static class Requires { - /// <summary> - /// Validates that a given parameter is not null. - /// </summary> - /// <typeparam name="T">The type of the parameter</typeparam> - /// <param name="value">The value.</param> - /// <param name="parameterName">Name of the parameter.</param> - /// <returns>The tested value, guaranteed to not be null.</returns> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static T NotNull<T>(T value, string parameterName) where T : class { - if (value == null) { - throw new ArgumentNullException(parameterName); - } - - Contract.EndContractBlock(); - return value; - } - - /// <summary> - /// Validates that a parameter is not null or empty. - /// </summary> - /// <param name="value">The value.</param> - /// <param name="parameterName">Name of the parameter.</param> - /// <returns>The validated value.</returns> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static string NotNullOrEmpty(string value, string parameterName) { - NotNull(value, parameterName); - True(value.Length > 0, parameterName, Strings.EmptyStringNotAllowed); - Contract.Ensures(Contract.Result<string>() == value); - Contract.EndContractBlock(); - return value; - } - - /// <summary> - /// Validates that an array is not null or empty. - /// </summary> - /// <typeparam name="T">The type of the elements in the sequence.</typeparam> - /// <param name="value">The value.</param> - /// <param name="parameterName">Name of the parameter.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void NotNullOrEmpty<T>(IEnumerable<T> value, string parameterName) { - NotNull(value, parameterName); - True(value.Any(), parameterName, Strings.InvalidArgument); - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates that an argument is either null or is a sequence with no null elements. - /// </summary> - /// <typeparam name="T">The type of elements in the sequence.</typeparam> - /// <param name="sequence">The sequence.</param> - /// <param name="parameterName">Name of the parameter.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void NullOrWithNoNullElements<T>(IEnumerable<T> sequence, string parameterName) where T : class { - if (sequence != null) { - if (sequence.Any(e => e == null)) { - throw new ArgumentException(MessagingStrings.SequenceContainsNullElement, parameterName); - } - } - } - - /// <summary> - /// Validates some expression describing the acceptable range for an argument evaluates to true. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="ArgumentOutOfRangeException"/>.</param> - /// <param name="parameterName">Name of the parameter.</param> - /// <param name="message">The message to include with the exception.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void InRange(bool condition, string parameterName, string message = null) { - if (!condition) { - throw new ArgumentOutOfRangeException(parameterName, message); - } - - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates some expression describing the acceptable condition for an argument evaluates to true. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="ArgumentException"/>.</param> - /// <param name="parameterName">Name of the parameter.</param> - /// <param name="message">The message to include with the exception.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void True(bool condition, string parameterName = null, string message = null) { - if (!condition) { - throw new ArgumentException(message ?? Strings.InvalidArgument, parameterName); - } - - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates some expression describing the acceptable condition for an argument evaluates to true. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="ArgumentException"/>.</param> - /// <param name="parameterName">Name of the parameter.</param> - /// <param name="unformattedMessage">The unformatted message.</param> - /// <param name="args">Formatting arguments.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void True(bool condition, string parameterName, string unformattedMessage, params object[] args) { - if (!condition) { - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, unformattedMessage, args), parameterName); - } - - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates some expression describing the acceptable condition for an argument evaluates to true. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void ValidState(bool condition) { - if (!condition) { - throw new InvalidOperationException(); - } - - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates some expression describing the acceptable condition for an argument evaluates to true. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param> - /// <param name="message">The message to include with the exception.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void ValidState(bool condition, string message) { - if (!condition) { - throw new InvalidOperationException(message); - } - - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates some expression describing the acceptable condition for an argument evaluates to true. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param> - /// <param name="unformattedMessage">The unformatted message.</param> - /// <param name="args">Formatting arguments.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void ValidState(bool condition, string unformattedMessage, params object[] args) { - if (!condition) { - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, unformattedMessage, args)); - } - - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates that some argument describes a type that is or derives from a required type. - /// </summary> - /// <typeparam name="T">The type that the argument must be or derive from.</typeparam> - /// <param name="type">The type given in the argument.</param> - /// <param name="parameterName">Name of the parameter.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void NotNullSubtype<T>(Type type, string parameterName) { - NotNull(type, parameterName); - True(typeof(T).IsAssignableFrom(type), parameterName, MessagingStrings.UnexpectedType, typeof(T).FullName, type.FullName); - - Contract.EndContractBlock(); - } - - /// <summary> - /// Validates some expression describing the acceptable condition for an argument evaluates to true. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="FormatException"/>.</param> - /// <param name="message">The message.</param> -#if !CLR4 - [ContractArgumentValidator] -#endif - [Pure, DebuggerStepThrough] - internal static void Format(bool condition, string message) { - if (!condition) { - throw new FormatException(message); - } - - Contract.EndContractBlock(); - } - - /// <summary> - /// Throws an <see cref="NotSupportedException"/> if a condition does not evaluate to <c>true</c>. - /// </summary> - /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="NotSupportedException"/>.</param> - /// <param name="message">The message.</param> - [Pure, DebuggerStepThrough] - internal static void Support(bool condition, string message) { - if (!condition) { - throw new NotSupportedException(message); - } - } - - /// <summary> - /// Throws an <see cref="ArgumentException"/> - /// </summary> - /// <param name="parameterName">Name of the parameter.</param> - /// <param name="message">The message.</param> - [Pure, DebuggerStepThrough] - internal static void Fail(string parameterName, string message) { - throw new ArgumentException(message, parameterName); - } - } -} diff --git a/src/DotNetOpenAuth.Core/RequiresEx.cs b/src/DotNetOpenAuth.Core/RequiresEx.cs new file mode 100644 index 0000000..8779b2f --- /dev/null +++ b/src/DotNetOpenAuth.Core/RequiresEx.cs @@ -0,0 +1,119 @@ +//----------------------------------------------------------------------- +// <copyright file="RequiresEx.cs" company="Outercurve Foundation"> +// Copyright (c) Outercurve Foundation. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Diagnostics.Contracts; + using System.Globalization; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using Validation; + + /// <summary> + /// Argument validation checks that throw some kind of ArgumentException when they fail (unless otherwise noted). + /// </summary> + internal static class RequiresEx { + /// <summary> + /// Validates some expression describing the acceptable condition for an argument evaluates to true. + /// </summary> + /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param> +#if !CLR4 + [ContractArgumentValidator] +#endif + [Pure, DebuggerStepThrough] + internal static void ValidState(bool condition) { + if (!condition) { + throw new InvalidOperationException(); + } + + Contract.EndContractBlock(); + } + + /// <summary> + /// Validates some expression describing the acceptable condition for an argument evaluates to true. + /// </summary> + /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param> + /// <param name="message">The message to include with the exception.</param> +#if !CLR4 + [ContractArgumentValidator] +#endif + [Pure, DebuggerStepThrough] + internal static void ValidState(bool condition, string message) { + if (!condition) { + throw new InvalidOperationException(message); + } + + Contract.EndContractBlock(); + } + + /// <summary> + /// Validates some expression describing the acceptable condition for an argument evaluates to true. + /// </summary> + /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="InvalidOperationException"/>.</param> + /// <param name="unformattedMessage">The unformatted message.</param> + /// <param name="args">Formatting arguments.</param> +#if !CLR4 + [ContractArgumentValidator] +#endif + [Pure, DebuggerStepThrough] + internal static void ValidState(bool condition, string unformattedMessage, params object[] args) { + if (!condition) { + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, unformattedMessage, args)); + } + + Contract.EndContractBlock(); + } + + /// <summary> + /// Validates that some argument describes a type that is or derives from a required type. + /// </summary> + /// <typeparam name="T">The type that the argument must be or derive from.</typeparam> + /// <param name="type">The type given in the argument.</param> + /// <param name="parameterName">Name of the parameter.</param> +#if !CLR4 + [ContractArgumentValidator] +#endif + [Pure, DebuggerStepThrough] + internal static void NotNullSubtype<T>(Type type, string parameterName) { + Requires.NotNull(type, parameterName); + Requires.That(typeof(T).IsAssignableFrom(type), parameterName, MessagingStrings.UnexpectedType, typeof(T).FullName, type.FullName); + + Contract.EndContractBlock(); + } + + /// <summary> + /// Validates some expression describing the acceptable condition for an argument evaluates to true. + /// </summary> + /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="FormatException"/>.</param> + /// <param name="message">The message.</param> +#if !CLR4 + [ContractArgumentValidator] +#endif + [Pure, DebuggerStepThrough] + internal static void Format(bool condition, string message) { + if (!condition) { + throw new FormatException(message); + } + + Contract.EndContractBlock(); + } + + /// <summary> + /// Throws an <see cref="NotSupportedException"/> if a condition does not evaluate to <c>true</c>. + /// </summary> + /// <param name="condition">The expression that must evaluate to true to avoid an <see cref="NotSupportedException"/>.</param> + /// <param name="message">The message.</param> + [Pure, DebuggerStepThrough] + internal static void Support(bool condition, string message) { + if (!condition) { + throw new NotSupportedException(message); + } + } + } +} diff --git a/src/DotNetOpenAuth.Core/UriUtil.cs b/src/DotNetOpenAuth.Core/UriUtil.cs index c52e1bb..824ab6b 100644 --- a/src/DotNetOpenAuth.Core/UriUtil.cs +++ b/src/DotNetOpenAuth.Core/UriUtil.cs @@ -14,6 +14,7 @@ namespace DotNetOpenAuth { using System.Web; using System.Web.UI; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// Utility methods for working with URIs. diff --git a/src/DotNetOpenAuth.Core/Util.cs b/src/DotNetOpenAuth.Core/Util.cs index a017ea3..fc293d2 100644 --- a/src/DotNetOpenAuth.Core/Util.cs +++ b/src/DotNetOpenAuth.Core/Util.cs @@ -17,6 +17,7 @@ namespace DotNetOpenAuth { using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// A grab-bag utility class. diff --git a/src/DotNetOpenAuth.Core/packages.config b/src/DotNetOpenAuth.Core/packages.config new file mode 100644 index 0000000..10eec89 --- /dev/null +++ b/src/DotNetOpenAuth.Core/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Validation" version="2.0.0.12319" targetFramework="net40" /> +</packages>
\ No newline at end of file |