diff options
Diffstat (limited to 'src/DotNetOpenAuth.Core')
73 files changed, 287 insertions, 1484 deletions
diff --git a/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs b/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs index 7c03c48..cdcd670 100644 --- a/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/DotNetOpenAuthSection.cs @@ -7,7 +7,6 @@ namespace DotNetOpenAuth.Configuration { using System; using System.Configuration; - using System.Diagnostics.Contracts; using System.Web; using System.Web.Configuration; @@ -15,7 +14,6 @@ namespace DotNetOpenAuth.Configuration { /// Represents the section in the host's .config file that configures /// this library's settings. /// </summary> - [ContractVerification(true)] public class DotNetOpenAuthSection : ConfigurationSectionGroup { /// <summary> /// The name of the section under which this library's settings must be found. diff --git a/src/DotNetOpenAuth.Core/Configuration/HostNameElement.cs b/src/DotNetOpenAuth.Core/Configuration/HostNameElement.cs index b46ece9..5386314 100644 --- a/src/DotNetOpenAuth.Core/Configuration/HostNameElement.cs +++ b/src/DotNetOpenAuth.Core/Configuration/HostNameElement.cs @@ -6,12 +6,10 @@ namespace DotNetOpenAuth.Configuration { using System.Configuration; - using System.Diagnostics.Contracts; /// <summary> /// Represents the name of a single host or a regex pattern for host names. /// </summary> - [ContractVerification(true)] internal class HostNameElement : ConfigurationElement { /// <summary> /// Gets the name of the @name attribute. diff --git a/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs b/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs index f009ce5..8f537c3 100644 --- a/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/HostNameOrRegexCollection.cs @@ -7,13 +7,12 @@ namespace DotNetOpenAuth.Configuration { using System.Collections.Generic; 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. /// </summary> - [ContractVerification(true)] internal class HostNameOrRegexCollection : ConfigurationElementCollection { /// <summary> /// Initializes a new instance of the <see cref="HostNameOrRegexCollection"/> class. @@ -63,7 +62,7 @@ namespace DotNetOpenAuth.Configuration { /// An <see cref="T:System.Object"/> that acts as the key for the specified <see cref="T:System.Configuration.ConfigurationElement"/>. /// </returns> protected override object GetElementKey(ConfigurationElement element) { - Contract.Assume(element != null); // this should be Contract.Requires in base class. + Requires.NotNull(element, "element"); return ((HostNameElement)element).Name ?? string.Empty; } } diff --git a/src/DotNetOpenAuth.Core/Configuration/MessagingElement.cs b/src/DotNetOpenAuth.Core/Configuration/MessagingElement.cs index ff98d36..64dfba3 100644 --- a/src/DotNetOpenAuth.Core/Configuration/MessagingElement.cs +++ b/src/DotNetOpenAuth.Core/Configuration/MessagingElement.cs @@ -7,14 +7,12 @@ namespace DotNetOpenAuth.Configuration { using System; using System.Configuration; - using System.Diagnostics.Contracts; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; /// <summary> /// Represents the <messaging> element in the host's .config file. /// </summary> - [ContractVerification(true)] public class MessagingElement : ConfigurationSection { /// <summary> /// The name of the <webResourceUrlProvider> sub-element. @@ -75,7 +73,6 @@ namespace DotNetOpenAuth.Configuration { /// </summary> public static MessagingElement Configuration { get { - Contract.Ensures(Contract.Result<MessagingElement>() != null); return (MessagingElement)ConfigurationManager.GetSection(MessagingElementName) ?? new MessagingElement(); } } diff --git a/src/DotNetOpenAuth.Core/Configuration/ReportingElement.cs b/src/DotNetOpenAuth.Core/Configuration/ReportingElement.cs index 0af8205..f0184a6 100644 --- a/src/DotNetOpenAuth.Core/Configuration/ReportingElement.cs +++ b/src/DotNetOpenAuth.Core/Configuration/ReportingElement.cs @@ -8,7 +8,6 @@ namespace DotNetOpenAuth.Configuration { using System; using System.Collections.Generic; using System.Configuration; - using System.Diagnostics.Contracts; using System.Linq; using System.Text; @@ -76,7 +75,6 @@ namespace DotNetOpenAuth.Configuration { /// </summary> public static ReportingElement Configuration { get { - Contract.Ensures(Contract.Result<ReportingElement>() != null); return (ReportingElement)ConfigurationManager.GetSection(ReportingElementName) ?? new ReportingElement(); } } diff --git a/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs index 96f60bf..de70f64 100644 --- a/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/TrustedProviderConfigurationCollection.cs @@ -9,7 +9,7 @@ namespace DotNetOpenAuth.Configuration { using System.Collections.Generic; 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 3e72722..08bd2a1 100644 --- a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs @@ -8,16 +8,15 @@ namespace DotNetOpenAuth.Configuration { using System; using System.Collections.Generic; using System.Configuration; - using System.Diagnostics.Contracts; using System.Linq; using System.Text; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A collection of <see cref="TypeConfigurationElement<T>"/>. /// </summary> /// <typeparam name="T">The type that all types specified in the elements must derive from.</typeparam> - [ContractVerification(true)] internal class TypeConfigurationCollection<T> : ConfigurationElementCollection where T : class { /// <summary> @@ -44,7 +43,6 @@ namespace DotNetOpenAuth.Configuration { /// <param name="allowInternals">if set to <c>true</c> then internal types may be instantiated.</param> /// <returns>A sequence of instances generated from types in this collection. May be empty, but never null.</returns> internal IEnumerable<T> CreateInstances(bool allowInternals) { - Contract.Ensures(Contract.Result<IEnumerable<T>>() != null); return from element in this.Cast<TypeConfigurationElement<T>>() where !element.IsEmpty select element.CreateInstance(default(T), allowInternals); @@ -68,7 +66,7 @@ namespace DotNetOpenAuth.Configuration { /// An <see cref="T:System.Object"/> that acts as the key for the specified <see cref="T:System.Configuration.ConfigurationElement"/>. /// </returns> protected override object GetElementKey(ConfigurationElement element) { - Contract.Assume(element != null); // this should be Contract.Requires in base class. + Requires.NotNull(element, "element"); TypeConfigurationElement<T> typedElement = (TypeConfigurationElement<T>)element; return (!string.IsNullOrEmpty(typedElement.TypeName) ? typedElement.TypeName : typedElement.XamlSource) ?? string.Empty; } diff --git a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs index edbb614..a3a8140 100644 --- a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs +++ b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs @@ -8,7 +8,6 @@ namespace DotNetOpenAuth.Configuration { using System; using System.Configuration; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.IO; using System.Reflection; using System.Web; @@ -82,8 +81,6 @@ namespace DotNetOpenAuth.Configuration { /// <param name="defaultValue">The value to return if no type is given in the .config file.</param> /// <returns>The newly instantiated type.</returns> public T CreateInstance(T defaultValue) { - Contract.Ensures(Contract.Result<T>() != null || Contract.Result<T>() == defaultValue); - return this.CreateInstance(defaultValue, false); } @@ -95,8 +92,6 @@ namespace DotNetOpenAuth.Configuration { /// <returns>The newly instantiated type.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")] public T CreateInstance(T defaultValue, bool allowInternals) { - Contract.Ensures(Contract.Result<T>() != null || Contract.Result<T>() == defaultValue); - if (this.CustomType != null) { if (!allowInternals) { // Although .NET will usually prevent our instantiating non-public types, @@ -132,7 +127,6 @@ namespace DotNetOpenAuth.Configuration { /// be present. /// </remarks> private static T CreateInstanceFromXaml(Stream xaml) { - Contract.Ensures(Contract.Result<T>() != null); #if CLR4 return (T)XamlServices.Load(xaml); #else diff --git a/src/DotNetOpenAuth.Core/Configuration/UntrustedWebRequestElement.cs b/src/DotNetOpenAuth.Core/Configuration/UntrustedWebRequestElement.cs index b49452a..a16522a 100644 --- a/src/DotNetOpenAuth.Core/Configuration/UntrustedWebRequestElement.cs +++ b/src/DotNetOpenAuth.Core/Configuration/UntrustedWebRequestElement.cs @@ -7,7 +7,6 @@ namespace DotNetOpenAuth.Configuration { using System; using System.Configuration; - using System.Diagnostics.Contracts; /// <summary> /// Represents the section of a .config file where security policies regarding web requests diff --git a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj index dc47259..50b8a67 100644 --- a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj +++ b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj @@ -4,6 +4,7 @@ <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir> </PropertyGroup> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" /> <PropertyGroup> @@ -27,12 +28,10 @@ <Compile Include="Messaging\Bindings\MemoryCryptoKeyStore.cs" /> <Compile Include="Messaging\BinaryDataBagFormatter.cs" /> <Compile Include="Messaging\CachedDirectWebResponse.cs" /> - <Compile Include="Messaging\ChannelContract.cs" /> <Compile Include="Messaging\DataBagFormatterBase.cs" /> <Compile Include="Messaging\HmacAlgorithms.cs" /> <Compile Include="Messaging\HttpRequestHeaders.cs" /> <Compile Include="Messaging\IHttpDirectRequest.cs" /> - <Compile Include="Messaging\IHttpDirectRequestContract.cs" /> <Compile Include="Messaging\IHttpIndirectResponse.cs" /> <Compile Include="Messaging\IMessageOriginalPayload.cs" /> <Compile Include="Messaging\DirectWebRequestOptions.cs" /> @@ -40,7 +39,6 @@ <Compile Include="Messaging\HostErrorException.cs" /> <Compile Include="Messaging\IHttpDirectResponse.cs" /> <Compile Include="Messaging\IExtensionMessage.cs" /> - <Compile Include="Messaging\IHttpDirectResponseContract.cs" /> <Compile Include="Messaging\IMessage.cs" /> <Compile Include="Messaging\IncomingWebResponse.cs" /> <Compile Include="Messaging\IDirectResponseProtocolMessage.cs" /> @@ -49,7 +47,6 @@ <Compile Include="Messaging\EmptyList.cs" /> <Compile Include="Messaging\ErrorUtilities.cs" /> <Compile Include="Messaging\IMessageWithEvents.cs" /> - <Compile Include="Messaging\IncomingWebResponseContract.cs" /> <Compile Include="Messaging\IProtocolMessageWithExtensions.cs" /> <Compile Include="Messaging\InternalErrorException.cs" /> <Compile Include="Messaging\IStreamSerializingDataBag.cs" /> @@ -116,6 +113,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" /> @@ -136,8 +134,9 @@ <Compile Include="Loggers\TraceLogger.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Messaging\ReadOnlyDictionary.cs" /> + <Compile Include="PureAttribute.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,8 +172,13 @@ <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.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> + <Private>True</Private> + </Reference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" /> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " /> + <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> </Project>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Core/Logger.cs b/src/DotNetOpenAuth.Core/Logger.cs index 975b391..cf9343b 100644 --- a/src/DotNetOpenAuth.Core/Logger.cs +++ b/src/DotNetOpenAuth.Core/Logger.cs @@ -6,11 +6,11 @@ namespace DotNetOpenAuth { using System; - using System.Diagnostics.Contracts; using System.Globalization; 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..554205a 100644 --- a/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs +++ b/src/DotNetOpenAuth.Core/Messaging/BinaryDataBagFormatter.cs @@ -8,12 +8,12 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using DotNetOpenAuth.Messaging.Bindings; + using Validation; /// <summary> /// A compact binary <see cref="DataBag"/> serialization class. @@ -45,7 +45,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 4cb5337..0439908 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs @@ -8,11 +8,11 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Linq; 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 +42,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; } @@ -138,9 +138,9 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// <param name="decrypted">The decrypted key.</param> internal CachedCryptoKey(CryptoKey encrypted, CryptoKey decrypted) : base(decrypted.Key, decrypted.ExpiresUtc) { - Contract.Requires(encrypted != null); - Contract.Requires(decrypted != null); - Contract.Requires(encrypted.ExpiresUtc == decrypted.ExpiresUtc); + Requires.NotNull(encrypted, "encrypted"); + Requires.NotNull(decrypted, "decrypted"); + Requires.That(encrypted.ExpiresUtc == decrypted.ExpiresUtc, "encrypted", "encrypted and decrypted expirations must equal."); this.EncryptedKey = encrypted.Key; } @@ -149,16 +149,6 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// Gets the encrypted key. /// </summary> internal byte[] EncryptedKey { get; private set; } - - /// <summary> - /// Invariant conditions. - /// </summary> - [ContractInvariantMethod] - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Code contracts")] - [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")] - private void ObjectInvariant() { - Contract.Invariant(this.EncryptedKey != null); - } } } } diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs index 3fa50d4..d6fef62 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/CryptoKey.cs @@ -8,10 +8,10 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Linq; using System.Text; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A cryptographic key and metadata concerning it. @@ -34,7 +34,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; } @@ -45,7 +45,6 @@ namespace DotNetOpenAuth.Messaging.Bindings { [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's a buffer")] public byte[] Key { get { - Contract.Ensures(Contract.Result<byte[]>() != null); return this.key; } } @@ -55,7 +54,6 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// </summary> public DateTime ExpiresUtc { get { - Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc); return this.expiresUtc; } } diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs index 88b8fed..8c5db3c 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/ExpiredMessageException.cs @@ -6,8 +6,8 @@ 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 +21,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..ce7bf42 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/ICryptoKeyStore.cs @@ -8,10 +8,10 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Linq; using System.Text; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// A persistent store for rotating symmetric cryptographic keys. @@ -23,7 +23,6 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// of the confidentiality of the keys. One possible mitigation is to asymmetrically encrypt /// each key using a certificate installed in the server's certificate store. /// </remarks> - [ContractClass(typeof(ICryptoKeyStoreContract))] public interface ICryptoKeyStore { /// <summary> /// Gets the key in a given bucket and handle. @@ -57,62 +56,4 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// <param name="handle">The key handle. Case sensitive.</param> void RemoveKey(string bucket, string handle); } - - /// <summary> - /// Code contract for the <see cref="ICryptoKeyStore"/> interface. - /// </summary> - [ContractClassFor(typeof(ICryptoKeyStore))] - internal abstract class ICryptoKeyStoreContract : ICryptoKeyStore { - /// <summary> - /// Gets the key in a given bucket and handle. - /// </summary> - /// <param name="bucket">The bucket name. Case sensitive.</param> - /// <param name="handle">The key handle. Case sensitive.</param> - /// <returns> - /// The cryptographic key, or <c>null</c> if no matching key was found. - /// </returns> - CryptoKey ICryptoKeyStore.GetKey(string bucket, string handle) { - Requires.NotNullOrEmpty(bucket, "bucket"); - Requires.NotNullOrEmpty(handle, "handle"); - throw new NotImplementedException(); - } - - /// <summary> - /// Gets a sequence of existing keys within a given bucket. - /// </summary> - /// <param name="bucket">The bucket name. Case sensitive.</param> - /// <returns> - /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>. - /// </returns> - IEnumerable<KeyValuePair<string, CryptoKey>> ICryptoKeyStore.GetKeys(string bucket) { - Requires.NotNullOrEmpty(bucket, "bucket"); - Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, CryptoKey>>>() != null); - throw new NotImplementedException(); - } - - /// <summary> - /// Stores a cryptographic key. - /// </summary> - /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param> - /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param> - /// <param name="key">The key to store.</param> - /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception> - void ICryptoKeyStore.StoreKey(string bucket, string handle, CryptoKey key) { - Requires.NotNullOrEmpty(bucket, "bucket"); - Requires.NotNullOrEmpty(handle, "handle"); - Requires.NotNull(key, "key"); - throw new NotImplementedException(); - } - - /// <summary> - /// Removes the key. - /// </summary> - /// <param name="bucket">The bucket name. Case sensitive.</param> - /// <param name="handle">The key handle. Case sensitive.</param> - void ICryptoKeyStore.RemoveKey(string bucket, string handle) { - Requires.NotNullOrEmpty(bucket, "bucket"); - Requires.NotNullOrEmpty(handle, "handle"); - throw new NotImplementedException(); - } - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs index 7e39536..45bccdf 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs @@ -7,7 +7,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..20b1831 100644 --- a/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs @@ -8,15 +8,14 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; 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. /// </summary> - [ContractVerification(true)] [DebuggerDisplay("{Status} {ContentType.MediaType}, length: {ResponseStream.Length}")] internal class CachedDirectWebResponse : IncomingWebResponse { /// <summary> @@ -160,14 +159,13 @@ namespace DotNetOpenAuth.Messaging { [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.")] private static MemoryStream CacheNetworkStreamAndClose(HttpWebResponse response, int maximumBytesToRead) { Requires.NotNull(response, "response"); - Contract.Ensures(Contract.Result<MemoryStream>() != null); // Now read and cache the network stream Stream networkStream = response.GetResponseStream(); MemoryStream cachedStream = new MemoryStream(response.ContentLength < 0 ? 4 * 1024 : Math.Min((int)response.ContentLength, maximumBytesToRead)); try { - Contract.Assume(networkStream.CanRead, "HttpWebResponse.GetResponseStream() always returns a readable stream."); // CC missing - Contract.Assume(cachedStream.CanWrite, "This is a MemoryStream -- it's always writable."); // CC missing + Assumes.True(networkStream.CanRead, "HttpWebResponse.GetResponseStream() always returns a readable stream."); // CC missing + Assumes.True(cachedStream.CanWrite, "This is a MemoryStream -- it's always writable."); // CC missing networkStream.CopyTo(cachedStream); cachedStream.Seek(0, SeekOrigin.Begin); diff --git a/src/DotNetOpenAuth.Core/Messaging/Channel.cs b/src/DotNetOpenAuth.Core/Messaging/Channel.cs index f8ac6a1..9c2ba8c 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Channel.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Channel.cs @@ -24,13 +24,12 @@ 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. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Unavoidable.")] - [ContractVerification(true)] - [ContractClass(typeof(ChannelContract))] public abstract class Channel : IDisposable { /// <summary> /// The encoding to use when writing out POST entity strings. @@ -201,7 +200,7 @@ namespace DotNetOpenAuth.Messaging { } set { - Requires.InRange(value >= 500 && value <= 4096, "value"); + Requires.Range(value >= 500 && value <= 4096, "value"); this.maximumIndirectMessageUrlLength = value; } } @@ -233,9 +232,8 @@ namespace DotNetOpenAuth.Messaging { /// </summary> protected internal ReadOnlyCollection<IChannelBindingElement> BindingElements { get { - Contract.Ensures(Contract.Result<ReadOnlyCollection<IChannelBindingElement>>() != null); var result = this.outgoingBindingElements.AsReadOnly(); - Contract.Assume(result != null); // should be an implicit BCL contract + Assumes.True(result != null); // should be an implicit BCL contract return result; } } @@ -252,8 +250,6 @@ namespace DotNetOpenAuth.Messaging { /// </summary> protected internal ReadOnlyCollection<IChannelBindingElement> IncomingBindingElements { get { - Contract.Ensures(Contract.Result<ReadOnlyCollection<IChannelBindingElement>>().All(be => be.Channel != null)); - Contract.Ensures(Contract.Result<ReadOnlyCollection<IChannelBindingElement>>().All(be => be != null)); return this.incomingBindingElements.AsReadOnly(); } } @@ -308,7 +304,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 +323,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(); } @@ -340,7 +336,6 @@ namespace DotNetOpenAuth.Messaging { /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> public OutgoingWebResponse PrepareResponse(IProtocolMessage message) { Requires.NotNull(message, "message"); - Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); this.ProcessOutgoingMessage(message); Logger.Channel.DebugFormat("Sending message: {0}", message.GetType().Name); @@ -420,7 +415,6 @@ namespace DotNetOpenAuth.Messaging { public bool TryReadFromRequest<TRequest>(HttpRequestBase httpRequest, out TRequest request) where TRequest : class, IProtocolMessage { Requires.NotNull(httpRequest, "httpRequest"); - Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<TRequest>(out request) != null)); IProtocolMessage untypedRequest = this.ReadFromRequest(httpRequest); if (untypedRequest == null) { @@ -511,7 +505,6 @@ namespace DotNetOpenAuth.Messaging { public TResponse Request<TResponse>(IDirectedProtocolMessage requestMessage) where TResponse : class, IProtocolMessage { Requires.NotNull(requestMessage, "requestMessage"); - Contract.Ensures(Contract.Result<TResponse>() != null); IProtocolMessage response = this.Request(requestMessage); ErrorUtilities.VerifyProtocol(response != null, MessagingStrings.ExpectedMessageNotReceived, typeof(TResponse)); @@ -620,7 +613,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,11 +627,10 @@ 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); - Contract.Ensures(Contract.Result<HttpRequestBase>() != null); + RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - Contract.Assume(HttpContext.Current.Request.Url != null); - Contract.Assume(HttpContext.Current.Request.RawUrl != null); + Assumes.True(HttpContext.Current.Request.Url != null); + Assumes.True(HttpContext.Current.Request.RawUrl != null); return new HttpRequestWrapper(HttpContext.Current.Request); } @@ -729,7 +721,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; @@ -785,7 +777,7 @@ namespace DotNetOpenAuth.Messaging { Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.GetPublicFacingUrl().AbsoluteUri); // Search Form data first, and if nothing is there search the QueryString - Contract.Assume(request.Form != null && request.GetQueryStringBeforeRewriting() != null); + Assumes.True(request.Form != null && request.GetQueryStringBeforeRewriting() != null); var fields = request.Form.ToDictionary(); if (fields.Count == 0 && request.HttpMethod != "POST") { // OpenID 2.0 section 4.1.2 fields = request.GetQueryStringBeforeRewriting().ToDictionary(); @@ -837,13 +829,12 @@ 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"); - Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); + Requires.That(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); + Requires.That((message.HttpMethods & (HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest)) != 0, "message", "GET or POST expected."); - Contract.Assert(message != null && message.Recipient != null); + Assumes.True(message != null && message.Recipient != null); var messageAccessor = this.MessageDescriptions.GetAccessor(message); - Contract.Assert(message != null && message.Recipient != null); + Assumes.True(message != null && message.Recipient != null); var fields = messageAccessor.Serialize(); OutgoingWebResponse response = null; @@ -887,9 +878,8 @@ 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); // As part of this redirect, we include an HTML body in order to get passed some proxy filters // such as WebSense. @@ -924,9 +914,8 @@ 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); WebHeaderCollection headers = new WebHeaderCollection(); headers.Add(HttpResponseHeader.ContentType, "text/html"); @@ -973,8 +962,7 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { Requires.NotNull(request, "request"); - Requires.True(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); - Contract.Ensures(Contract.Result<HttpWebRequest>() != null); + Requires.That(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); throw new NotImplementedException(); } @@ -1039,7 +1027,7 @@ namespace DotNetOpenAuth.Messaging { MessageProtections appliedProtection = MessageProtections.None; foreach (IChannelBindingElement bindingElement in this.outgoingBindingElements) { - Contract.Assume(bindingElement.Channel != null); + Assumes.True(bindingElement.Channel != null); MessageProtections? elementProtection = bindingElement.ProcessOutgoingMessage(message); if (elementProtection.HasValue) { Logger.Bindings.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName); @@ -1086,7 +1074,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 +1098,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"; @@ -1129,7 +1117,6 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual HttpWebRequest InitializeRequestAsPost(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); - Contract.Ensures(Contract.Result<HttpWebRequest>() != null); var messageAccessor = this.MessageDescriptions.GetAccessor(requestMessage); var fields = messageAccessor.Serialize(); @@ -1164,7 +1151,6 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual HttpWebRequest InitializeRequestAsPut(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); - Contract.Ensures(Contract.Result<HttpWebRequest>() != null); HttpWebRequest request = this.InitializeRequestAsGet(requestMessage); request.Method = "PUT"; @@ -1181,7 +1167,6 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> protected virtual HttpWebRequest InitializeRequestAsDelete(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); - Contract.Ensures(Contract.Result<HttpWebRequest>() != null); HttpWebRequest request = this.InitializeRequestAsGet(requestMessage); request.Method = "DELETE"; @@ -1254,7 +1239,7 @@ namespace DotNetOpenAuth.Messaging { MessageProtections appliedProtection = MessageProtections.None; foreach (IChannelBindingElement bindingElement in this.IncomingBindingElements) { - Contract.Assume(bindingElement.Channel != null); // CC bug: this.IncomingBindingElements ensures this... why must we assume it here? + Assumes.True(bindingElement.Channel != null); // CC bug: this.IncomingBindingElements ensures this... why must we assume it here? MessageProtections? elementProtection = bindingElement.ProcessIncomingMessage(message); if (elementProtection.HasValue) { Logger.Bindings.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName); @@ -1350,8 +1335,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"); - Contract.Ensures(Contract.Result<IEnumerable<IChannelBindingElement>>() != null); + Requires.NullOrNotNullElements(elements, "elements"); if (elements == null) { return new IChannelBindingElement[0]; } diff --git a/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs b/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs deleted file mode 100644 index b48d45b..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/ChannelContract.cs +++ /dev/null @@ -1,54 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="ChannelContract.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Collections.Generic; - using System.Diagnostics.Contracts; - - /// <summary> - /// Code contract for the <see cref="Channel"/> class. - /// </summary> - [ContractClassFor(typeof(Channel))] - internal abstract class ChannelContract : Channel { - /// <summary> - /// Prevents a default instance of the ChannelContract class from being created. - /// </summary> - private ChannelContract() - : base(null, null) { - } - - /// <summary> - /// Gets the protocol message that may be in the given HTTP response. - /// </summary> - /// <param name="response">The response that is anticipated to contain an protocol message.</param> - /// <returns> - /// The deserialized message parts, if found. Null otherwise. - /// </returns> - /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { - Requires.NotNull(response, "response"); - throw new NotImplementedException(); - } - - /// <summary> - /// Queues a message for sending in the response stream where the fields - /// are sent in the response stream in querystring style. - /// </summary> - /// <param name="response">The message to send as a response.</param> - /// <returns> - /// The pending user agent redirect based message to be sent as an HttpResponse. - /// </returns> - /// <remarks> - /// This method implements spec V1.0 section 5.3. - /// </remarks> - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { - Requires.NotNull(response, "response"); - Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); - throw new NotImplementedException(); - } - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs b/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs index f3ebc04..5c69e4d 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ChannelEventArgs.cs @@ -6,7 +6,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 0800840..8469676 100644 --- a/src/DotNetOpenAuth.Core/Messaging/DataBag.cs +++ b/src/DotNetOpenAuth.Core/Messaging/DataBag.cs @@ -8,7 +8,7 @@ namespace DotNetOpenAuth.Messaging { using System; 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, @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <param name="version">The DataBag version.</param> protected DataBag(Version version) { - Contract.Requires(version != null); + Requires.NotNull(version, "version"); this.version = version; } diff --git a/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs b/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs index e7ac254..210a95e 100644 --- a/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs +++ b/src/DotNetOpenAuth.Core/Messaging/DataBagFormatterBase.cs @@ -8,7 +8,6 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Security.Cryptography; @@ -17,6 +16,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 +110,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 +129,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,8 +303,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); - Contract.Ensures(Contract.Result<byte[]>() != null); + RequiresEx.ValidState(this.asymmetricSigning != null || this.cryptoKeyStore != null); if (this.asymmetricSigning != null) { using (var hasher = SHA1.Create()) { @@ -328,7 +327,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 +348,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..0886ef2 100644 --- a/src/DotNetOpenAuth.Core/Messaging/EnumerableCacheExtensions.cs +++ b/src/DotNetOpenAuth.Core/Messaging/EnumerableCacheExtensions.cs @@ -9,7 +9,7 @@ namespace DotNetOpenAuth.Messaging { using System; 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..71c904b 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ErrorUtilities.cs @@ -11,11 +11,11 @@ namespace DotNetOpenAuth.Messaging { using System.Diagnostics.Contracts; using System.Globalization; using System.Web; + using Validation; /// <summary> /// A collection of error checking and reporting methods. /// </summary> - [ContractVerification(true)] [Pure] internal static class ErrorUtilities { /// <summary> @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static Exception Wrap(Exception inner, string errorMessage, params object[] args) { Requires.NotNull(args, "args"); - Contract.Assume(errorMessage != null); + Assumes.True(errorMessage != null); return new ProtocolException(string.Format(CultureInfo.CurrentCulture, errorMessage, args), inner); } @@ -58,8 +58,6 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="InternalErrorException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception> [Pure] internal static void VerifyInternal(bool condition, string errorMessage) { - Contract.Ensures(condition); - Contract.EnsuresOnThrow<InternalErrorException>(!condition); if (!condition) { ThrowInternal(errorMessage); } @@ -75,9 +73,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifyInternal(bool condition, string errorMessage, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<InternalErrorException>(!condition); - Contract.Assume(errorMessage != null); + Assumes.True(errorMessage != null); if (!condition) { errorMessage = string.Format(CultureInfo.CurrentCulture, errorMessage, args); throw new InternalErrorException(errorMessage); @@ -92,8 +88,6 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="InvalidOperationException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception> [Pure] internal static void VerifyOperation(bool condition, string errorMessage) { - Contract.Ensures(condition); - Contract.EnsuresOnThrow<InvalidOperationException>(!condition); if (!condition) { throw new InvalidOperationException(errorMessage); } @@ -107,8 +101,6 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="NotSupportedException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception> [Pure] internal static void VerifySupported(bool condition, string errorMessage) { - Contract.Ensures(condition); - Contract.EnsuresOnThrow<NotSupportedException>(!condition); if (!condition) { throw new NotSupportedException(errorMessage); } @@ -124,9 +116,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifySupported(bool condition, string errorMessage, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<NotSupportedException>(!condition); - Contract.Assume(errorMessage != null); + Assumes.True(errorMessage != null); if (!condition) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, errorMessage, args)); } @@ -142,9 +132,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifyOperation(bool condition, string errorMessage, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<InvalidOperationException>(!condition); - Contract.Assume(errorMessage != null); + Assumes.True(errorMessage != null); if (!condition) { errorMessage = string.Format(CultureInfo.CurrentCulture, errorMessage, args); throw new InvalidOperationException(errorMessage); @@ -161,9 +149,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifyHost(bool condition, string errorMessage, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<ProtocolException>(!condition); - Contract.Assume(errorMessage != null); + Assumes.True(errorMessage != null); if (!condition) { throw new HostErrorException(string.Format(CultureInfo.CurrentCulture, errorMessage, args)); } @@ -181,9 +167,7 @@ namespace DotNetOpenAuth.Messaging { internal static void VerifyProtocol(bool condition, IProtocolMessage faultedMessage, string errorMessage, params object[] args) { Requires.NotNull(args, "args"); Requires.NotNull(faultedMessage, "faultedMessage"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<ProtocolException>(!condition); - Contract.Assume(errorMessage != null); + Assumes.True(errorMessage != null); if (!condition) { throw new ProtocolException(string.Format(CultureInfo.CurrentCulture, errorMessage, args), faultedMessage); } @@ -199,9 +183,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifyProtocol(bool condition, string unformattedMessage, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<ProtocolException>(!condition); - Contract.Assume(unformattedMessage != null); + Assumes.True(unformattedMessage != null); if (!condition) { var exception = new ProtocolException(string.Format(CultureInfo.CurrentCulture, unformattedMessage, args)); if (Logger.Messaging.IsErrorEnabled) { @@ -231,7 +213,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static Exception ThrowProtocol(string unformattedMessage, params object[] args) { Requires.NotNull(args, "args"); - Contract.Assume(unformattedMessage != null); + Assumes.True(unformattedMessage != null); VerifyProtocol(false, unformattedMessage, args); // we never reach here, but this allows callers to "throw" this method. @@ -247,7 +229,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static Exception ThrowFormat(string message, params object[] args) { Requires.NotNull(args, "args"); - Contract.Assume(message != null); + Assumes.True(message != null); throw new FormatException(string.Format(CultureInfo.CurrentCulture, message, args)); } @@ -261,9 +243,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifyFormat(bool condition, string message, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<FormatException>(!condition); - Contract.Assume(message != null); + Assumes.True(message != null); if (!condition) { throw ThrowFormat(message, args); } @@ -279,9 +259,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifyArgument(bool condition, string message, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<ArgumentException>(!condition); - Contract.Assume(message != null); + Assumes.True(message != null); if (!condition) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, message, args)); } @@ -297,7 +275,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static Exception ThrowArgumentNamed(string parameterName, string message, params object[] args) { Requires.NotNull(args, "args"); - Contract.Assume(message != null); + Assumes.True(message != null); throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, message, args), parameterName); } @@ -312,9 +290,7 @@ namespace DotNetOpenAuth.Messaging { [Pure] internal static void VerifyArgumentNamed(bool condition, string parameterName, string message, params object[] args) { Requires.NotNull(args, "args"); - Contract.Ensures(condition); - Contract.EnsuresOnThrow<ArgumentException>(!condition); - Contract.Assume(message != null); + Assumes.True(message != null); if (!condition) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, message, args), parameterName); } @@ -328,8 +304,6 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> [Pure] internal static void VerifyArgumentNotNull(object value, string paramName) { - Contract.Ensures(value != null); - Contract.EnsuresOnThrow<ArgumentNullException>(value == null); if (value == null) { throw new ArgumentNullException(paramName); } @@ -344,8 +318,6 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="ArgumentException">Thrown if <paramref name="value"/> has zero length.</exception> [Pure] internal static void VerifyNonZeroLength(string value, string paramName) { - Contract.Ensures((value != null && value.Length > 0) && !string.IsNullOrEmpty(value)); - Contract.EnsuresOnThrow<ArgumentException>(value == null || value.Length == 0); VerifyArgumentNotNull(value, paramName); if (value.Length == 0) { throw new ArgumentException(MessagingStrings.UnexpectedEmptyString, paramName); @@ -358,8 +330,6 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current"/> == <c>null</c></exception> [Pure] internal static void VerifyHttpContext() { - Contract.Ensures(HttpContext.Current != null); - Contract.Ensures(HttpContext.Current.Request != null); ErrorUtilities.VerifyOperation(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); } 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..55233c2 100644 --- a/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs +++ b/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs @@ -9,7 +9,6 @@ namespace DotNetOpenAuth.Messaging { using System.Collections.Specialized; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Net; @@ -20,6 +19,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..fca46a0 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs @@ -6,13 +6,12 @@ namespace DotNetOpenAuth.Messaging { using System; - using System.Diagnostics.Contracts; + using Validation; /// <summary> /// An interface that must be implemented by message transforms/validators in order /// to be included in the channel stack. /// </summary> - [ContractClass(typeof(IChannelBindingElementContract))] public interface IChannelBindingElement { /// <summary> /// Gets or sets the channel that this binding element belongs to. @@ -63,84 +62,4 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> MessageProtections? ProcessIncomingMessage(IProtocolMessage message); } - - /// <summary> - /// Code Contract for the <see cref="IChannelBindingElement"/> interface. - /// </summary> - [ContractClassFor(typeof(IChannelBindingElement))] - internal abstract class IChannelBindingElementContract : IChannelBindingElement { - /// <summary> - /// Prevents a default instance of the <see cref="IChannelBindingElementContract"/> class from being created. - /// </summary> - private IChannelBindingElementContract() { - } - - #region IChannelBindingElement Members - - /// <summary> - /// Gets or sets the channel that this binding element belongs to. - /// </summary> - /// <value></value> - /// <remarks> - /// This property is set by the channel when it is first constructed. - /// </remarks> - Channel IChannelBindingElement.Channel { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - - /// <summary> - /// Gets the protection commonly offered (if any) by this binding element. - /// </summary> - /// <value></value> - /// <remarks> - /// This value is used to assist in sorting binding elements in the channel stack. - /// </remarks> - MessageProtections IChannelBindingElement.Protection { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Prepares a message for sending based on the rules of this channel binding element. - /// </summary> - /// <param name="message">The message to prepare for sending.</param> - /// <returns> - /// The protections (if any) that this binding element applied to the message. - /// Null if this binding element did not even apply to this binding element. - /// </returns> - /// <remarks> - /// Implementations that provide message protection must honor the - /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. - /// </remarks> - MessageProtections? IChannelBindingElement.ProcessOutgoingMessage(IProtocolMessage message) { - Requires.NotNull(message, "message"); - Requires.ValidState(((IChannelBindingElement)this).Channel != null); - throw new NotImplementedException(); - } - - /// <summary> - /// Performs any transformation on an incoming message that may be necessary and/or - /// validates an incoming message based on the rules of this channel binding element. - /// </summary> - /// <param name="message">The incoming message to process.</param> - /// <returns> - /// The protections (if any) that this binding element applied to the message. - /// Null if this binding element did not even apply to this binding element. - /// </returns> - /// <exception cref="ProtocolException"> - /// Thrown when the binding element rules indicate that this message is invalid and should - /// NOT be processed. - /// </exception> - /// <remarks> - /// Implementations that provide message protection must honor the - /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. - /// </remarks> - MessageProtections? IChannelBindingElement.ProcessIncomingMessage(IProtocolMessage message) { - Requires.NotNull(message, "message"); - Requires.ValidState(((IChannelBindingElement)this).Channel != null); - throw new NotImplementedException(); - } - - #endregion - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs b/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs index 0d1ab03..955d7c0 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IDataBagFormatter.cs @@ -6,13 +6,12 @@ namespace DotNetOpenAuth.Messaging { using System; - using System.Diagnostics.Contracts; + using Validation; /// <summary> /// A serializer for <see cref="DataBag"/>-derived types /// </summary> /// <typeparam name="T">The DataBag-derived type that is to be serialized/deserialized.</typeparam> - [ContractClass(typeof(IDataBagFormatterContract<>))] internal interface IDataBagFormatter<in T> where T : DataBag { /// <summary> /// Serializes the specified message. @@ -30,50 +29,4 @@ namespace DotNetOpenAuth.Messaging { /// <param name="messagePartName">The name of the parameter whose value is to be deserialized. Used for error message generation, but may be <c>null</c>.</param> void Deserialize(T message, string data, IProtocolMessage containingMessage = null, string messagePartName = null); } - - /// <summary> - /// Contract class for the IDataBagFormatter interface. - /// </summary> - /// <typeparam name="T">The type of DataBag to serialize.</typeparam> - [ContractClassFor(typeof(IDataBagFormatter<>))] - internal abstract class IDataBagFormatterContract<T> : IDataBagFormatter<T> where T : DataBag, new() { - /// <summary> - /// Prevents a default instance of the <see cref="IDataBagFormatterContract<T>"/> class from being created. - /// </summary> - private IDataBagFormatterContract() { - } - - #region IDataBagFormatter<T> Members - - /// <summary> - /// Serializes the specified message. - /// </summary> - /// <param name="message">The message to serialize. Must not be null.</param> - /// <returns>A non-null, non-empty value.</returns> - string IDataBagFormatter<T>.Serialize(T message) { - Requires.NotNull(message, "message"); - Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); - - throw new System.NotImplementedException(); - } - - /// <summary> - /// Deserializes a <see cref="DataBag"/>. - /// </summary> - /// <param name="message">The instance to deserialize into</param> - /// <param name="data">The serialized form of the <see cref="DataBag"/> to deserialize. Must not be null or empty.</param> - /// <param name="containingMessage">The message that contains the <see cref="DataBag"/> serialized value. Must not be nulll.</param> - /// <param name="messagePartName">Name of the message part whose value is to be deserialized. Used for exception messages.</param> - void IDataBagFormatter<T>.Deserialize(T message, string data, IProtocolMessage containingMessage, string messagePartName) { - Requires.NotNull(message, "message"); - Requires.NotNull(containingMessage, "containingMessage"); - Requires.NotNullOrEmpty(data, "data"); - Requires.NotNullOrEmpty(messagePartName, "messagePartName"); - Contract.Ensures(Contract.Result<T>() != null); - - throw new System.NotImplementedException(); - } - - #endregion - } }
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs index 7878405..f3975b3 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. @@ -18,7 +19,6 @@ namespace DotNetOpenAuth.Messaging { /// <remarks> /// Implementations of this interface must be thread safe. /// </remarks> - [ContractClass(typeof(IDirectWebRequestHandlerContract))] public interface IDirectWebRequestHandler { /// <summary> /// Determines whether this instance can support the specified options. @@ -102,122 +102,4 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options); } - - /// <summary> - /// Code contract for the <see cref="IDirectWebRequestHandler"/> type. - /// </summary> - [ContractClassFor(typeof(IDirectWebRequestHandler))] - internal abstract class IDirectWebRequestHandlerContract : IDirectWebRequestHandler { - #region IDirectWebRequestHandler Members - - /// <summary> - /// Determines whether this instance can support the specified options. - /// </summary> - /// <param name="options">The set of options that might be given in a subsequent web request.</param> - /// <returns> - /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>. - /// </returns> - bool IDirectWebRequestHandler.CanSupport(DirectWebRequestOptions options) { - throw new System.NotImplementedException(); - } - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <returns> - /// The stream the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method. - /// Callers <i>must</i> close and dispose of the request stream when they are done - /// writing to it to avoid taking up the connection too long and causing long waits on - /// subsequent requests.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request) { - Requires.NotNull(request, "request"); - throw new System.NotImplementedException(); - } - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns> - /// The stream the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method. - /// Callers <i>must</i> close and dispose of the request stream when they are done - /// writing to it to avoid taking up the connection too long and causing long waits on - /// subsequent requests.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) { - Requires.NotNull(request, "request"); - Requires.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(); - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <returns> - /// An instance of <see cref="IncomingWebResponse"/> describing the response. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing. - /// </remarks> - IncomingWebResponse IDirectWebRequestHandler.GetResponse(HttpWebRequest request) { - Requires.NotNull(request, "request"); - Contract.Ensures(Contract.Result<IncomingWebResponse>() != null); - Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null); - throw new System.NotImplementedException(); - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns> - /// An instance of <see cref="IncomingWebResponse"/> describing the response. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing. - /// </remarks> - IncomingWebResponse IDirectWebRequestHandler.GetResponse(HttpWebRequest request, DirectWebRequestOptions options) { - 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); - - ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name)); - throw new System.NotImplementedException(); - } - - #endregion - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs index 7153334..7b26869 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs @@ -5,13 +5,11 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Messaging { - using System.Diagnostics.Contracts; using System.Net; /// <summary> /// An interface that allows direct request messages to capture the details of the HTTP request they arrived on. /// </summary> - [ContractClass(typeof(IHttpDirectRequestContract))] public interface IHttpDirectRequest : IMessage { /// <summary> /// Gets the HTTP headers of the request. diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequestContract.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequestContract.cs deleted file mode 100644 index cfde6cf..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequestContract.cs +++ /dev/null @@ -1,75 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="IHttpDirectRequestContract.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Collections.Generic; - using System.Diagnostics.Contracts; - using System.Linq; - using System.Net; - using System.Text; - - /// <summary> - /// Contract class for the <see cref="IHttpDirectRequest"/> interface. - /// </summary> - [ContractClassFor(typeof(IHttpDirectRequest))] - public abstract class IHttpDirectRequestContract : IHttpDirectRequest { - #region IHttpDirectRequest Members - - /// <summary> - /// Gets the HTTP headers of the request. - /// </summary> - /// <value>May be an empty collection, but must not be <c>null</c>.</value> - WebHeaderCollection IHttpDirectRequest.Headers { - get { - Contract.Ensures(Contract.Result<WebHeaderCollection>() != null); - throw new NotImplementedException(); - } - } - - #endregion - - #region IMessage Members - - /// <summary> - /// Gets the version of the protocol or extension this message is prepared to implement. - /// </summary> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - Version IMessage.Version { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Gets the extra, non-standard Protocol parameters included in the message. - /// </summary> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - IDictionary<string, string> IMessage.ExtraData { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Checks the message state for conformity to the protocol specification - /// and throws an exception if the message is invalid. - /// </summary> - /// <remarks> - /// <para>Some messages have required fields, or combinations of fields that must relate to each other - /// in specialized ways. After deserializing a message, this method checks the state of the - /// message to see if it conforms to the protocol.</para> - /// <para>Note that this property should <i>not</i> check signatures or perform any state checks - /// outside this scope of this particular message.</para> - /// </remarks> - /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> - void IMessage.EnsureValidMessage() { - throw new NotImplementedException(); - } - - #endregion - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponse.cs index d942366..f455fcf 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponse.cs @@ -5,14 +5,12 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Messaging { - using System.Diagnostics.Contracts; using System.Net; /// <summary> /// An interface that allows direct response messages to specify /// HTTP transport specific properties. /// </summary> - [ContractClass(typeof(IHttpDirectResponseContract))] public interface IHttpDirectResponse { /// <summary> /// Gets the HTTP status code that the direct response should be sent with. diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponseContract.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponseContract.cs deleted file mode 100644 index a04ba62..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectResponseContract.cs +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="IHttpDirectResponseContract.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Collections.Generic; - using System.Diagnostics.Contracts; - using System.Linq; - using System.Net; - using System.Text; - - /// <summary> - /// Contract class for the <see cref="IHttpDirectResponse"/> interface. - /// </summary> - [ContractClassFor(typeof(IHttpDirectResponse))] - public abstract class IHttpDirectResponseContract : IHttpDirectResponse { - #region IHttpDirectResponse Members - - /// <summary> - /// Gets the HTTP status code that the direct response should be sent with. - /// </summary> - /// <value></value> - HttpStatusCode IHttpDirectResponse.HttpStatusCode { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Gets the HTTP headers to add to the response. - /// </summary> - /// <value>May be an empty collection, but must not be <c>null</c>.</value> - WebHeaderCollection IHttpDirectResponse.Headers { - get { - Contract.Ensures(Contract.Result<WebHeaderCollection>() != null); - throw new NotImplementedException(); - } - } - - #endregion - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs index e0e8665..c9ab73b 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IHttpIndirectResponse.cs @@ -5,7 +5,6 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Messaging { - using System.Diagnostics.Contracts; using System.Net; /// <summary> diff --git a/src/DotNetOpenAuth.Core/Messaging/IMessage.cs b/src/DotNetOpenAuth.Core/Messaging/IMessage.cs index 62673ef..c007913 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IMessage.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IMessage.cs @@ -7,14 +7,12 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; using System.Text; /// <summary> /// The interface that classes must implement to be serialized/deserialized /// as protocol or extension messages. /// </summary> - [ContractClass(typeof(IMessageContract))] public interface IMessage { /// <summary> /// Gets the version of the protocol or extension this message is prepared to implement. @@ -46,55 +44,4 @@ namespace DotNetOpenAuth.Messaging { /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> void EnsureValidMessage(); } - - /// <summary> - /// Code contract for the <see cref="IMessage"/> interface. - /// </summary> - [ContractClassFor(typeof(IMessage))] - internal abstract class IMessageContract : IMessage { - /// <summary> - /// Prevents a default instance of the <see cref="IMessageContract"/> class from being created. - /// </summary> - private IMessageContract() { - } - - /// <summary> - /// Gets the version of the protocol or extension this message is prepared to implement. - /// </summary> - Version IMessage.Version { - get { - Contract.Ensures(Contract.Result<Version>() != null); - return default(Version); // dummy return - } - } - - /// <summary> - /// Gets the extra, non-standard Protocol parameters included in the message. - /// </summary> - /// <value></value> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - IDictionary<string, string> IMessage.ExtraData { - get { - Contract.Ensures(Contract.Result<IDictionary<string, string>>() != null); - return default(IDictionary<string, string>); - } - } - - /// <summary> - /// Checks the message state for conformity to the protocol specification - /// and throws an exception if the message is invalid. - /// </summary> - /// <remarks> - /// <para>Some messages have required fields, or combinations of fields that must relate to each other - /// in specialized ways. After deserializing a message, this method checks the state of the - /// message to see if it conforms to the protocol.</para> - /// <para>Note that this property should <i>not</i> check signatures or perform any state checks - /// outside this scope of this particular message.</para> - /// </remarks> - /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> - void IMessage.EnsureValidMessage() { - } - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs index e45ac1d..1e86328 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IMessageFactory.cs @@ -7,13 +7,12 @@ 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 /// is designed to deserialize it and instantiates that class. /// </summary> - [ContractClass(typeof(IMessageFactoryContract))] public interface IMessageFactory { /// <summary> /// Analyzes an incoming request message payload to discover what kind of @@ -41,53 +40,4 @@ namespace DotNetOpenAuth.Messaging { /// </returns> IDirectResponseProtocolMessage GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields); } - - /// <summary> - /// Code contract for the <see cref="IMessageFactory"/> interface. - /// </summary> - [ContractClassFor(typeof(IMessageFactory))] - internal abstract class IMessageFactoryContract : IMessageFactory { - /// <summary> - /// Prevents a default instance of the <see cref="IMessageFactoryContract"/> class from being created. - /// </summary> - private IMessageFactoryContract() { - } - - #region IMessageFactory Members - - /// <summary> - /// Analyzes an incoming request message payload to discover what kind of - /// message is embedded in it and returns the type, or null if no match is found. - /// </summary> - /// <param name="recipient">The intended or actual recipient of the request message.</param> - /// <param name="fields">The name/value pairs that make up the message payload.</param> - /// <returns> - /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can - /// deserialize to. Null if the request isn't recognized as a valid protocol message. - /// </returns> - IDirectedProtocolMessage IMessageFactory.GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) { - Requires.NotNull(recipient, "recipient"); - Requires.NotNull(fields, "fields"); - - throw new NotImplementedException(); - } - - /// <summary> - /// Analyzes an incoming request message payload to discover what kind of - /// message is embedded in it and returns the type, or null if no match is found. - /// </summary> - /// <param name="request">The message that was sent as a request that resulted in the response.</param> - /// <param name="fields">The name/value pairs that make up the message payload.</param> - /// <returns> - /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can - /// deserialize to. Null if the request isn't recognized as a valid protocol message. - /// </returns> - IDirectResponseProtocolMessage IMessageFactory.GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) { - Requires.NotNull(request, "request"); - Requires.NotNull(fields, "fields"); - throw new NotImplementedException(); - } - - #endregion - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IMessageOriginalPayload.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageOriginalPayload.cs index 099f54b..33fa860 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IMessageOriginalPayload.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IMessageOriginalPayload.cs @@ -8,14 +8,12 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Text; /// <summary> /// An interface that appears on messages that need to retain a description of /// what their literal payload was when they were deserialized. /// </summary> - [ContractClass(typeof(IMessageOriginalPayloadContract))] public interface IMessageOriginalPayload { /// <summary> /// Gets or sets the original message parts, before any normalization or default values were assigned. @@ -23,18 +21,4 @@ namespace DotNetOpenAuth.Messaging { [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "By design")] IDictionary<string, string> OriginalPayload { get; set; } } - - /// <summary> - /// Code contract for the <see cref="IMessageOriginalPayload"/> interface. - /// </summary> - [ContractClassFor(typeof(IMessageOriginalPayload))] - internal abstract class IMessageOriginalPayloadContract : IMessageOriginalPayload { - /// <summary> - /// Gets or sets the original message parts, before any normalization or default values were assigned. - /// </summary> - IDictionary<string, string> IMessageOriginalPayload.OriginalPayload { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs index 60e1f50..2992678 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs @@ -7,7 +7,6 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; using System.Linq; using System.Text; @@ -15,7 +14,6 @@ namespace DotNetOpenAuth.Messaging { /// The interface that classes must implement to be serialized/deserialized /// as protocol or extension messages that uses POST multi-part data for binary content. /// </summary> - [ContractClass(typeof(IMessageWithBinaryDataContract))] public interface IMessageWithBinaryData : IDirectedProtocolMessage { /// <summary> /// Gets the parts of the message that carry binary data. @@ -28,129 +26,4 @@ namespace DotNetOpenAuth.Messaging { /// </summary> bool SendAsMultipart { get; } } - - /// <summary> - /// The contract class for the <see cref="IMessageWithBinaryData"/> interface. - /// </summary> - [ContractClassFor(typeof(IMessageWithBinaryData))] - internal abstract class IMessageWithBinaryDataContract : IMessageWithBinaryData { - /// <summary> - /// Prevents a default instance of the <see cref="IMessageWithBinaryDataContract"/> class from being created. - /// </summary> - private IMessageWithBinaryDataContract() { - } - - #region IMessageWithBinaryData Members - - /// <summary> - /// Gets the parts of the message that carry binary data. - /// </summary> - /// <value>A list of parts. Never null.</value> - IList<MultipartPostPart> IMessageWithBinaryData.BinaryData { - get { - Contract.Ensures(Contract.Result<IList<MultipartPostPart>>() != null); - throw new NotImplementedException(); - } - } - - /// <summary> - /// Gets a value indicating whether this message should be sent as multi-part POST. - /// </summary> - bool IMessageWithBinaryData.SendAsMultipart { - get { throw new NotImplementedException(); } - } - - #endregion - - #region IMessage Properties - - /// <summary> - /// Gets the version of the protocol or extension this message is prepared to implement. - /// </summary> - /// <value></value> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - Version IMessage.Version { - get { - return default(Version); // dummy return - } - } - - /// <summary> - /// Gets the extra, non-standard Protocol parameters included in the message. - /// </summary> - /// <value></value> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - IDictionary<string, string> IMessage.ExtraData { - get { - return default(IDictionary<string, string>); - } - } - - #endregion - - #region IDirectedProtocolMessage Members - - /// <summary> - /// Gets the preferred method of transport for the message. - /// </summary> - /// <remarks> - /// For indirect messages this will likely be GET+POST, which both can be simulated in the user agent: - /// the GET with a simple 301 Redirect, and the POST with an HTML form in the response with javascript - /// to automate submission. - /// </remarks> - HttpDeliveryMethods IDirectedProtocolMessage.HttpMethods { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Gets the URL of the intended receiver of this message. - /// </summary> - Uri IDirectedProtocolMessage.Recipient { - get { throw new NotImplementedException(); } - } - - #endregion - - #region IProtocolMessage Members - - /// <summary> - /// Gets the level of protection this message requires. - /// </summary> - MessageProtections IProtocolMessage.RequiredProtection { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Gets a value indicating whether this is a direct or indirect message. - /// </summary> - MessageTransport IProtocolMessage.Transport { - get { throw new NotImplementedException(); } - } - - #endregion - - #region IMessage methods - - /// <summary> - /// Checks the message state for conformity to the protocol specification - /// and throws an exception if the message is invalid. - /// </summary> - /// <remarks> - /// <para>Some messages have required fields, or combinations of fields that must relate to each other - /// in specialized ways. After deserializing a message, this method checks the state of the - /// message to see if it conforms to the protocol.</para> - /// <para>Note that this property should <i>not</i> check signatures or perform any state checks - /// outside this scope of this particular message.</para> - /// </remarks> - /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> - void IMessage.EnsureValidMessage() { - throw new NotImplementedException(); - } - - #endregion - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IProtocolMessageWithExtensions.cs b/src/DotNetOpenAuth.Core/Messaging/IProtocolMessageWithExtensions.cs index c492e65..436c7a9 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IProtocolMessageWithExtensions.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IProtocolMessageWithExtensions.cs @@ -7,12 +7,10 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; /// <summary> /// A protocol message that supports adding extensions to the payload for transmission. /// </summary> - [ContractClass(typeof(IProtocolMessageWithExtensionsContract))] public interface IProtocolMessageWithExtensions : IProtocolMessage { /// <summary> /// Gets the list of extensions that are included with this message. @@ -22,95 +20,4 @@ namespace DotNetOpenAuth.Messaging { /// </remarks> IList<IExtensionMessage> Extensions { get; } } - - /// <summary> - /// Code contract for the <see cref="IProtocolMessageWithExtensions"/> interface. - /// </summary> - [ContractClassFor(typeof(IProtocolMessageWithExtensions))] - internal abstract class IProtocolMessageWithExtensionsContract : IProtocolMessageWithExtensions { - /// <summary> - /// Prevents a default instance of the <see cref="IProtocolMessageWithExtensionsContract"/> class from being created. - /// </summary> - private IProtocolMessageWithExtensionsContract() { - } - - #region IProtocolMessageWithExtensions Members - - /// <summary> - /// Gets the list of extensions that are included with this message. - /// </summary> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - IList<IExtensionMessage> IProtocolMessageWithExtensions.Extensions { - get { - Contract.Ensures(Contract.Result<IList<IExtensionMessage>>() != null); - throw new NotImplementedException(); - } - } - - #endregion - - #region IProtocolMessage Members - - /// <summary> - /// Gets the level of protection this message requires. - /// </summary> - MessageProtections IProtocolMessage.RequiredProtection { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Gets a value indicating whether this is a direct or indirect message. - /// </summary> - MessageTransport IProtocolMessage.Transport { - get { throw new NotImplementedException(); } - } - - #endregion - - #region IMessage Members - - /// <summary> - /// Gets the version of the protocol or extension this message is prepared to implement. - /// </summary> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - Version IMessage.Version { - get { - throw new NotImplementedException(); - } - } - - /// <summary> - /// Gets the extra, non-standard Protocol parameters included in the message. - /// </summary> - /// <remarks> - /// Implementations of this interface should ensure that this property never returns null. - /// </remarks> - IDictionary<string, string> IMessage.ExtraData { - get { - throw new NotImplementedException(); - } - } - - /// <summary> - /// Checks the message state for conformity to the protocol specification - /// and throws an exception if the message is invalid. - /// </summary> - /// <remarks> - /// <para>Some messages have required fields, or combinations of fields that must relate to each other - /// in specialized ways. After deserializing a message, this method checks the state of the - /// message to see if it conforms to the protocol.</para> - /// <para>Note that this property should <i>not</i> check signatures or perform any state checks - /// outside this scope of this particular message.</para> - /// </remarks> - /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> - void IMessage.EnsureValidMessage() { - throw new NotImplementedException(); - } - - #endregion - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs b/src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs index cc82d6a..16fed67 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IStreamSerializingDataBag.cs @@ -6,13 +6,11 @@ namespace DotNetOpenAuth.Messaging { using System; - using System.Diagnostics.Contracts; using System.IO; /// <summary> /// An interface implemented by <see cref="DataBag"/>-derived types that support binary serialization. /// </summary> - [ContractClass(typeof(IStreamSerializingDataBaContract))] internal interface IStreamSerializingDataBag { /// <summary> /// Serializes the instance to the specified stream. @@ -26,30 +24,4 @@ namespace DotNetOpenAuth.Messaging { /// <param name="stream">The stream.</param> void Deserialize(Stream stream); } - - /// <summary> - /// Code Contract for the <see cref="IStreamSerializingDataBag"/> interface. - /// </summary> - [ContractClassFor(typeof(IStreamSerializingDataBag))] - internal abstract class IStreamSerializingDataBaContract : IStreamSerializingDataBag { - /// <summary> - /// Serializes the instance to the specified stream. - /// </summary> - /// <param name="stream">The stream.</param> - void IStreamSerializingDataBag.Serialize(Stream stream) { - Contract.Requires(stream != null); - Contract.Requires(stream.CanWrite); - throw new NotImplementedException(); - } - - /// <summary> - /// Initializes the fields on this instance from the specified stream. - /// </summary> - /// <param name="stream">The stream.</param> - void IStreamSerializingDataBag.Deserialize(Stream stream) { - Contract.Requires(stream != null); - Contract.Requires(stream.CanRead); - throw new NotImplementedException(); - } - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs index cdb26ae..abb01a1 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs @@ -7,18 +7,16 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Globalization; using System.IO; 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. /// </summary> - [ContractVerification(true)] - [ContractClass(typeof(IncomingWebResponseContract))] public abstract class IncomingWebResponse : IDisposable { /// <summary> /// The encoding to use in reading a response that does not declare its own content encoding. diff --git a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs deleted file mode 100644 index 5c94e47..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponseContract.cs +++ /dev/null @@ -1,54 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="IncomingWebResponseContract.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Diagnostics.Contracts; - using System.IO; - - /// <summary> - /// Code contract for the <see cref="IncomingWebResponse"/> class. - /// </summary> - [ContractClassFor(typeof(IncomingWebResponse))] - internal abstract class IncomingWebResponseContract : IncomingWebResponse { - /// <summary> - /// Gets the body of the HTTP response. - /// </summary> - /// <value></value> - public override Stream ResponseStream { - get { throw new NotImplementedException(); } - } - - /// <summary> - /// Creates a text reader for the response stream. - /// </summary> - /// <returns> - /// The text reader, initialized for the proper encoding. - /// </returns> - public override StreamReader GetResponseReader() { - Contract.Ensures(Contract.Result<StreamReader>() != null); - throw new NotImplementedException(); - } - - /// <summary> - /// Gets an offline snapshot version of this instance. - /// </summary> - /// <param name="maximumBytesToCache">The maximum bytes from the response stream to cache.</param> - /// <returns>A snapshot version of this instance.</returns> - /// <remarks> - /// If this instance is a <see cref="NetworkDirectWebResponse"/> creating a snapshot - /// will automatically close and dispose of the underlying response stream. - /// If this instance is a <see cref="CachedDirectWebResponse"/>, the result will - /// be the self same instance. - /// </remarks> - internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) { - Requires.InRange(maximumBytesToCache >= 0, "maximumBytesToCache"); - Requires.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..251ff30 100644 --- a/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs +++ b/src/DotNetOpenAuth.Core/Messaging/KeyedCollectionDelegate.cs @@ -7,7 +7,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..34be92d 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MessageReceivingEndpoint.cs @@ -7,7 +7,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 +23,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 +34,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..1b30748 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MessageSerializer.cs @@ -14,11 +14,11 @@ namespace DotNetOpenAuth.Messaging { using System.Reflection; using System.Xml; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// Serializes/deserializes OAuth messages for/from transit. /// </summary> - [ContractVerification(true)] internal class MessageSerializer { /// <summary> /// The specific <see cref="IMessage"/>-derived type @@ -31,10 +31,8 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <param name="messageType">The specific <see cref="IMessage"/>-derived type /// 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"); - Contract.Ensures(this.messageType != null); + RequiresEx.NotNullSubtype<IMessage>(messageType, "messageType"); this.messageType = messageType; } @@ -43,9 +41,8 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <param name="messageType">The type of message that will be serialized/deserialized.</param> /// <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"); + internal static MessageSerializer Get(Type messageType) { + RequiresEx.NotNullSubtype<IMessage>(messageType, "messageType"); return new MessageSerializer(messageType); } @@ -94,7 +91,7 @@ namespace DotNetOpenAuth.Messaging { string type = "string"; MessagePart partDescription; if (messageDictionary.Description.Mapping.TryGetValue(pair.Key, out partDescription)) { - Contract.Assume(partDescription != null); + Assumes.True(partDescription != null); if (partDescription.IsRequired || partDescription.IsNondefaultValueSet(messageDictionary.Message)) { include = true; Type formattingType = partDescription.PreferredFormattingType; @@ -150,7 +147,6 @@ namespace DotNetOpenAuth.Messaging { [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Parallel design with Deserialize method.")] internal IDictionary<string, string> Serialize(MessageDictionary messageDictionary) { Requires.NotNull(messageDictionary, "messageDictionary"); - Contract.Ensures(Contract.Result<IDictionary<string, string>>() != null); // Rather than hand back the whole message dictionary (which // includes keys with blank values), create a new dictionary @@ -160,7 +156,7 @@ namespace DotNetOpenAuth.Messaging { foreach (var pair in messageDictionary) { MessagePart partDescription; if (messageDictionary.Description.Mapping.TryGetValue(pair.Key, out partDescription)) { - Contract.Assume(partDescription != null); + Assumes.True(partDescription != null); if (partDescription.IsRequired || partDescription.IsNondefaultValueSet(messageDictionary.Message)) { result.Add(pair.Key, pair.Value); } diff --git a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs index e859162..fffb855 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs @@ -9,7 +9,6 @@ namespace DotNetOpenAuth.Messaging { using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.IO.Compression; @@ -29,6 +28,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 +198,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(); } @@ -589,7 +589,6 @@ namespace DotNetOpenAuth.Messaging { /// <returns>A sequence of key=value pairs discovered in the header. Never null, but may be empty.</returns> internal static IEnumerable<KeyValuePair<string, string>> ParseAuthorizationHeader(string scheme, string authorizationHeader) { Requires.NotNullOrEmpty(scheme, "scheme"); - Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, string>>>() != null); string prefix = scheme + " "; if (authorizationHeader != null) { @@ -621,7 +620,6 @@ namespace DotNetOpenAuth.Messaging { internal static string CombineKeyHandleAndPayload(string handle, string payload) { Requires.NotNullOrEmpty(handle, "handle"); Requires.NotNullOrEmpty(payload, "payload"); - Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); return handle + "!" + payload; } @@ -695,8 +693,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; @@ -717,7 +715,6 @@ namespace DotNetOpenAuth.Messaging { internal static string ComputeHash(this HashAlgorithm algorithm, string value, Encoding encoding = null) { Requires.NotNull(algorithm, "algorithm"); Requires.NotNull(value, "value"); - Contract.Ensures(Contract.Result<string>() != null); encoding = encoding ?? Encoding.UTF8; byte[] bytesToHash = encoding.GetBytes(value); @@ -736,7 +733,6 @@ namespace DotNetOpenAuth.Messaging { internal static string ComputeHash(this HashAlgorithm algorithm, IDictionary<string, string> data, Encoding encoding = null) { Requires.NotNull(algorithm, "algorithm"); Requires.NotNull(data, "data"); - Contract.Ensures(Contract.Result<string>() != null); // Assemble the dictionary to sign, taking care to remove the signature itself // in order to accurately reproduce the original signature (which of course didn't include @@ -757,7 +753,6 @@ namespace DotNetOpenAuth.Messaging { internal static string ComputeHash(this HashAlgorithm algorithm, IEnumerable<KeyValuePair<string, string>> sortedData, Encoding encoding = null) { Requires.NotNull(algorithm, "algorithm"); Requires.NotNull(sortedData, "sortedData"); - Contract.Ensures(Contract.Result<string>() != null); return ComputeHash(algorithm, CreateQueryString(sortedData), encoding); } @@ -936,7 +931,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) { @@ -979,7 +974,6 @@ namespace DotNetOpenAuth.Messaging { [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")] internal static byte[] Compress(byte[] buffer, CompressionMethod method = CompressionMethod.Deflate) { Requires.NotNull(buffer, "buffer"); - Contract.Ensures(Contract.Result<byte[]>() != null); using (var ms = new MemoryStream()) { Stream compressingStream = null; @@ -992,7 +986,7 @@ namespace DotNetOpenAuth.Messaging { compressingStream = new GZipStream(ms, CompressionMode.Compress, true); break; default: - Requires.InRange(false, "method"); + Requires.Range(false, "method"); break; } @@ -1016,7 +1010,6 @@ namespace DotNetOpenAuth.Messaging { [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")] internal static byte[] Decompress(byte[] buffer, CompressionMethod method = CompressionMethod.Deflate) { Requires.NotNull(buffer, "buffer"); - Contract.Ensures(Contract.Result<byte[]>() != null); using (var compressedDataStream = new MemoryStream(buffer)) { using (var decompressedDataStream = new MemoryStream()) { @@ -1030,7 +1023,7 @@ namespace DotNetOpenAuth.Messaging { decompressingStream = new GZipStream(compressedDataStream, CompressionMode.Decompress, true); break; default: - Requires.InRange(false, "method"); + Requires.Range(false, "method"); break; } @@ -1070,7 +1063,6 @@ namespace DotNetOpenAuth.Messaging { /// <returns>A data buffer.</returns> internal static byte[] FromBase64WebSafeString(string base64WebSafe) { Requires.NotNullOrEmpty(base64WebSafe, "base64WebSafe"); - Contract.Ensures(Contract.Result<byte[]>() != null); // Restore the padding characters and original URL-unsafe characters. int missingPaddingCharacters; @@ -1158,8 +1150,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 +1170,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 +1193,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 +1213,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); } @@ -1434,7 +1426,6 @@ namespace DotNetOpenAuth.Messaging { /// <returns>The formulated querystring style string.</returns> internal static string CreateQueryString(IEnumerable<KeyValuePair<string, string>> args) { Requires.NotNull(args, "args"); - Contract.Ensures(Contract.Result<string>() != null); if (!args.Any()) { return string.Empty; @@ -1638,7 +1629,6 @@ namespace DotNetOpenAuth.Messaging { /// <c>Dictionary<string, string></c> does not allow null keys. /// </remarks> internal static Dictionary<string, string> ToDictionary(this NameValueCollection nvc) { - Contract.Ensures((nvc != null && Contract.Result<Dictionary<string, string>>() != null) || (nvc == null && Contract.Result<Dictionary<string, string>>() == null)); return ToDictionary(nvc, false); } @@ -1654,7 +1644,6 @@ namespace DotNetOpenAuth.Messaging { /// <returns>The generated dictionary, or null if <paramref name="nvc"/> is null.</returns> /// <exception cref="ArgumentException">Thrown if <paramref name="throwOnNullKey"/> is <c>true</c> and a null key is encountered.</exception> internal static Dictionary<string, string> ToDictionary(this NameValueCollection nvc, bool throwOnNullKey) { - Contract.Ensures((nvc != null && Contract.Result<Dictionary<string, string>>() != null) || (nvc == null && Contract.Result<Dictionary<string, string>>() == null)); if (nvc == null) { return null; } @@ -1708,7 +1697,6 @@ namespace DotNetOpenAuth.Messaging { Requires.NotNull(source, "source"); Requires.NotNull(comparer, "comparer"); Requires.NotNull(keySelector, "keySelector"); - Contract.Ensures(Contract.Result<IOrderedEnumerable<TSource>>() != null); return System.Linq.Enumerable.OrderBy<TSource, TKey>(source, keySelector, new ComparisonHelper<TKey>(comparer)); } @@ -1771,7 +1759,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..b4a0968 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs @@ -8,10 +8,10 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; 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..754d71d 100644 --- a/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs @@ -7,16 +7,15 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Diagnostics; - using System.Diagnostics.Contracts; using System.IO; using System.Net; using System.Text; + using Validation; /// <summary> /// A live network HTTP response /// </summary> [DebuggerDisplay("{Status} {ContentType.MediaType}")] - [ContractVerification(true)] internal class NetworkDirectWebResponse : IncomingWebResponse, IDisposable { /// <summary> /// The network response object, used to initialize this instance, that still needs diff --git a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs index e1e9d53..be7774f 100644 --- a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs +++ b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs @@ -8,7 +8,6 @@ namespace DotNetOpenAuth.Messaging { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.IO; using System.Net; using System.Net.Mime; @@ -16,6 +15,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 +136,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 +178,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..bc2f985 100644 --- a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs +++ b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs @@ -6,9 +6,9 @@ namespace DotNetOpenAuth.Messaging { using System; - 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/ProtocolException.cs b/src/DotNetOpenAuth.Core/Messaging/ProtocolException.cs index 982e1c0..4bc3590 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ProtocolException.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ProtocolException.cs @@ -7,7 +7,6 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; using System.Security; using System.Security.Permissions; 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..017c7d7 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/IMessagePartEncoder.cs @@ -7,9 +7,9 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System; using System.Collections.Generic; - 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. @@ -17,7 +17,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// <remarks> /// Implementations of this interface must include a default constructor and must be thread-safe. /// </remarks> - [ContractClass(typeof(IMessagePartEncoderContract))] public interface IMessagePartEncoder { /// <summary> /// Encodes the specified value. @@ -34,45 +33,4 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception> object Decode(string value); } - - /// <summary> - /// Code contract for the <see cref="IMessagePartEncoder"/> type. - /// </summary> - [ContractClassFor(typeof(IMessagePartEncoder))] - internal abstract class IMessagePartEncoderContract : IMessagePartEncoder { - /// <summary> - /// Initializes a new instance of the <see cref="IMessagePartEncoderContract"/> class. - /// </summary> - protected IMessagePartEncoderContract() { - } - - #region IMessagePartEncoder Members - - /// <summary> - /// Encodes the specified value. - /// </summary> - /// <param name="value">The value. Guaranteed to never be null.</param> - /// <returns> - /// The <paramref name="value"/> in string form, ready for message transport. - /// </returns> - string IMessagePartEncoder.Encode(object value) { - Requires.NotNull(value, "value"); - throw new NotImplementedException(); - } - - /// <summary> - /// Decodes the specified value. - /// </summary> - /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param> - /// <returns> - /// The deserialized form of the given string. - /// </returns> - /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception> - object IMessagePartEncoder.Decode(string value) { - Requires.NotNull(value, "value"); - throw new NotImplementedException(); - } - - #endregion - } } diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescription.cs index 7e67842..cd04e1d 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; @@ -80,7 +81,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { [Pure] internal MessageDictionary GetDictionary(IMessage message) { Requires.NotNull(message, "message"); - Contract.Ensures(Contract.Result<MessageDictionary>() != null); return this.GetDictionary(message, false); } @@ -93,7 +93,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { [Pure] internal MessageDictionary GetDictionary(IMessage message, bool getOriginalValues) { Requires.NotNull(message, "message"); - Contract.Ensures(Contract.Result<MessageDictionary>() != null); return new MessageDictionary(message, this, getOriginalValues); } diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs index 3517abc..f27a7af 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDescriptionCollection.cs @@ -10,11 +10,11 @@ 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. /// </summary> - [ContractVerification(true)] internal class MessageDescriptionCollection : IEnumerable<MessageDescription> { /// <summary> /// A dictionary of reflected message types and the generated reflection information. @@ -68,9 +68,8 @@ 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); MessageTypeAndVersion key = new MessageTypeAndVersion(messageType, messageVersion); @@ -106,7 +105,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { [Pure] internal MessageDescription Get(IMessage message) { Requires.NotNull(message, "message"); - Contract.Ensures(Contract.Result<MessageDescription>() != null); return this.Get(message.GetType(), message.Version); } @@ -136,8 +134,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// <summary> /// A struct used as the key to bundle message type and version. /// </summary> - [ContractVerification(true)] - private struct MessageTypeAndVersion { + private struct MessageTypeAndVersion { /// <summary> /// Backing store for the <see cref="Type"/> property. /// </summary> diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs index cf44863..a2dddb2 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessageDictionary.cs @@ -11,13 +11,13 @@ 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 /// provides access to both well-defined message properties and "extra" /// name/value pairs that have no properties associated with them. /// </summary> - [ContractVerification(false)] internal class MessageDictionary : IDictionary<string, string> { /// <summary> /// The <see cref="IMessage"/> instance manipulated by this dictionary. @@ -55,7 +55,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// </summary> public IMessage Message { get { - Contract.Ensures(Contract.Result<IMessage>() != null); return this.message; } } @@ -65,7 +64,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// </summary> public MessageDescription Description { get { - Contract.Ensures(Contract.Result<MessageDescription>() != null); return this.description; } } @@ -380,7 +378,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// <returns>The generated dictionary.</returns> [Pure] public IDictionary<string, string> Serialize() { - Contract.Ensures(Contract.Result<IDictionary<string, string>>() != null); return this.Serializer.Serialize(this); } diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs index a6e8da2..add4beb 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/MessagePart.cs @@ -9,18 +9,17 @@ namespace DotNetOpenAuth.Messaging.Reflection { using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; using System.Net.Security; using System.Reflection; using System.Xml; using DotNetOpenAuth.Configuration; + using Validation; /// <summary> /// Describes an individual member of a message and assists in its serialization. /// </summary> - [ContractVerification(true)] [DebuggerDisplay("MessagePart {Name}")] internal class MessagePart { /// <summary> @@ -66,20 +65,20 @@ namespace DotNetOpenAuth.Messaging.Reflection { [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Much more efficient initialization when we can call methods.")] static MessagePart() { Func<string, Uri> safeUri = str => { - Contract.Assume(str != null); + Assumes.True(str != null); return new Uri(str); }; Func<string, bool> safeBool = str => { - Contract.Assume(str != null); + Assumes.True(str != null); return bool.Parse(str); }; Func<byte[], string> safeFromByteArray = bytes => { - Contract.Assume(bytes != null); + Assumes.True(bytes != null); return Convert.ToBase64String(bytes); }; Func<string, byte[]> safeToByteArray = str => { - Contract.Assume(str != null); + Assumes.True(str != null); return Convert.FromBase64String(str); }; Map<Uri>(uri => uri.AbsoluteUri, uri => uri.OriginalString, safeUri); @@ -106,7 +105,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; @@ -119,7 +118,7 @@ namespace DotNetOpenAuth.Messaging.Reflection { this.memberDeclaredType = (this.field != null) ? this.field.FieldType : this.property.PropertyType; this.defaultMemberValue = DeriveDefaultValue(this.memberDeclaredType); - Contract.Assume(this.memberDeclaredType != null); // CC missing PropertyInfo.PropertyType ensures result != null + Assumes.True(this.memberDeclaredType != null); // CC missing PropertyInfo.PropertyType ensures result != null if (attribute.Encoder == null) { if (!converters.TryGetValue(this.memberDeclaredType, out this.converter)) { if (this.memberDeclaredType.IsGenericType && @@ -203,7 +202,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); } } @@ -394,7 +393,6 @@ namespace DotNetOpenAuth.Messaging.Reflection { /// <returns>An instance of the desired encoder.</returns> private static IMessagePartEncoder GetEncoder(Type messagePartEncoder) { Requires.NotNull(messagePartEncoder, "messagePartEncoder"); - Contract.Ensures(Contract.Result<IMessagePartEncoder>() != null); IMessagePartEncoder encoder; lock (encoders) { diff --git a/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs b/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs index 4139f52..c45eb5d 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Reflection/ValueMapping.cs @@ -6,12 +6,11 @@ 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. /// </summary> - [ContractVerification(true)] internal struct ValueMapping { /// <summary> /// The mapping function that converts some custom type to a string. diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs index 762b54b..fd35e5f 100644 --- a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs +++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactory.cs @@ -7,11 +7,11 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; using System.Linq; 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 +42,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) { @@ -208,7 +208,6 @@ namespace DotNetOpenAuth.Messaging { protected virtual IDirectedProtocolMessage InstantiateAsRequest(MessageDescription messageDescription, MessageReceivingEndpoint recipient) { Requires.NotNull(messageDescription, "messageDescription"); Requires.NotNull(recipient, "recipient"); - Contract.Ensures(Contract.Result<IDirectedProtocolMessage>() != null); ConstructorInfo ctor = this.requestMessageTypes[messageDescription]; return (IDirectedProtocolMessage)ctor.Invoke(new object[] { recipient.Location, messageDescription.MessageVersion }); @@ -223,7 +222,6 @@ namespace DotNetOpenAuth.Messaging { protected virtual IDirectResponseProtocolMessage InstantiateAsResponse(MessageDescription messageDescription, IDirectedProtocolMessage request) { Requires.NotNull(messageDescription, "messageDescription"); Requires.NotNull(request, "request"); - Contract.Ensures(Contract.Result<IDirectResponseProtocolMessage>() != null); Type requestType = request.GetType(); var ctors = this.FindMatchingResponseConstructors(messageDescription, requestType); @@ -249,7 +247,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)) @@ -277,7 +275,6 @@ namespace DotNetOpenAuth.Messaging { private static int CountInCommon(ICollection<string> collection1, ICollection<string> collection2, StringComparison comparison = StringComparison.Ordinal) { Requires.NotNull(collection1, "collection1"); Requires.NotNull(collection2, "collection2"); - Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= Math.Min(collection1.Count, collection2.Count)); return collection1.Count(value1 => collection2.Any(value2 => string.Equals(value1, value2, comparison))); } diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs index 7ca5d45..9cb80b0 100644 --- a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs +++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs @@ -7,10 +7,10 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Reflection; + using Validation; /// <summary> /// A channel that uses the standard message factory. @@ -98,7 +98,6 @@ namespace DotNetOpenAuth.Messaging { { Requires.NotNull(messageTypes, "messageTypes"); Requires.NotNull(descriptionsCache, "descriptionsCache"); - Contract.Ensures(Contract.Result<IEnumerable<MessageDescription>>() != null); // Get all the MessageDescription objects through the standard cache, // so that perhaps it will be a quick lookup, or at least it will be 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..1d7c424 100644 --- a/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs +++ b/src/DotNetOpenAuth.Core/Messaging/UriStyleMessageFormatter.cs @@ -7,7 +7,6 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; using System.Linq; using System.Security.Cryptography; using System.Text; @@ -15,6 +14,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 +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 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/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.Core/Properties/AssemblyInfo.cs index 21cbb94..7f8a591 100644 --- a/src/DotNetOpenAuth.Core/Properties/AssemblyInfo.cs +++ b/src/DotNetOpenAuth.Core/Properties/AssemblyInfo.cs @@ -7,7 +7,6 @@ // We DON'T put an AssemblyVersionAttribute in here because it is generated in the build. using System; -using System.Diagnostics.Contracts; using System.Net; using System.Reflection; using System.Resources; @@ -31,8 +30,6 @@ using System.Web.UI; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")] -[assembly: ContractVerification(true)] - #if StrongNameSigned // See comment at top of this file. We need this so that strong-naming doesn't // keep this assembly from being useful to shared host (medium trust) web sites. diff --git a/src/DotNetOpenAuth.Core/PureAttribute.cs b/src/DotNetOpenAuth.Core/PureAttribute.cs new file mode 100644 index 0000000..04f7ead --- /dev/null +++ b/src/DotNetOpenAuth.Core/PureAttribute.cs @@ -0,0 +1,22 @@ +//----------------------------------------------------------------------- +// <copyright file="PureAttribute.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace System.Diagnostics.Contracts { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + +#if !CLR4 + /// <summary> + /// Designates a type or member as one that does not mutate any objects that were allocated + /// before the invocation of the member. + /// </summary> + [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] + internal sealed class PureAttribute : Attribute { + } +#endif +} diff --git a/src/DotNetOpenAuth.Core/Reporting.cs b/src/DotNetOpenAuth.Core/Reporting.cs index 80a3374..f902fd6 100644 --- a/src/DotNetOpenAuth.Core/Reporting.cs +++ b/src/DotNetOpenAuth.Core/Reporting.cs @@ -9,7 +9,6 @@ namespace DotNetOpenAuth { using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.IO.IsolatedStorage; @@ -23,6 +22,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 @@ -170,7 +170,7 @@ namespace DotNetOpenAuth { /// <param name="category">The category within the event. Null and empty strings are allowed, but considered the same.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "PersistentCounter instances are stored in a table for later use.")] internal static void RecordEventOccurrence(string eventName, string category) { - Contract.Requires(!string.IsNullOrEmpty(eventName)); + Requires.NotNullOrEmpty(eventName, "eventName"); // In release builds, just quietly return. if (string.IsNullOrEmpty(eventName)) { @@ -196,7 +196,7 @@ namespace DotNetOpenAuth { /// <param name="eventNameByObjectType">The object whose type name is the event name to record.</param> /// <param name="category">The category within the event. Null and empty strings are allowed, but considered the same.</param> internal static void RecordEventOccurrence(object eventNameByObjectType, string category) { - Contract.Requires(eventNameByObjectType != null); + Requires.NotNull(eventNameByObjectType, "eventNameByObjectType"); // In release builds, just quietly return. if (eventNameByObjectType == null) { @@ -213,7 +213,7 @@ namespace DotNetOpenAuth { /// </summary> /// <param name="feature">The feature.</param> internal static void RecordFeatureUse(string feature) { - Contract.Requires(!string.IsNullOrEmpty(feature)); + Requires.NotNullOrEmpty(feature, "feature"); // In release builds, just quietly return. if (string.IsNullOrEmpty(feature)) { @@ -231,7 +231,7 @@ namespace DotNetOpenAuth { /// </summary> /// <param name="value">The object whose type is the feature to set as used.</param> internal static void RecordFeatureUse(object value) { - Contract.Requires(value != null); + Requires.NotNull(value, "value"); // In release builds, just quietly return. if (value == null) { @@ -250,7 +250,7 @@ namespace DotNetOpenAuth { /// <param name="value">The object whose type is the feature to set as used.</param> /// <param name="dependency1">Some dependency used by <paramref name="value"/>.</param> internal static void RecordFeatureAndDependencyUse(object value, object dependency1) { - Contract.Requires(value != null); + Requires.NotNull(value, "value"); // In release builds, just quietly return. if (value == null) { @@ -274,7 +274,7 @@ namespace DotNetOpenAuth { /// <param name="dependency1">Some dependency used by <paramref name="value"/>.</param> /// <param name="dependency2">Some dependency used by <paramref name="value"/>.</param> internal static void RecordFeatureAndDependencyUse(object value, object dependency1, object dependency2) { - Contract.Requires(value != null); + Requires.NotNull(value, "value"); // In release builds, just quietly return. if (value == null) { @@ -298,7 +298,7 @@ namespace DotNetOpenAuth { /// </summary> /// <param name="request">The request.</param> internal static void RecordRequestStatistics(HttpRequestBase request) { - Contract.Requires(request != null); + Requires.NotNull(request, "request"); // In release builds, just quietly return. if (request == null) { @@ -534,8 +534,6 @@ namespace DotNetOpenAuth { /// </summary> /// <returns>An isolated storage location appropriate for our host.</returns> private static IsolatedStorageFile GetIsolatedStorage() { - Contract.Ensures(Contract.Result<IsolatedStorageFile>() != null); - IsolatedStorageFile result = null; // We'll try for whatever storage location we can get, @@ -567,8 +565,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); - Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); + RequiresEx.ValidState(file != null, "file not set."); Guid identityGuid = Guid.Empty; const int GuidLength = 16; 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..1a077c4 --- /dev/null +++ b/src/DotNetOpenAuth.Core/RequiresEx.cs @@ -0,0 +1,94 @@ +//----------------------------------------------------------------------- +// <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> + [Pure, DebuggerStepThrough] + internal static void ValidState(bool condition) { + if (!condition) { + throw new InvalidOperationException(); + } + } + + /// <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> + [Pure, DebuggerStepThrough] + internal static void ValidState(bool condition, string message) { + if (!condition) { + throw new InvalidOperationException(message); + } + } + + /// <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> + [Pure, DebuggerStepThrough] + internal static void ValidState(bool condition, string unformattedMessage, params object[] args) { + if (!condition) { + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, unformattedMessage, args)); + } + } + + /// <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> + [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); + } + + /// <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> + [Pure, DebuggerStepThrough] + internal static void Format(bool condition, string message) { + if (!condition) { + throw new FormatException(message); + } + } + + /// <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..25b92a2 100644 --- a/src/DotNetOpenAuth.Core/UriUtil.cs +++ b/src/DotNetOpenAuth.Core/UriUtil.cs @@ -8,17 +8,16 @@ namespace DotNetOpenAuth { using System; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; - using System.Diagnostics.Contracts; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// Utility methods for working with URIs. /// </summary> - [ContractVerification(true)] internal static class UriUtil { /// <summary> /// Tests a URI for the presence of an OAuth payload. @@ -28,15 +27,14 @@ namespace DotNetOpenAuth { /// <returns> /// True if the URI contains an OAuth message. /// </returns> - [ContractVerification(false)] // bugs/limitations in CC static analysis - internal static bool QueryStringContainPrefixedParameters(this Uri uri, string prefix) { + internal static bool QueryStringContainPrefixedParameters(this Uri uri, string prefix) { Requires.NotNullOrEmpty(prefix, "prefix"); if (uri == null) { return false; } NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query); - Contract.Assume(nvc != null); // BCL + Assumes.True(nvc != null); // BCL return nvc.Keys.OfType<string>().Any(key => key.StartsWith(prefix, StringComparison.Ordinal)); } @@ -60,7 +58,6 @@ namespace DotNetOpenAuth { /// <returns>The string version of the Uri.</returns> internal static string ToStringWithImpliedPorts(this UriBuilder builder) { Requires.NotNull(builder, "builder"); - Contract.Ensures(Contract.Result<string>() != null); // We only check for implied ports on HTTP and HTTPS schemes since those // are the only ones supported by OpenID anyway. @@ -73,7 +70,7 @@ namespace DotNetOpenAuth { // we're removing only the port (and not something in the query string that // looks like a port. string result = Regex.Replace(url, @"^(https?://[^:]+):\d+", m => m.Groups[1].Value, RegexOptions.IgnoreCase); - Contract.Assume(result != null); // Regex.Replace never returns null + Assumes.True(result != null); // Regex.Replace never returns null return result; } else { // The port must be explicitly given anyway. @@ -95,12 +92,12 @@ namespace DotNetOpenAuth { } if (page != null && !designMode) { - Contract.Assume(page.Request != null); + Assumes.True(page.Request != null); // Validate new value by trying to construct a Realm object based on it. string relativeUrl = page.ResolveUrl(value); - Contract.Assume(page.Request.Url != null); - Contract.Assume(relativeUrl != null); + Assumes.True(page.Request.Url != null); + Assumes.True(relativeUrl != null); new Uri(page.Request.Url, relativeUrl); // throws an exception on failure. } else { // We can't fully test it, but it should start with either ~/ or a protocol. diff --git a/src/DotNetOpenAuth.Core/Util.cs b/src/DotNetOpenAuth.Core/Util.cs index 3babba5..ec28c50 100644 --- a/src/DotNetOpenAuth.Core/Util.cs +++ b/src/DotNetOpenAuth.Core/Util.cs @@ -6,7 +6,6 @@ namespace DotNetOpenAuth { using System; using System.Collections.Generic; - using System.Diagnostics.Contracts; using System.Globalization; using System.Net; using System.Reflection; @@ -17,11 +16,11 @@ namespace DotNetOpenAuth { using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; + using Validation; /// <summary> /// A grab-bag utility class. /// </summary> - [ContractVerification(true)] internal static class Util { /// <summary> /// The base namespace for this library from which all other namespaces derive. @@ -103,8 +102,7 @@ namespace DotNetOpenAuth { return new DelayedToString<IEnumerable<KeyValuePair<K, V>>>( pairs, p => { - ////Contract.Requires(pairs != null); // CC: anonymous method can't handle it - ErrorUtilities.VerifyArgumentNotNull(pairs, "pairs"); + Requires.NotNull(pairs, "pairs"); var dictionary = pairs as IDictionary<K, V>; var messageDictionary = pairs as MessageDictionary; StringBuilder sb = new StringBuilder(dictionary != null ? dictionary.Count * 40 : 200); @@ -139,7 +137,6 @@ namespace DotNetOpenAuth { /// <param name="list">The list of elements.</param> /// <param name="multiLineElements">if set to <c>true</c>, special formatting will be applied to the output to make it clear where one element ends and the next begins.</param> /// <returns>An object whose ToString method will perform the actual work of generating the string.</returns> - [ContractVerification(false)] internal static object ToStringDeferred<T>(this IEnumerable<T> list, bool multiLineElements) { return new DelayedToString<IEnumerable<T>>( list, @@ -148,7 +145,7 @@ namespace DotNetOpenAuth { ErrorUtilities.VerifyArgumentNotNull(l, "l"); string newLine = Environment.NewLine; - ////Contract.Assume(newLine != null && newLine.Length > 0); + ////Assumes.True(newLine != null && newLine.Length > 0); StringBuilder sb = new StringBuilder(); if (multiLineElements) { sb.AppendLine("[{"); diff --git a/src/DotNetOpenAuth.Core/packages.config b/src/DotNetOpenAuth.Core/packages.config new file mode 100644 index 0000000..70866e7 --- /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.1.12362" targetFramework="net40" /> +</packages>
\ No newline at end of file |