diff options
Diffstat (limited to 'src')
188 files changed, 779 insertions, 763 deletions
diff --git a/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardSelector.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardSelector.cs index 94beeeb..b1d5bfd 100644 --- a/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardSelector.cs +++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/InfoCardSelector.cs @@ -454,7 +454,7 @@ namespace DotNetOpenAuth.InfoCard { /// <returns>The event arguments sent to the event handlers.</returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "decryptor", Justification = "By design")] protected virtual ReceivingTokenEventArgs OnReceivingToken(string tokenXml) { - Contract.Requires<ArgumentNullException>(tokenXml != null); + Requires.NotNull(tokenXml, "tokenXml"); var args = new ReceivingTokenEventArgs(tokenXml); var receivingToken = this.ReceivingToken; @@ -470,7 +470,7 @@ namespace DotNetOpenAuth.InfoCard { /// </summary> /// <param name="token">The token, if it was decrypted.</param> protected virtual void OnReceivedToken(Token token) { - Contract.Requires<ArgumentNullException>(token != null); + Requires.NotNull(token, "token"); var receivedInfoCard = this.ReceivedToken; if (receivedInfoCard != null) { @@ -484,8 +484,8 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="unprocessedToken">The unprocessed token.</param> /// <param name="ex">The exception generated while processing the token.</param> protected virtual void OnTokenProcessingError(string unprocessedToken, Exception ex) { - Contract.Requires<ArgumentNullException>(unprocessedToken != null); - Contract.Requires<ArgumentNullException>(ex != null); + Requires.NotNull(unprocessedToken, "unprocessedToken"); + Requires.NotNull(ex, "ex"); var tokenProcessingError = this.TokenProcessingError; if (tokenProcessingError != null) { @@ -724,7 +724,7 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="optional">A space-delimited list of claim type URIs for claims that may optionally be included in a submitted Information Card.</param> [Pure] private void GetRequestedClaims(out string required, out string optional) { - Contract.Requires<InvalidOperationException>(this.ClaimsRequested != null); + Requires.ValidState(this.ClaimsRequested != null); Contract.Ensures(Contract.ValueAtReturn<string>(out required) != null); Contract.Ensures(Contract.ValueAtReturn<string>(out optional) != null); @@ -750,7 +750,7 @@ namespace DotNetOpenAuth.InfoCard { /// or to downgrade gracefully if the user agent lacks an Information Card selector. /// </summary> private void RenderSupportingScript() { - Contract.Requires<InvalidOperationException>(this.infoCardSupportedPanel != null); + Requires.ValidState(this.infoCardSupportedPanel != null); this.Page.ClientScript.RegisterClientScriptResource(typeof(InfoCardSelector), ScriptResourceName); diff --git a/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivingTokenEventArgs.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivingTokenEventArgs.cs index 3dd892a..d831a84 100644 --- a/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivingTokenEventArgs.cs +++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/ReceivingTokenEventArgs.cs @@ -21,7 +21,7 @@ namespace DotNetOpenAuth.InfoCard { /// </summary> /// <param name="tokenXml">The raw token XML, prior to any decryption.</param> internal ReceivingTokenEventArgs(string tokenXml) { - Contract.Requires<ArgumentNullException>(tokenXml != null); + Requires.NotNull(tokenXml, "tokenXml"); this.TokenXml = tokenXml; this.IsEncrypted = Token.IsEncrypted(this.TokenXml); @@ -63,7 +63,7 @@ namespace DotNetOpenAuth.InfoCard { /// </summary> /// <param name="securityToken">The security token.</param> public void AddDecryptingToken(SecurityToken securityToken) { - Contract.Requires<ArgumentNullException>(securityToken != null); + Requires.NotNull(securityToken, "securityToken"); this.DecryptingTokens.Add(securityToken); } @@ -73,8 +73,8 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="certificate">The certificate.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")] public void AddDecryptingToken(X509Certificate2 certificate) { - Contract.Requires<ArgumentNullException>(certificate != null); - Contract.Requires<ArgumentException>(certificate.HasPrivateKey); + Requires.NotNull(certificate, "certificate"); + Requires.True(certificate.HasPrivateKey, "certificate"); var cert = new X509SecurityToken(certificate); try { this.AddDecryptingToken(cert); diff --git a/src/DotNetOpenAuth.InfoCard.UI/InfoCard/TokenProcessingErrorEventArgs.cs b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/TokenProcessingErrorEventArgs.cs index 0f17b63..3ce9f40 100644 --- a/src/DotNetOpenAuth.InfoCard.UI/InfoCard/TokenProcessingErrorEventArgs.cs +++ b/src/DotNetOpenAuth.InfoCard.UI/InfoCard/TokenProcessingErrorEventArgs.cs @@ -18,8 +18,8 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="tokenXml">The token XML.</param> /// <param name="exception">The exception.</param> internal TokenProcessingErrorEventArgs(string tokenXml, Exception exception) { - Contract.Requires<ArgumentNullException>(tokenXml != null); - Contract.Requires<ArgumentNullException>(exception != null); + Requires.NotNull(tokenXml, "tokenXml"); + Requires.NotNull(exception, "exception"); this.TokenXml = tokenXml; this.Exception = exception; } diff --git a/src/DotNetOpenAuth.InfoCard/InfoCard/Token/Token.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/Token.cs index 3b6f573..fc7683d 100644 --- a/src/DotNetOpenAuth.InfoCard/InfoCard/Token/Token.cs +++ b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/Token.cs @@ -43,8 +43,8 @@ namespace DotNetOpenAuth.InfoCard { /// <exception cref="InformationCardException">Thrown for any problem decoding or decrypting the token.</exception> [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type."), SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")] private Token(string tokenXml, Uri audience, TokenDecryptor decryptor) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml)); - Contract.Requires<ArgumentException>(decryptor != null || !IsEncrypted(tokenXml)); + Requires.NotNullOrEmpty(tokenXml, "tokenXml"); + Requires.True(decryptor != null || !IsEncrypted(tokenXml), null); Contract.Ensures(this.AuthorizationContext != null); byte[] decryptedBytes; @@ -117,7 +117,7 @@ namespace DotNetOpenAuth.InfoCard { /// </summary> public string SiteSpecificId { get { - Contract.Requires<InvalidOperationException>(this.Claims.ContainsKey(ClaimTypes.PPID) && !string.IsNullOrEmpty(this.Claims[ClaimTypes.PPID])); + Requires.ValidState(this.Claims.ContainsKey(ClaimTypes.PPID) && !string.IsNullOrEmpty(this.Claims[ClaimTypes.PPID])); string ppidValue; ErrorUtilities.VerifyOperation(this.Claims.TryGetValue(ClaimTypes.PPID, out ppidValue) && ppidValue != null, InfoCardStrings.PpidClaimRequired); return TokenUtility.CalculateSiteSpecificID(ppidValue); @@ -143,7 +143,7 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="tokenXml">The token XML.</param> /// <returns>The deserialized token.</returns> public static Token Read(string tokenXml) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml)); + Requires.NotNullOrEmpty(tokenXml, "tokenXml"); return Read(tokenXml, (Uri)null); } @@ -154,7 +154,7 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="audience">The URI that this token must have been crafted to be sent to. Use <c>null</c> to accept any intended audience.</param> /// <returns>The deserialized token.</returns> public static Token Read(string tokenXml, Uri audience) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml)); + Requires.NotNullOrEmpty(tokenXml, "tokenXml"); return Read(tokenXml, audience, Enumerable.Empty<SecurityToken>()); } @@ -165,8 +165,8 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="decryptionTokens">Any X.509 certificates that may be used to decrypt the token, if necessary.</param> /// <returns>The deserialized token.</returns> public static Token Read(string tokenXml, IEnumerable<SecurityToken> decryptionTokens) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml)); - Contract.Requires<ArgumentNullException>(decryptionTokens != null); + Requires.NotNullOrEmpty(tokenXml, "tokenXml"); + Requires.NotNull(decryptionTokens, "decryptionTokens"); return Read(tokenXml, null, decryptionTokens); } @@ -178,8 +178,8 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="decryptionTokens">Any X.509 certificates that may be used to decrypt the token, if necessary.</param> /// <returns>The deserialized token.</returns> public static Token Read(string tokenXml, Uri audience, IEnumerable<SecurityToken> decryptionTokens) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(tokenXml)); - Contract.Requires<ArgumentNullException>(decryptionTokens != null); + Requires.NotNullOrEmpty(tokenXml, "tokenXml"); + Requires.NotNull(decryptionTokens, "decryptionTokens"); Contract.Ensures(Contract.Result<Token>() != null); TokenDecryptor decryptor = null; @@ -201,7 +201,7 @@ namespace DotNetOpenAuth.InfoCard { /// </returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive"), Pure] internal static bool IsEncrypted(string tokenXml) { - Contract.Requires<ArgumentNullException>(tokenXml != null); + Requires.NotNull(tokenXml, "tokenXml"); var stringReader = new StringReader(tokenXml); XmlReader tokenReader; @@ -230,7 +230,7 @@ namespace DotNetOpenAuth.InfoCard { /// <c>true</c> if the specified token XML is encrypted; otherwise, <c>false</c>. /// </returns> private static bool IsEncrypted(XmlReader tokenXmlReader) { - Contract.Requires<ArgumentNullException>(tokenXmlReader != null); + Requires.NotNull(tokenXmlReader, "tokenXmlReader"); return tokenXmlReader.IsStartElement(TokenDecryptor.XmlEncryptionStrings.EncryptedData, TokenDecryptor.XmlEncryptionStrings.Namespace); } diff --git a/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenDecryptor.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenDecryptor.cs index eb59fd3..e9199c7 100644 --- a/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenDecryptor.cs +++ b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenDecryptor.cs @@ -89,7 +89,7 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="reader">The encrypted token XML reader.</param> /// <returns>A byte array of the contents of the encrypted token</returns> internal byte[] DecryptToken(XmlReader reader) { - Contract.Requires<ArgumentNullException>(reader != null); + Requires.NotNull(reader, "reader"); Contract.Ensures(Contract.Result<byte[]>() != null); byte[] securityTokenData; diff --git a/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenUtility.cs b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenUtility.cs index 69fa441..2d211b5 100644 --- a/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenUtility.cs +++ b/src/DotNetOpenAuth.InfoCard/InfoCard/Token/TokenUtility.cs @@ -162,7 +162,7 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="authzContext">The Authorization Context</param> /// <returns>A unique ID for this user at this web site.</returns> internal static string GetUniqueName(AuthorizationContext authzContext) { - Contract.Requires<ArgumentNullException>(authzContext != null); + Requires.NotNull(authzContext, "authzContext"); Claim uniqueIssuerClaim = null; Claim uniqueUserClaim = null; @@ -218,7 +218,7 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="ppid">The personal private identifier.</param> /// <returns>A string containing the XXX-XXXX-XXX cosmetic value.</returns> internal static string CalculateSiteSpecificID(string ppid) { - Contract.Requires<ArgumentNullException>(ppid != null); + Requires.NotNull(ppid, "ppid"); Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); int callSignChars = 10; @@ -248,7 +248,7 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="cs">the claimset which contains the claim</param> /// <returns>a RSA claim</returns> private static Claim GetUniqueRsaClaim(ClaimSet cs) { - Contract.Requires<ArgumentNullException>(cs != null); + Requires.NotNull(cs, "cs"); Claim rsa = null; @@ -270,8 +270,8 @@ namespace DotNetOpenAuth.InfoCard { /// <param name="claimValue">the claim value to hash with.</param> /// <returns>A base64 representation of the combined ID.</returns> private static string ComputeCombinedId(RSA issuerKey, string claimValue) { - Contract.Requires<ArgumentNullException>(issuerKey != null); - Contract.Requires<ArgumentNullException>(claimValue != null); + Requires.NotNull(issuerKey, "issuerKey"); + Requires.NotNull(claimValue, "claimValue"); Contract.Ensures(Contract.Result<string>() != null); int nameLength = Encoding.UTF8.GetByteCount(claimValue); diff --git a/src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs b/src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs index 58d7d51..da1c7ff 100644 --- a/src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs +++ b/src/DotNetOpenAuth.InfoCard/InfoCardErrorUtilities.cs @@ -26,7 +26,7 @@ namespace DotNetOpenAuth { /// <exception cref="InfoCard.InformationCardException">Thrown if <paramref name="condition"/> evaluates to <c>false</c>.</exception> [Pure] internal static void VerifyInfoCard(bool condition, string errorMessage, params object[] args) { - Contract.Requires<ArgumentNullException>(args != null); + Requires.NotNull(args, "args"); Contract.Ensures(condition); Contract.EnsuresOnThrow<InfoCard.InformationCardException>(!condition); Contract.Assume(errorMessage != null); diff --git a/src/DotNetOpenAuth.Messaging.UI/DotNetOpenAuth.Messaging.UI.csproj b/src/DotNetOpenAuth.Messaging.UI/DotNetOpenAuth.Messaging.UI.csproj index d38f5ef..1807986 100644 --- a/src/DotNetOpenAuth.Messaging.UI/DotNetOpenAuth.Messaging.UI.csproj +++ b/src/DotNetOpenAuth.Messaging.UI/DotNetOpenAuth.Messaging.UI.csproj @@ -13,7 +13,6 @@ <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>DotNetOpenAuth</RootNamespace> <AssemblyName>DotNetOpenAuth.Messaging.UI</AssemblyName> - <CodeContractsRewritingDisabled>true</CodeContractsRewritingDisabled> </PropertyGroup> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" /> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> diff --git a/src/DotNetOpenAuth.Messaging/Configuration/DotNetOpenAuthSection.cs b/src/DotNetOpenAuth.Messaging/Configuration/DotNetOpenAuthSection.cs index 70c8cce..e0c7fc4 100644 --- a/src/DotNetOpenAuth.Messaging/Configuration/DotNetOpenAuthSection.cs +++ b/src/DotNetOpenAuth.Messaging/Configuration/DotNetOpenAuthSection.cs @@ -33,24 +33,12 @@ namespace DotNetOpenAuth.Configuration { private const string OAuthElementName = "oauth"; /// <summary> - /// A value indicating whether this instance came from a real Configuration instance. - /// </summary> - private bool synthesizedInstance; - - /// <summary> /// Initializes a new instance of the <see cref="DotNetOpenAuthSection"/> class. /// </summary> internal DotNetOpenAuthSection() { } /// <summary> - /// Initializes a new instance of the <see cref="DotNetOpenAuthSection"/> class. - /// </summary> - private DotNetOpenAuthSection(bool synthesized) { - this.synthesizedInstance = synthesized; - } - - /// <summary> /// Gets the messaging configuration element. /// </summary> public static MessagingElement Messaging { @@ -67,6 +55,8 @@ namespace DotNetOpenAuth.Configuration { /// <summary> /// Gets a named section in this section group, or <c>null</c> if no such section is defined. /// </summary> + /// <param name="name">The name of the section to obtain.</param> + /// <returns>The desired section, or null if it could not be obtained.</returns> internal static ConfigurationSection GetNamedSection(string name) { string fullyQualifiedSectionName = SectionName + "/" + name; if (HttpContext.Current != null) { diff --git a/src/DotNetOpenAuth.Messaging/DotNetOpenAuth.Messaging.csproj b/src/DotNetOpenAuth.Messaging/DotNetOpenAuth.Messaging.csproj index 801f447..68d1864 100644 --- a/src/DotNetOpenAuth.Messaging/DotNetOpenAuth.Messaging.csproj +++ b/src/DotNetOpenAuth.Messaging/DotNetOpenAuth.Messaging.csproj @@ -11,7 +11,6 @@ <ProjectGuid>{60426312-6AE5-4835-8667-37EDEA670222}</ProjectGuid> <AppDesignerFolder>Properties</AppDesignerFolder> <AssemblyName>DotNetOpenAuth.Messaging</AssemblyName> - <CodeContractsRewritingDisabled>true</CodeContractsRewritingDisabled> </PropertyGroup> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" /> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> diff --git a/src/DotNetOpenAuth.Messaging/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.Messaging/Properties/AssemblyInfo.cs index 9426fb5..25999da 100644 --- a/src/DotNetOpenAuth.Messaging/Properties/AssemblyInfo.cs +++ b/src/DotNetOpenAuth.Messaging/Properties/AssemblyInfo.cs @@ -64,6 +64,7 @@ using System.Web.UI; [assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.AuthorizationServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] [assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] [assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] +[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.Client.UI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] #else [assembly: InternalsVisibleTo("DotNetOpenAuth.Test")] [assembly: InternalsVisibleTo("DotNetOpenAuth.InfoCard")] diff --git a/src/DotNetOpenAuth.Messaging/Requires.cs b/src/DotNetOpenAuth.Messaging/Requires.cs index e322da7..ce3a01f 100644 --- a/src/DotNetOpenAuth.Messaging/Requires.cs +++ b/src/DotNetOpenAuth.Messaging/Requires.cs @@ -46,6 +46,18 @@ namespace DotNetOpenAuth { } /// <summary> + /// Validates that an array is not null or empty. + /// </summary> + /// <param name="value">The value.</param> + /// <param name="parameterName">Name of the parameter.</param> + [Pure, ContractArgumentValidator, 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> @@ -82,7 +94,7 @@ namespace DotNetOpenAuth { /// <param name="parameterName">Name of the parameter.</param> /// <param name="message">The message to include with the exception.</param> [Pure, ContractArgumentValidator, DebuggerStepThrough] - internal static void True(bool condition, string parameterName, string message = null) { + internal static void True(bool condition, string parameterName = null, string message = null) { if (!condition) { throw new ArgumentException(message ?? Strings.InvalidArgument, parameterName); } @@ -163,6 +175,20 @@ namespace DotNetOpenAuth { } /// <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, ContractArgumentValidator, 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> diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs index 253b104..d0992bd 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs @@ -35,10 +35,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { securitySettings, messageFactory ?? new OAuthConsumerMessageFactory(), InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) { - Contract.Requires<ArgumentNullException>(tokenManager != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); - Contract.Requires<ArgumentNullException>(signingBindingElement != null); - Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel); + Requires.NotNull(tokenManager, "tokenManager"); + Requires.NotNull(securitySettings, "securitySettings"); + Requires.NotNull(signingBindingElement, "signingBindingElement"); + Requires.True(signingBindingElement.SignatureCallback == null, "signingBindingElement", OAuthStrings.SigningElementAlreadyAssociatedWithChannel); } /// <summary> diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs index 7408789..7a7998e 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs @@ -21,7 +21,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </summary> /// <param name="signingCertificate">The certificate used to sign outgoing messages.</param> public RsaSha1ConsumerSigningBindingElement(X509Certificate2 signingCertificate) { - Contract.Requires<ArgumentNullException>(signingCertificate != null); + Requires.NotNull(signingCertificate, "signingCertificate"); this.SigningCertificate = signingCertificate; } diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs index 82ee92f..7ec1399 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs @@ -27,8 +27,8 @@ namespace DotNetOpenAuth.OAuth { /// <param name="serviceDescription">The endpoints and behavior of the Service Provider.</param> /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> protected ConsumerBase(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) { - Contract.Requires<ArgumentNullException>(serviceDescription != null); - Contract.Requires<ArgumentNullException>(tokenManager != null); + Requires.NotNull(serviceDescription, "serviceDescription"); + Requires.NotNull(tokenManager, "tokenManager"); ITamperProtectionChannelBindingElement signingElement = serviceDescription.CreateTamperProtectionElement(); INonceStore store = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge); @@ -110,7 +110,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="accessToken">The access token that permits access to the protected resource.</param> /// <returns>The initialized WebRequest object.</returns> public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) { - Contract.Requires<ArgumentNullException>(endpoint != null); + Requires.NotNull(endpoint, "endpoint"); Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(accessToken)); return this.PrepareAuthorizedRequest(endpoint, accessToken, EmptyDictionary<string, string>.Instance); @@ -125,9 +125,9 @@ namespace DotNetOpenAuth.OAuth { /// <param name="extraData">Extra parameters to include in the message. Must not be null, but may be empty.</param> /// <returns>The initialized WebRequest object.</returns> public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken, IDictionary<string, string> extraData) { - Contract.Requires<ArgumentNullException>(endpoint != null); + Requires.NotNull(endpoint, "endpoint"); Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(accessToken)); - Contract.Requires<ArgumentNullException>(extraData != null); + Requires.NotNull(extraData, "extraData"); IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); foreach (var pair in extraData) { @@ -146,9 +146,9 @@ namespace DotNetOpenAuth.OAuth { /// <param name="binaryData">Extra parameters to include in the message. Must not be null, but may be empty.</param> /// <returns>The initialized WebRequest object.</returns> public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken, IEnumerable<MultipartPostPart> binaryData) { - Contract.Requires<ArgumentNullException>(endpoint != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken)); - Contract.Requires<ArgumentNullException>(binaryData != null); + Requires.NotNull(endpoint, "endpoint"); + Requires.NotNullOrEmpty(accessToken, "accessToken"); + Requires.NotNull(binaryData, "binaryData"); AccessProtectedResourceRequest message = this.CreateAuthorizingMessage(endpoint, accessToken); foreach (MultipartPostPart part in binaryData) { @@ -176,7 +176,7 @@ namespace DotNetOpenAuth.OAuth { /// </remarks> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Type of parameter forces the method to apply only to specific scenario.")] public HttpWebRequest PrepareAuthorizedRequest(AccessProtectedResourceRequest message) { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); return this.OAuthChannel.InitializeRequest(message); } @@ -214,7 +214,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="accessToken">The access token that permits access to the protected resource.</param> /// <returns>The initialized WebRequest object.</returns> protected internal AccessProtectedResourceRequest CreateAuthorizingMessage(MessageReceivingEndpoint endpoint, string accessToken) { - Contract.Requires<ArgumentNullException>(endpoint != null); + Requires.NotNull(endpoint, "endpoint"); Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(accessToken)); AccessProtectedResourceRequest message = new AccessProtectedResourceRequest(endpoint, this.ServiceProvider.Version) { @@ -276,7 +276,7 @@ namespace DotNetOpenAuth.OAuth { /// The access token assigned by the Service Provider. /// </returns> protected AuthorizedTokenResponse ProcessUserAuthorization(string requestToken, string verifier) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(requestToken)); + Requires.NotNullOrEmpty(requestToken, "requestToken"); Contract.Ensures(Contract.Result<AuthorizedTokenResponse>() != null); var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint, this.ServiceProvider.Version) { diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs index de37b80..e7d7f4f 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs @@ -79,7 +79,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="openIdAuthenticationRequest">The OpenID authentication request.</param> /// <param name="scope">The scope of access that is requested of the service provider.</param> public void AttachAuthorizationRequest(IAuthenticationRequest openIdAuthenticationRequest, string scope) { - Contract.Requires<ArgumentNullException>(openIdAuthenticationRequest != null); + Requires.NotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest"); var authorizationRequest = new AuthorizationRequest { Consumer = this.ConsumerKey, @@ -101,8 +101,8 @@ namespace DotNetOpenAuth.OAuth { /// The token manager instance must implement <see cref="IOpenIdOAuthTokenManager"/>. /// </remarks> public AuthorizedTokenResponse ProcessUserAuthorization(IAuthenticationResponse openIdAuthenticationResponse) { - Contract.Requires<ArgumentNullException>(openIdAuthenticationResponse != null); - Contract.Requires<InvalidOperationException>(this.TokenManager is IOpenIdOAuthTokenManager); + Requires.NotNull(openIdAuthenticationResponse, "openIdAuthenticationResponse"); + Requires.ValidState(this.TokenManager is IOpenIdOAuthTokenManager); var openidTokenManager = this.TokenManager as IOpenIdOAuthTokenManager; ErrorUtilities.VerifyOperation(openidTokenManager != null, OAuthStrings.OpenIdOAuthExtensionRequiresSpecialTokenManagerInterface, typeof(IOpenIdOAuthTokenManager).FullName); @@ -140,7 +140,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="request">The incoming HTTP request.</param> /// <returns>The access token, or null if no incoming authorization message was recognized.</returns> public AuthorizedTokenResponse ProcessUserAuthorization(HttpRequestInfo request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); UserAuthorizationResponse authorizationMessage; if (this.Channel.TryReadFromRequest<UserAuthorizationResponse>(request, out authorizationMessage)) { diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderTokenManager.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderTokenManager.cs index 5d10a0b..13320b3 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderTokenManager.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/IServiceProviderTokenManager.cs @@ -102,7 +102,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </returns> /// <exception cref="KeyNotFoundException">Thrown if the consumer key cannot be found.</exception> IConsumerDescription IServiceProviderTokenManager.GetConsumer(string consumerKey) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(consumerKey)); + Requires.NotNullOrEmpty(consumerKey, "consumerKey"); Contract.Ensures(Contract.Result<IConsumerDescription>() != null); throw new NotImplementedException(); } @@ -118,7 +118,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// been authorized, has expired or does not exist. /// </returns> bool IServiceProviderTokenManager.IsRequestTokenAuthorized(string requestToken) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(requestToken)); + Requires.NotNullOrEmpty(requestToken, "requestToken"); throw new NotImplementedException(); } @@ -135,7 +135,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// log and throw the appropriate error. /// </remarks> IServiceProviderRequestToken IServiceProviderTokenManager.GetRequestToken(string token) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token)); + Requires.NotNullOrEmpty(token, "token"); Contract.Ensures(Contract.Result<IServiceProviderRequestToken>() != null); throw new NotImplementedException(); } @@ -153,7 +153,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// log and throw the appropriate error. /// </remarks> IServiceProviderAccessToken IServiceProviderTokenManager.GetAccessToken(string token) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token)); + Requires.NotNullOrEmpty(token, "token"); Contract.Ensures(Contract.Result<IServiceProviderAccessToken>() != null); throw new NotImplementedException(); } @@ -171,7 +171,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// will automatically be saved without any extra handling). /// </remarks> void IServiceProviderTokenManager.UpdateToken(IServiceProviderRequestToken token) { - Contract.Requires<ArgumentNullException>(token != null); + Requires.NotNull(token, "token"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthIdentity.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthIdentity.cs index 65bde20..6865f79 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthIdentity.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthIdentity.cs @@ -24,7 +24,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </summary> /// <param name="username">The username.</param> internal OAuthIdentity(string username) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(username)); + Requires.NotNullOrEmpty(username, "username"); this.Name = username; } diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthPrincipal.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthPrincipal.cs index 82ecb0a..b274265 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthPrincipal.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthPrincipal.cs @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <param name="token">The access token.</param> internal OAuthPrincipal(IServiceProviderAccessToken token) : this(token.Username, token.Roles) { - Contract.Requires<ArgumentNullException>(token != null); + Requires.NotNull(token, "token"); this.AccessToken = token.Token; } diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs index e6d594f..a3bf2e9 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs @@ -35,10 +35,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { securitySettings, messageTypeProvider ?? new OAuthServiceProviderMessageFactory(tokenManager), InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) { - Contract.Requires<ArgumentNullException>(tokenManager != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); - Contract.Requires<ArgumentNullException>(signingBindingElement != null); - Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel); + Requires.NotNull(tokenManager, "tokenManager"); + Requires.NotNull(securitySettings, "securitySettings"); + Requires.NotNull(signingBindingElement, "signingBindingElement"); + Requires.True(signingBindingElement.SignatureCallback == null, "signingBindingElement", OAuthStrings.SigningElementAlreadyAssociatedWithChannel); } /// <summary> diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs index 5b3c918..565756b 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderMessageFactory.cs @@ -26,7 +26,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </summary> /// <param name="tokenManager">The token manager instance to use.</param> public OAuthServiceProviderMessageFactory(IServiceProviderTokenManager tokenManager) { - Contract.Requires<ArgumentNullException>(tokenManager != null); + Requires.NotNull(tokenManager, "tokenManager"); this.tokenManager = tokenManager; } diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/RsaSha1ServiceProviderSigningBindingElement.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/RsaSha1ServiceProviderSigningBindingElement.cs index bcd0322..06a005b 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/RsaSha1ServiceProviderSigningBindingElement.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/RsaSha1ServiceProviderSigningBindingElement.cs @@ -26,7 +26,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </summary> /// <param name="tokenManager">The token manager.</param> public RsaSha1ServiceProviderSigningBindingElement(IServiceProviderTokenManager tokenManager) { - Contract.Requires<ArgumentNullException>(tokenManager != null); + Requires.NotNull(tokenManager, "tokenManager"); this.tokenManager = tokenManager; } diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs index f53aa1b..596336a 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs @@ -37,8 +37,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <param name="securitySettings">The security settings.</param> [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contract"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")] internal TokenHandlingBindingElement(IServiceProviderTokenManager tokenManager, ServiceProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(tokenManager != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(tokenManager, "tokenManager"); + Requires.NotNull(securitySettings, "securitySettings"); this.tokenManager = tokenManager; this.securitySettings = securitySettings; @@ -153,7 +153,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </summary> /// <param name="message">The incoming message carrying the access token.</param> private void VerifyThrowTokenNotExpired(AccessProtectedResourceRequest message) { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); try { IServiceProviderAccessToken token = this.tokenManager.GetAccessToken(message.AccessToken); diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs index 09f3fad..f926ee3 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs @@ -69,9 +69,9 @@ namespace DotNetOpenAuth.OAuth { /// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param> public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, OAuthServiceProviderMessageFactory messageTypeProvider) : this(serviceDescription, tokenManager, OAuthElement.Configuration.ServiceProvider.ApplicationStore.CreateInstance(HttpApplicationStore), messageTypeProvider) { - Contract.Requires<ArgumentNullException>(serviceDescription != null); - Contract.Requires<ArgumentNullException>(tokenManager != null); - Contract.Requires<ArgumentNullException>(messageTypeProvider != null); + Requires.NotNull(serviceDescription, "serviceDescription"); + Requires.NotNull(tokenManager, "tokenManager"); + Requires.NotNull(messageTypeProvider, "messageTypeProvider"); } /// <summary> @@ -92,10 +92,10 @@ namespace DotNetOpenAuth.OAuth { /// <param name="nonceStore">The nonce store.</param> /// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param> public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore, OAuthServiceProviderMessageFactory messageTypeProvider) { - Contract.Requires<ArgumentNullException>(serviceDescription != null); - Contract.Requires<ArgumentNullException>(tokenManager != null); - Contract.Requires<ArgumentNullException>(nonceStore != null); - Contract.Requires<ArgumentNullException>(messageTypeProvider != null); + Requires.NotNull(serviceDescription, "serviceDescription"); + Requires.NotNull(tokenManager, "tokenManager"); + Requires.NotNull(nonceStore, "nonceStore"); + Requires.NotNull(messageTypeProvider, "messageTypeProvider"); var signingElement = serviceDescription.CreateTamperProtectionElement(); this.ServiceDescription = serviceDescription; @@ -171,7 +171,7 @@ namespace DotNetOpenAuth.OAuth { } set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); this.channel = value; } } @@ -257,7 +257,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="request">The token request message the Consumer sent that the Service Provider is now responding to.</param> /// <returns>The response message to send using the <see cref="Channel"/>, after optionally adding extra data to it.</returns> public UnauthorizedTokenResponse PrepareUnauthorizedTokenMessage(UnauthorizedTokenRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); string token = this.TokenGenerator.GenerateRequestToken(request.ConsumerKey); string secret = this.TokenGenerator.GenerateSecret(); @@ -307,8 +307,8 @@ namespace DotNetOpenAuth.OAuth { /// security measures that are required are taken.</para> /// </remarks> public AuthorizationRequest ReadAuthorizationRequest(IHostProcessedRequest openIdRequest) { - Contract.Requires<ArgumentNullException>(openIdRequest != null); - Contract.Requires<InvalidOperationException>(this.TokenManager is ICombinedOpenIdProviderTokenManager); + Requires.NotNull(openIdRequest, "openIdRequest"); + Requires.ValidState(this.TokenManager is ICombinedOpenIdProviderTokenManager); var openidTokenManager = this.TokenManager as ICombinedOpenIdProviderTokenManager; ErrorUtilities.VerifyOperation(openidTokenManager != null, OAuthStrings.OpenIdOAuthExtensionRequiresSpecialTokenManagerInterface, typeof(IOpenIdOAuthTokenManager).FullName); @@ -337,9 +337,9 @@ namespace DotNetOpenAuth.OAuth { [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to take IAuthenticationRequest because that's the only supported use case.")] [Obsolete("Call the overload that doesn't take a consumerKey instead.")] public void AttachAuthorizationResponse(IHostProcessedRequest openIdAuthenticationRequest, string consumerKey, string scope) { - Contract.Requires<ArgumentNullException>(openIdAuthenticationRequest != null); - Contract.Requires<ArgumentException>((consumerKey == null) == (scope == null)); - Contract.Requires<InvalidOperationException>(this.TokenManager is ICombinedOpenIdProviderTokenManager); + Requires.NotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest"); + Requires.True((consumerKey == null) == (scope == null), null); + Requires.ValidState(this.TokenManager is ICombinedOpenIdProviderTokenManager); var openidTokenManager = (ICombinedOpenIdProviderTokenManager)this.TokenManager; ErrorUtilities.VerifyArgument(consumerKey == null || consumerKey == openidTokenManager.GetConsumerKey(openIdAuthenticationRequest.Realm), OAuthStrings.OpenIdOAuthRealmConsumerKeyDoNotMatch); @@ -353,8 +353,8 @@ namespace DotNetOpenAuth.OAuth { /// <param name="scope">The approved access scope. Use <c>null</c> to indicate no access was granted. The empty string will be interpreted as some default level of access is granted.</param> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to take IAuthenticationRequest because that's the only supported use case.")] public void AttachAuthorizationResponse(IHostProcessedRequest openIdAuthenticationRequest, string scope) { - Contract.Requires<ArgumentNullException>(openIdAuthenticationRequest != null); - Contract.Requires<InvalidOperationException>(this.TokenManager is ICombinedOpenIdProviderTokenManager); + Requires.NotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest"); + Requires.ValidState(this.TokenManager is ICombinedOpenIdProviderTokenManager); var openidTokenManager = this.TokenManager as ICombinedOpenIdProviderTokenManager; IOpenIdMessageExtension response; @@ -385,7 +385,7 @@ namespace DotNetOpenAuth.OAuth { /// </returns> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Consistent user experience with instance.")] public UserAuthorizationResponse PrepareAuthorizationResponse(UserAuthorizationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); // It is very important for us to ignore the oauth_callback argument in the // UserAuthorizationRequest if the Consumer is a 1.0a consumer or else we @@ -422,8 +422,8 @@ namespace DotNetOpenAuth.OAuth { /// </returns> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Consistent user experience with instance.")] public UserAuthorizationResponse PrepareAuthorizationResponse(UserAuthorizationRequest request, Uri callback) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentNullException>(callback != null); + Requires.NotNull(request, "request"); + Requires.NotNull(callback, "callback"); var authorization = new UserAuthorizationResponse(callback, request.Version) { RequestToken = request.RequestToken, @@ -466,7 +466,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="request">The Consumer's message requesting an access token.</param> /// <returns>The HTTP response to actually send to the Consumer.</returns> public AuthorizedTokenResponse PrepareAccessTokenMessage(AuthorizedTokenRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); ErrorUtilities.VerifyProtocol(this.TokenManager.IsRequestTokenAuthorized(request.RequestToken), OAuthStrings.AccessTokenNotAuthorized, request.RequestToken); @@ -523,7 +523,7 @@ namespace DotNetOpenAuth.OAuth { /// </remarks> /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestInfo request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); AccessProtectedResourceRequest accessMessage; if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(request, out accessMessage)) { @@ -545,7 +545,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="request">The request.</param> /// <returns>The <see cref="IPrincipal"/> instance that can be used for access control of resources.</returns> public OAuthPrincipal CreatePrincipal(AccessProtectedResourceRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); IServiceProviderAccessToken accessToken = this.TokenManager.GetAccessToken(request.AccessToken); return new OAuthPrincipal(accessToken); diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITokenManager.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITokenManager.cs index af7eb54..7d68b63 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITokenManager.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITokenManager.cs @@ -97,7 +97,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </returns> /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception> string ITokenManager.GetTokenSecret(string token) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token)); + Requires.NotNullOrEmpty(token, "token"); Contract.Ensures(Contract.Result<string>() != null); throw new NotImplementedException(); } @@ -116,8 +116,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// method. /// </remarks> void ITokenManager.StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(request, "request"); + Requires.NotNull(response, "response"); throw new NotImplementedException(); } @@ -145,10 +145,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </para> /// </remarks> void ITokenManager.ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(consumerKey)); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(requestToken)); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken)); - Contract.Requires<ArgumentNullException>(accessTokenSecret != null); + Requires.NotNullOrEmpty(consumerKey, "consumerKey"); + Requires.NotNullOrEmpty(requestToken, "requestToken"); + Requires.NotNullOrEmpty(accessToken, "accessToken"); + Requires.NotNull(accessTokenSecret, "accessTokenSecret"); throw new NotImplementedException(); } @@ -160,7 +160,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Request or Access token, or invalid if the token is not recognized. /// </returns> TokenType ITokenManager.GetTokenType(string token) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(token)); + Requires.NotNullOrEmpty(token, "token"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs index cb15059..a8ea026 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs @@ -40,10 +40,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")] protected OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements) : base(messageTypeProvider, bindingElements) { - Contract.Requires<ArgumentNullException>(tokenManager != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); - Contract.Requires<ArgumentNullException>(signingBindingElement != null); - Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel); + Requires.NotNull(tokenManager, "tokenManager"); + Requires.NotNull(securitySettings, "securitySettings"); + Requires.NotNull(signingBindingElement, "signingBindingElement"); + Requires.True(signingBindingElement.SignatureCallback == null, "signingBindingElement", OAuthStrings.SigningElementAlreadyAssociatedWithChannel); Contract.Requires<ArgumentNullException>(bindingElements != null, "bindingElements"); this.TokenManager = tokenManager; @@ -79,7 +79,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <param name="request">The message to attach.</param> /// <returns>The initialized web request.</returns> internal HttpWebRequest InitializeRequest(IDirectedProtocolMessage request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); ProcessOutgoingMessage(request); return this.CreateHttpRequest(request); @@ -249,8 +249,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <param name="source">The dictionary with names and values to encode.</param> /// <param name="destination">The dictionary to add the encoded pairs to.</param> private static void UriEscapeParameters(IEnumerable<KeyValuePair<string, string>> source, IDictionary<string, string> destination) { - Contract.Requires<ArgumentNullException>(source != null); - Contract.Requires<ArgumentNullException>(destination != null); + Requires.NotNull(source, "source"); + Requires.NotNull(destination, "destination"); foreach (var pair in source) { var key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key); @@ -265,7 +265,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <param name="message">The message.</param> /// <returns>"POST", "GET" or some other similar http verb.</returns> private static string GetHttpMethod(IDirectedProtocolMessage message) { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); var signedMessage = message as ITamperResistantOAuthMessage; if (signedMessage != null) { diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs index 24382fe..2c47453 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs @@ -151,9 +151,9 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </remarks> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Unavoidable")] internal static string ConstructSignatureBaseString(ITamperResistantOAuthMessage message, MessageDictionary messageDictionary) { - Contract.Requires<ArgumentNullException>(message != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(message.HttpMethod)); - Contract.Requires<ArgumentNullException>(messageDictionary != null); + Requires.NotNull(message, "message"); + Requires.NotNullOrEmpty(message.HttpMethod, "message.HttpMethod"); + Requires.NotNull(messageDictionary, "messageDictionary"); ErrorUtilities.VerifyArgument(messageDictionary.Message == message, "Message references are not equal."); List<string> signatureBaseStringElements = new List<string>(3); @@ -279,7 +279,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <c>true</c> if the signature on the message is valid; otherwise, <c>false</c>. /// </returns> protected virtual bool IsSignatureValid(ITamperResistantOAuthMessage message) { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); string signature = this.GetSignature(message); return MessagingUtilities.EqualsConstantTime(message.Signature, signature); diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs index 4ff52fd..4450fb5 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBaseContract.cs @@ -39,8 +39,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <param name="message">The message to sign.</param> /// <returns>The signature for the message.</returns> protected override string GetSignature(ITamperResistantOAuthMessage message) { - Contract.Requires<ArgumentNullException>(message != null); - Contract.Requires<InvalidOperationException>(this.Channel != null); + Requires.NotNull(message, "message"); + Requires.ValidState(this.Channel != null); throw new NotImplementedException(); } } diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs index 67c5205..849ad5e 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs @@ -30,10 +30,9 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// in preferred use order. /// </param> internal SigningBindingElementChain(ITamperProtectionChannelBindingElement[] signers) { - Contract.Requires<ArgumentNullException>(signers != null); - Contract.Requires<ArgumentException>(signers.Length > 0); - Contract.Requires<ArgumentException>(!signers.Contains(null), MessagingStrings.SequenceContainsNullElement); - Contract.Requires<ArgumentException>(signers.Select(s => s.Protection).Distinct().Count() == 1, OAuthStrings.SigningElementsMustShareSameProtection); + Requires.NotNullOrEmpty(signers, "signers"); + Requires.NullOrWithNoNullElements(signers, "signers"); + Requires.True(signers.Select(s => s.Protection).Distinct().Count() == 1, "signers", OAuthStrings.SigningElementsMustShareSameProtection); this.signers = signers; } diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBase.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBase.cs index 1a0ba23..faa4345 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBase.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBase.cs @@ -65,8 +65,8 @@ namespace DotNetOpenAuth.OAuth.Messages { /// <param name="originatingRequest">The request that asked for this direct response.</param> /// <param name="version">The OAuth version.</param> protected MessageBase(MessageProtections protectionRequired, IDirectedProtocolMessage originatingRequest, Version version) { - Contract.Requires<ArgumentNullException>(originatingRequest != null); - Contract.Requires<ArgumentNullException>(version != null); + Requires.NotNull(originatingRequest, "originatingRequest"); + Requires.NotNull(version, "version"); this.protectionRequired = protectionRequired; this.transport = MessageTransport.Direct; @@ -82,8 +82,8 @@ namespace DotNetOpenAuth.OAuth.Messages { /// <param name="recipient">The URI that a directed message will be delivered to.</param> /// <param name="version">The OAuth version.</param> protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient, Version version) { - Contract.Requires<ArgumentNullException>(recipient != null); - Contract.Requires<ArgumentNullException>(version != null); + Requires.NotNull(recipient, "recipient"); + Requires.NotNull(version, "version"); this.protectionRequired = protectionRequired; this.transport = transport; @@ -242,7 +242,7 @@ namespace DotNetOpenAuth.OAuth.Messages { /// The string representation of this object. /// </returns> internal virtual string ToString(Channel channel) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); StringBuilder builder = new StringBuilder(); builder.AppendFormat(CultureInfo.InvariantCulture, "{0} message", GetType().Name); diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenResponse.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenResponse.cs index 0be9f63..04dee88 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenResponse.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UnauthorizedTokenResponse.cs @@ -27,8 +27,8 @@ namespace DotNetOpenAuth.OAuth.Messages { /// </remarks> protected internal UnauthorizedTokenResponse(UnauthorizedTokenRequest requestMessage, string requestToken, string tokenSecret) : this(requestMessage, requestMessage.Version) { - Contract.Requires<ArgumentNullException>(requestToken != null); - Contract.Requires<ArgumentNullException>(tokenSecret != null); + Requires.NotNull(requestToken, "requestToken"); + Requires.NotNull(tokenSecret, "tokenSecret"); this.RequestToken = requestToken; this.TokenSecret = tokenSecret; diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs b/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs index 4418b5e..3b7437c 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs @@ -140,7 +140,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="version">The OAuth version to get.</param> /// <returns>A matching <see cref="Protocol"/> instance.</returns> internal static Protocol Lookup(Version version) { - Contract.Requires<ArgumentNullException>(version != null); + Requires.NotNull(version, "version"); Contract.Requires<ArgumentOutOfRangeException>(AllVersions.Any(p => p.Version == version)); return AllVersions.First(p => p.Version == version); } diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs index ad40fa5..73c2bd6 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs @@ -24,7 +24,7 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="authorizationServer">The authorization server.</param> public AuthorizationServer(IAuthorizationServer authorizationServer) { - Contract.Requires<ArgumentNullException>(authorizationServer != null); + Requires.NotNull(authorizationServer, "authorizationServer"); this.OAuthChannel = new OAuth2AuthorizationServerChannel(authorizationServer); } @@ -81,7 +81,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param> /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) { - Contract.Requires<ArgumentNullException>(authorizationRequest != null); + Requires.NotNull(authorizationRequest, "authorizationRequest"); var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, scopes, callback); this.Channel.Respond(response); @@ -93,7 +93,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorizationRequest">The authorization request to disapprove.</param> /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { - Contract.Requires<ArgumentNullException>(authorizationRequest != null); + Requires.NotNull(authorizationRequest, "authorizationRequest"); var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback); this.Channel.Respond(response); @@ -123,7 +123,7 @@ namespace DotNetOpenAuth.OAuth2 { /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead. /// </remarks> public bool TryPrepareAccessTokenResponse(HttpRequestInfo httpRequestInfo, out IDirectResponseProtocolMessage response) { - Contract.Requires<ArgumentNullException>(httpRequestInfo != null); + Requires.NotNull(httpRequestInfo, "httpRequestInfo"); Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<IDirectResponseProtocolMessage>(out response) != null)); var request = this.ReadAccessTokenRequest(httpRequestInfo); @@ -158,7 +158,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> /// <returns>The authorization response message to send to the Client.</returns> public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { - Contract.Requires<ArgumentNullException>(authorizationRequest != null); + Requires.NotNull(authorizationRequest, "authorizationRequest"); Contract.Ensures(Contract.Result<EndUserAuthorizationFailedResponse>() != null); if (callback == null) { @@ -178,8 +178,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> /// <returns>The authorization response message to send to the Client.</returns> public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) { - Contract.Requires<ArgumentNullException>(authorizationRequest != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(userName)); + Requires.NotNull(authorizationRequest, "authorizationRequest"); + Requires.NotNullOrEmpty(userName, "userName"); Contract.Ensures(Contract.Result<EndUserAuthorizationSuccessResponseBase>() != null); if (callback == null) { @@ -218,7 +218,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="includeRefreshToken">If set to <c>true</c>, the response will include a long-lived refresh token.</param> /// <returns>The response message to send to the client.</returns> public virtual IDirectResponseProtocolMessage PrepareAccessTokenResponse(AccessTokenRequestBase request, bool includeRefreshToken = true) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); var tokenRequest = (IAuthorizationCarryingRequest)request; var response = new AccessTokenSuccessResponse(request) { @@ -236,7 +236,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <returns>The URL to redirect to. Never <c>null</c>.</returns> /// <exception cref="ProtocolException">Thrown if no callback URL could be determined.</exception> protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) { - Contract.Requires<ArgumentNullException>(authorizationRequest != null); + Requires.NotNull(authorizationRequest, "authorizationRequest"); Contract.Ensures(Contract.Result<Uri>() != null); var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier); diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs index ffa217b..acd8fb3 100644 --- a/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs +++ b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs @@ -178,7 +178,7 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="authorization">The authorization.</param> public ClientAuthorizationCompleteEventArgs(IAuthorizationState authorization) { - Contract.Requires<ArgumentNullException>(authorization != null); + Requires.NotNull(authorization, "authorization"); this.Authorization = authorization; } diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs index 51aac39..ec001ec 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="clientIdentifier">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> protected ClientBase(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) { - Contract.Requires<ArgumentNullException>(authorizationServer != null); + Requires.NotNull(authorizationServer, "authorizationServer"); this.AuthorizationServer = authorizationServer; this.Channel = new OAuth2ClientChannel(); this.ClientIdentifier = clientIdentifier; @@ -63,8 +63,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="request">The request for protected resources from the service provider.</param> /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param> public static void AuthorizeRequest(HttpWebRequest request, string accessToken) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken)); + Requires.NotNull(request, "request"); + Requires.NotNullOrEmpty(accessToken, "accessToken"); OAuthUtilities.AuthorizeWithBearerToken(request, accessToken); } @@ -76,9 +76,9 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="request">The request for protected resources from the service provider.</param> /// <param name="authorization">The authorization for this request previously obtained via OAuth.</param> public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentNullException>(authorization != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.AccessToken)); + Requires.NotNull(request, "request"); + Requires.NotNull(authorization, "authorization"); + Requires.True(!string.IsNullOrEmpty(authorization.AccessToken), "authorization"); Contract.Requires<ProtocolException>(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null); if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) { @@ -103,8 +103,8 @@ namespace DotNetOpenAuth.OAuth2 { /// If the parameter value was updated, this method calls <see cref="IAuthorizationState.SaveChanges"/> on that instance. /// </remarks> public bool RefreshAuthorization(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null) { - Contract.Requires<ArgumentNullException>(authorization != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.RefreshToken)); + Requires.NotNull(authorization, "authorization"); + Requires.True(!string.IsNullOrEmpty(authorization.RefreshToken), "authorization"); if (skipIfUsefulLifeExceeds.HasValue && authorization.AccessTokenExpirationUtc.HasValue) { TimeSpan usefulLifeRemaining = authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow; @@ -138,8 +138,8 @@ namespace DotNetOpenAuth.OAuth2 { /// replaced with the new one. /// </remarks> public IAuthorizationState GetScopedAccessToken(string refreshToken, HashSet<string> scope) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(refreshToken)); - Contract.Requires<ArgumentNullException>(scope != null); + Requires.NotNullOrEmpty(refreshToken, "refreshToken"); + Requires.NotNull(scope, "scope"); Contract.Ensures(Contract.Result<IAuthorizationState>() != null); var request = new AccessTokenRefreshRequest(this.AuthorizationServer) { @@ -161,8 +161,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorizationState">The authorization state maintained by the client.</param> /// <param name="accessTokenSuccess">The access token containing response message.</param> internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, AccessTokenSuccessResponse accessTokenSuccess) { - Contract.Requires<ArgumentNullException>(authorizationState != null); - Contract.Requires<ArgumentNullException>(accessTokenSuccess != null); + Requires.NotNull(authorizationState, "authorizationState"); + Requires.NotNull(accessTokenSuccess, "accessTokenSuccess"); authorizationState.AccessToken = accessTokenSuccess.AccessToken; authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime; @@ -189,8 +189,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorizationState">The authorization state maintained by the client.</param> /// <param name="accessTokenSuccess">The access token containing response message.</param> internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess) { - Contract.Requires<ArgumentNullException>(authorizationState != null); - Contract.Requires<ArgumentNullException>(accessTokenSuccess != null); + Requires.NotNull(authorizationState, "authorizationState"); + Requires.NotNull(accessTokenSuccess, "accessTokenSuccess"); authorizationState.AccessToken = accessTokenSuccess.AccessToken; authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime; @@ -215,8 +215,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorizationState">The authorization state to update.</param> /// <param name="authorizationSuccess">The authorization success message obtained from the authorization server.</param> internal void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) { - Contract.Requires<ArgumentNullException>(authorizationState != null); - Contract.Requires<ArgumentNullException>(authorizationSuccess != null); + Requires.NotNull(authorizationState, "authorizationState"); + Requires.NotNull(authorizationSuccess, "authorizationSuccess"); var accessTokenRequest = new AccessTokenAuthorizationCodeRequest(this.AuthorizationServer) { ClientIdentifier = this.ClientIdentifier, @@ -242,9 +242,9 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorization">The authorization to measure.</param> /// <returns>A fractional number no greater than 1. Could be negative if the access token has already expired.</returns> private static double ProportionalLifeRemaining(IAuthorizationState authorization) { - Contract.Requires<ArgumentNullException>(authorization != null); - Contract.Requires<ArgumentException>(authorization.AccessTokenIssueDateUtc.HasValue); - Contract.Requires<ArgumentException>(authorization.AccessTokenExpirationUtc.HasValue); + Requires.NotNull(authorization, "authorization"); + Requires.True(authorization.AccessTokenIssueDateUtc.HasValue, "authorization"); + Requires.True(authorization.AccessTokenExpirationUtc.HasValue, "authorization"); // Calculate what % of the total life this access token has left. TimeSpan totalLifetime = authorization.AccessTokenExpirationUtc.Value - authorization.AccessTokenIssueDateUtc.Value; diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs index e23eca4..d452525 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs @@ -37,8 +37,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="clientSecret">The client secret.</param> public UserAgentClient(Uri authorizationEndpoint, Uri tokenEndpoint, string clientIdentifier = null, string clientSecret = null) : this(new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint, TokenEndpoint = tokenEndpoint }, clientIdentifier, clientSecret) { - Contract.Requires<ArgumentNullException>(authorizationEndpoint != null); - Contract.Requires<ArgumentNullException>(tokenEndpoint != null); + Requires.NotNull(authorizationEndpoint, "authorizationEndpoint"); + Requires.NotNull(tokenEndpoint, "tokenEndpoint"); } /// <summary> @@ -69,8 +69,8 @@ namespace DotNetOpenAuth.OAuth2 { /// A fully-qualified URL suitable to initiate the authorization flow. /// </returns> public Uri RequestUserAuthorization(IAuthorizationState authorization, string state = null) { - Contract.Requires<ArgumentNullException>(authorization != null); - Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier)); + Requires.NotNull(authorization, "authorization"); + Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier)); if (authorization.Callback == null) { authorization.Callback = new Uri("http://localhost/"); @@ -93,7 +93,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorizationState">The authorization.</param> /// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns> public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) { - Contract.Requires<ArgumentNullException>(actualRedirectUrl != null); + Requires.NotNull(actualRedirectUrl, "actualRedirectUrl"); if (authorizationState == null) { authorizationState = new AuthorizationState(); diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs index a6fae13..fc14bcf 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs @@ -66,9 +66,9 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="state">The state of the client that should be sent back with the authorization response.</param> /// <returns>The authorization request.</returns> public OutgoingWebResponse PrepareRequestUserAuthorization(IAuthorizationState authorization, string state = null) { - Contract.Requires<ArgumentNullException>(authorization != null); - Contract.Requires<InvalidOperationException>(authorization.Callback != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired); - Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier)); + Requires.NotNull(authorization, "authorization"); + Requires.ValidState(authorization.Callback != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired); + Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier)); Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); if (authorization.Callback == null) { @@ -94,8 +94,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="request">The incoming HTTP request that may carry an authorization response.</param> /// <returns>The authorization state that contains the details of the authorization.</returns> public IAuthorizationState ProcessUserAuthorization(HttpRequestInfo request = null) { - Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier)); - Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientSecret)); + Requires.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier)); + Requires.ValidState(!string.IsNullOrEmpty(this.ClientSecret)); if (request == null) { request = this.Channel.GetRequestFromContext(); diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs index a5baef0..927a6ed 100644 --- a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs +++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="accessTokenAnalyzer">The access token analyzer.</param> public ResourceServer(IAccessTokenAnalyzer accessTokenAnalyzer) { - Contract.Requires<ArgumentNullException>(accessTokenAnalyzer != null); + Requires.NotNull(accessTokenAnalyzer, "accessTokenAnalyzer"); this.AccessTokenAnalyzer = accessTokenAnalyzer; this.Channel = new OAuth2ResourceServerChannel(); @@ -71,7 +71,7 @@ namespace DotNetOpenAuth.OAuth2 { [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")] public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string userName, out HashSet<string> scope) { - Contract.Requires<ArgumentNullException>(httpRequestInfo != null); + Requires.NotNull(httpRequestInfo, "httpRequestInfo"); AccessProtectedResourceRequest request = null; try { @@ -127,8 +127,8 @@ namespace DotNetOpenAuth.OAuth2 { [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")] [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")] public virtual OutgoingWebResponse VerifyAccess(HttpRequestMessageProperty request, Uri requestUri, out IPrincipal principal) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentNullException>(requestUri != null); + Requires.NotNull(request, "request"); + Requires.NotNull(requestUri, "requestUri"); return this.VerifyAccess(new HttpRequestInfo(request, requestUri), out principal); } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs index 6278828..a502962 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AccessToken.cs @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <param name="authorization">The authorization to be described by the access token.</param> /// <param name="lifetime">The lifetime of the access token.</param> internal AccessToken(IAuthorizationDescription authorization, TimeSpan? lifetime) { - Contract.Requires<ArgumentNullException>(authorization != null); + Requires.NotNull(authorization, "authorization"); this.ClientIdentifier = authorization.ClientIdentifier; this.UtcCreationDate = authorization.UtcIssued; @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <param name="username">The username of the account that authorized this token.</param> /// <param name="lifetime">The lifetime for this access token.</param> internal AccessToken(string clientIdentifier, IEnumerable<string> scopes, string username, TimeSpan? lifetime) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier)); + Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier"); this.ClientIdentifier = clientIdentifier; this.Scope.ResetContents(scopes); diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs index 03732bb..6900b89 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/AuthorizationCode.cs @@ -36,8 +36,8 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <param name="scopes">The authorized scopes.</param> /// <param name="username">The name on the account that authorized access.</param> internal AuthorizationCode(string clientIdentifier, Uri callback, IEnumerable<string> scopes, string username) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier)); - Contract.Requires<ArgumentNullException>(callback != null); + Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier"); + Requires.NotNull(callback, "callback"); this.ClientIdentifier = clientIdentifier; this.CallbackHash = CalculateCallbackHash(callback); @@ -58,7 +58,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <param name="authorizationServer">The authorization server that will be serializing/deserializing this authorization code. Must not be null.</param> /// <returns>A DataBag formatter.</returns> internal static IDataBagFormatter<AuthorizationCode> CreateFormatter(IAuthorizationServer authorizationServer) { - Contract.Requires<ArgumentNullException>(authorizationServer != null); + Requires.NotNull(authorizationServer, "authorizationServer"); Contract.Ensures(Contract.Result<IDataBagFormatter<AuthorizationCode>>() != null); return new UriStyleMessageFormatter<AuthorizationCode>( diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs index 888830e..0c31023 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs @@ -22,7 +22,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <param name="authorizationServer">The authorization server.</param> protected internal OAuth2AuthorizationServerChannel(IAuthorizationServer authorizationServer) : base(InitializeBindingElements(authorizationServer)) { - Contract.Requires<ArgumentNullException>(authorizationServer != null); + Requires.NotNull(authorizationServer, "authorizationServer"); this.AuthorizationServer = authorizationServer; } @@ -94,7 +94,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// An array of binding elements used to initialize the channel. /// </returns> private static IChannelBindingElement[] InitializeBindingElements(IAuthorizationServer authorizationServer) { - Contract.Requires<ArgumentNullException>(authorizationServer != null); + Requires.NotNull(authorizationServer, "authorizationServer"); var bindingElements = new List<IChannelBindingElement>(); bindingElements.Add(new AuthServerAllFlowsBindingElement()); diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs index 9fe54c5..ee41957 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/ChannelElements/RefreshToken.cs @@ -31,7 +31,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// </summary> /// <param name="authorization">The authorization this refresh token should describe.</param> internal RefreshToken(IAuthorizationDescription authorization) { - Contract.Requires<ArgumentNullException>(authorization != null); + Requires.NotNull(authorization, "authorization"); this.ClientIdentifier = authorization.ClientIdentifier; this.UtcCreationDate = authorization.UtcIssued; @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// A DataBag formatter. Never null. /// </returns> internal static IDataBagFormatter<RefreshToken> CreateFormatter(ICryptoKeyStore cryptoKeyStore) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); Contract.Ensures(Contract.Result<IDataBagFormatter<RefreshToken>>() != null); return new UriStyleMessageFormatter<RefreshToken>(cryptoKeyStore, RefreshTokenKeyBucket, signed: true, encrypted: true); diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs index 74b8ebb..0897090 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAccessTokenAnalyzer.cs @@ -54,8 +54,8 @@ namespace DotNetOpenAuth.OAuth2 { /// A value indicating whether this access token is valid. /// </returns> bool IAccessTokenAnalyzer.TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) { - Contract.Requires<ArgumentNullException>(message != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken)); + Requires.NotNull(message, "message"); + Requires.NotNullOrEmpty(accessToken, "accessToken"); Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<string>(out user) != null)); throw new NotImplementedException(); diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs index 883f40c..6457f36 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IAuthorizationServer.cs @@ -175,7 +175,7 @@ namespace DotNetOpenAuth.OAuth2 { /// the resources to which access is being granted are sensitive. /// </returns> TimeSpan IAuthorizationServer.GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage) { - Contract.Requires<ArgumentNullException>(accessTokenRequestMessage != null); + Requires.NotNull(accessTokenRequestMessage, "accessTokenRequestMessage"); throw new NotImplementedException(); } @@ -191,7 +191,7 @@ namespace DotNetOpenAuth.OAuth2 { /// The caller is responsible to dispose of this value. /// </returns> RSACryptoServiceProvider IAuthorizationServer.GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage) { - Contract.Requires<ArgumentNullException>(accessTokenRequestMessage != null); + Requires.NotNull(accessTokenRequestMessage, "accessTokenRequestMessage"); Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null); throw new NotImplementedException(); } @@ -203,7 +203,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <returns>The client registration. Never null.</returns> /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception> IConsumerDescription IAuthorizationServer.GetClient(string clientIdentifier) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier)); + Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier"); Contract.Ensures(Contract.Result<IConsumerDescription>() != null); throw new NotImplementedException(); } @@ -231,7 +231,7 @@ namespace DotNetOpenAuth.OAuth2 { /// account or piece of hardware in which the tokens were stored. </para> /// </remarks> bool IAuthorizationServer.IsAuthorizationValid(IAuthorizationDescription authorization) { - Contract.Requires<ArgumentNullException>(authorization != null); + Requires.NotNull(authorization, "authorization"); throw new NotImplementedException(); } } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs index 97294e6..4529cef 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IClientAuthorizationTracker.cs @@ -44,7 +44,7 @@ namespace DotNetOpenAuth.OAuth2 { /// The authorization state; may be <c>null</c> if no authorization state matches. /// </returns> IAuthorizationState IClientAuthorizationTracker.GetAuthorizationState(Uri callbackUrl, string clientState) { - Contract.Requires<ArgumentNullException>(callbackUrl != null); + Requires.NotNull(callbackUrl, "callbackUrl"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs index 14f3523..cf07dc6 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/IConsumerDescription.cs @@ -91,8 +91,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <c>true</c> if the callback is allowed; otherwise, <c>false</c>. /// </returns> bool IConsumerDescription.IsCallbackAllowed(Uri callback) { - Contract.Requires<ArgumentNullException>(callback != null); - Contract.Requires<ArgumentException>(callback.IsAbsoluteUri); + Requires.NotNull(callback, "callback"); + Requires.True(callback.IsAbsoluteUri, "callback"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs index 22dad1d..f3dad87 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs @@ -34,7 +34,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="authorizationServer">The authorization server.</param> internal AccessTokenAuthorizationCodeRequest(AuthorizationServerDescription authorizationServer) : this(authorizationServer.TokenEndpoint, authorizationServer.Version) { - Contract.Requires<ArgumentNullException>(authorizationServer != null); + Requires.NotNull(authorizationServer, "authorizationServer"); } /// <summary> diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs index 5497e1b..ecf3254 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs @@ -24,8 +24,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="version">The protocol version.</param> internal EndUserAuthorizationFailedResponse(Uri clientCallback, Version version) : base(version, MessageTransport.Indirect, clientCallback) { - Contract.Requires<ArgumentNullException>(version != null); - Contract.Requires<ArgumentNullException>(clientCallback != null); + Requires.NotNull(version, "version"); + Requires.NotNull(clientCallback, "clientCallback"); } /// <summary> @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="request">The authorization request from the user agent on behalf of the client.</param> internal EndUserAuthorizationFailedResponse(Uri clientCallback, EndUserAuthorizationRequest request) : base(((IProtocolMessage)request).Version, MessageTransport.Indirect, clientCallback) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); ((IMessageWithClientState)this).ClientState = request.ClientState; } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs index 1cb2bab..2455406 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationRequest.cs @@ -27,8 +27,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="version">The protocol version.</param> internal EndUserAuthorizationRequest(Uri authorizationEndpoint, Version version) : base(version, MessageTransport.Indirect, authorizationEndpoint) { - Contract.Requires<ArgumentNullException>(authorizationEndpoint != null); - Contract.Requires<ArgumentNullException>(version != null); + Requires.NotNull(authorizationEndpoint, "authorizationEndpoint"); + Requires.NotNull(version, "version"); this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest; this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); this.ResponseType = EndUserAuthorizationResponseType.AuthorizationCode; @@ -40,9 +40,9 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="authorizationServer">The authorization server.</param> internal EndUserAuthorizationRequest(AuthorizationServerDescription authorizationServer) : this(authorizationServer.AuthorizationEndpoint, authorizationServer.Version) { - Contract.Requires<ArgumentNullException>(authorizationServer != null); - Contract.Requires<ArgumentException>(authorizationServer.Version != null); - Contract.Requires<ArgumentException>(authorizationServer.AuthorizationEndpoint != null); + Requires.NotNull(authorizationServer, "authorizationServer"); + Requires.True(authorizationServer.Version != null, "authorizationServer"); + Requires.True(authorizationServer.AuthorizationEndpoint != null, "authorizationServer"); } /// <summary> diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs index c9373eb..b82b1da 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs @@ -27,8 +27,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="version">The protocol version.</param> internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, Version version) : base(clientCallback, version) { - Contract.Requires<ArgumentNullException>(version != null); - Contract.Requires<ArgumentNullException>(clientCallback != null); + Requires.NotNull(version, "version"); + Requires.NotNull(clientCallback, "clientCallback"); this.TokenType = Protocol.AccessTokenTypes.Bearer; } @@ -39,8 +39,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="request">The authorization request from the user agent on behalf of the client.</param> internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, EndUserAuthorizationRequest request) : base(clientCallback, request) { - Contract.Requires<ArgumentNullException>(clientCallback != null); - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(clientCallback, "clientCallback"); + Requires.NotNull(request, "request"); ((IMessageWithClientState)this).ClientState = request.ClientState; this.TokenType = Protocol.AccessTokenTypes.Bearer; } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs index 65965ef..ac7f392 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs @@ -24,8 +24,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="version">The protocol version.</param> internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, Version version) : base(clientCallback, version) { - Contract.Requires<ArgumentNullException>(version != null); - Contract.Requires<ArgumentNullException>(clientCallback != null); + Requires.NotNull(version, "version"); + Requires.NotNull(clientCallback, "clientCallback"); } /// <summary> @@ -35,8 +35,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="request">The authorization request from the user agent on behalf of the client.</param> internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, EndUserAuthorizationRequest request) : base(clientCallback, request) { - Contract.Requires<ArgumentNullException>(clientCallback != null); - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(clientCallback, "clientCallback"); + Requires.NotNull(request, "request"); ((IMessageWithClientState)this).ClientState = request.ClientState; } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs index d3c32e8..ff52743 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs @@ -26,8 +26,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="version">The protocol version.</param> internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, Version version) : base(version, MessageTransport.Indirect, clientCallback) { - Contract.Requires<ArgumentNullException>(version != null); - Contract.Requires<ArgumentNullException>(clientCallback != null); + Requires.NotNull(version, "version"); + Requires.NotNull(clientCallback, "clientCallback"); this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); } @@ -38,8 +38,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="request">The authorization request from the user agent on behalf of the client.</param> internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, EndUserAuthorizationRequest request) : base(request, clientCallback) { - Contract.Requires<ArgumentNullException>(clientCallback != null); - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(clientCallback, "clientCallback"); + Requires.NotNull(request, "request"); ((IMessageWithClientState)this).ClientState = request.ClientState; this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer); this.Scope.ResetContents(request.Scope); diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs index e390d6e..c5e438f 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/MessageBase.cs @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// </summary> /// <param name="version">The version.</param> protected MessageBase(Version version) { - Contract.Requires<ArgumentNullException>(version != null); + Requires.NotNull(version, "version"); this.messageTransport = MessageTransport.Direct; this.version = version; this.HttpMethods = HttpDeliveryMethods.GetRequest; @@ -54,7 +54,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="request">The originating request.</param> /// <param name="recipient">The recipient of the directed message. Null if not applicable.</param> protected MessageBase(IDirectedProtocolMessage request, Uri recipient = null) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); this.originatingRequest = request; this.messageTransport = request.Transport; this.version = request.Version; @@ -70,8 +70,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="messageTransport">The message transport.</param> /// <param name="recipient">The recipient.</param> protected MessageBase(Version version, MessageTransport messageTransport, Uri recipient) { - Contract.Requires<ArgumentNullException>(version != null); - Contract.Requires<ArgumentNullException>(recipient != null); + Requires.NotNull(version, "version"); + Requires.NotNull(recipient, "recipient"); this.version = version; this.messageTransport = messageTransport; diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs index d79c00b..529fab2 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Messages/UnauthorizedResponse.cs @@ -23,7 +23,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="version">The protocol version.</param> internal UnauthorizedResponse(ProtocolException exception, Version version = null) : base(version ?? Protocol.Default.Version) { - Contract.Requires<ArgumentNullException>(exception != null); + Requires.NotNull(exception, "exception"); this.ErrorMessage = exception.Message; } @@ -43,7 +43,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <param name="exception">The exception.</param> internal UnauthorizedResponse(IDirectedProtocolMessage request, ProtocolException exception) : this(request) { - Contract.Requires<ArgumentNullException>(exception != null); + Requires.NotNull(exception, "exception"); this.ErrorMessage = exception.Message; } diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs index c2b2f5f..1ae3701 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs @@ -81,7 +81,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="scopes">The scopes to serialize.</param> /// <returns>A space-delimited list.</returns> public static string JoinScopes(HashSet<string> scopes) { - Contract.Requires<ArgumentNullException>(scopes != null); + Requires.NotNull(scopes, "scopes"); return string.Join(" ", scopes.ToArray()); } @@ -91,8 +91,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="request">The request to authorize.</param> /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param> internal static void AuthorizeWithBearerToken(this HttpWebRequest request, string accessToken) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken)); + Requires.NotNull(request, "request"); + Requires.NotNullOrEmpty(accessToken, "accessToken"); ErrorUtilities.VerifyProtocol(accessToken.All(ch => accessTokenAuthorizationHeaderAllowedCharacters.IndexOf(ch) >= 0), "The access token contains characters that must not appear in the HTTP Authorization header."); request.Headers[HttpRequestHeader.Authorization] = string.Format( @@ -108,7 +108,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="clientIdentifier">The client identifier.</param> /// <returns>The client information. Never null.</returns> internal static IConsumerDescription GetClientOrThrow(this IAuthorizationServer authorizationServer, string clientIdentifier) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier)); + Requires.NotNullOrEmpty(clientIdentifier, "clientIdentifier"); Contract.Ensures(Contract.Result<IConsumerDescription>() != null); try { diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs index 1f59e52..f2b7d1c 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/StandardAccessTokenAnalyzer.cs @@ -22,9 +22,9 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorizationServerPublicSigningKey">The crypto service provider with the authorization server public signing key.</param> /// <param name="resourceServerPrivateEncryptionKey">The crypto service provider with the resource server private encryption key.</param> public StandardAccessTokenAnalyzer(RSACryptoServiceProvider authorizationServerPublicSigningKey, RSACryptoServiceProvider resourceServerPrivateEncryptionKey) { - Contract.Requires<ArgumentNullException>(authorizationServerPublicSigningKey != null); - Contract.Requires<ArgumentNullException>(resourceServerPrivateEncryptionKey != null); - Contract.Requires<ArgumentException>(!resourceServerPrivateEncryptionKey.PublicOnly); + Requires.NotNull(authorizationServerPublicSigningKey, "authorizationServerPublicSigningKey"); + Requires.NotNull(resourceServerPrivateEncryptionKey, "resourceServerPrivateEncryptionKey"); + Requires.True(!resourceServerPrivateEncryptionKey.PublicOnly, "resourceServerPrivateEncryptionKey"); this.AuthorizationServerPublicSigningKey = authorizationServerPublicSigningKey; this.ResourceServerPrivateEncryptionKey = resourceServerPrivateEncryptionKey; } diff --git a/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AnonymousRequestEventArgs.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AnonymousRequestEventArgs.cs index 9ffaa55..2cf680d 100644 --- a/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AnonymousRequestEventArgs.cs +++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/AnonymousRequestEventArgs.cs @@ -18,7 +18,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </summary> /// <param name="request">The incoming OpenID request.</param> internal AnonymousRequestEventArgs(IAnonymousRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); this.Request = request; } diff --git a/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs index 90dedc2..7b33695 100644 --- a/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs +++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs @@ -82,7 +82,7 @@ namespace DotNetOpenAuth.OpenId.Provider { } set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); provider = value; } } @@ -98,15 +98,15 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </remarks> public static IAuthenticationRequest PendingAuthenticationRequest { get { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); Contract.Ensures(Contract.Result<IAuthenticationRequest>() == null || PendingRequest != null); return HttpContext.Current.Session[PendingRequestKey] as IAuthenticationRequest; } set { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); HttpContext.Current.Session[PendingRequestKey] = value; } } @@ -122,15 +122,15 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </remarks> public static IAnonymousRequest PendingAnonymousRequest { get { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); Contract.Ensures(Contract.Result<IAnonymousRequest>() == null || PendingRequest != null); return HttpContext.Current.Session[PendingRequestKey] as IAnonymousRequest; } set { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); HttpContext.Current.Session[PendingRequestKey] = value; } } @@ -146,14 +146,14 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </remarks> public static IHostProcessedRequest PendingRequest { get { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); return HttpContext.Current.Session[PendingRequestKey] as IHostProcessedRequest; } set { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Contract.Requires<InvalidOperationException>(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current.Session != null, MessagingStrings.SessionRequired); HttpContext.Current.Session[PendingRequestKey] = value; } } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs index 883df2c..a651fe5 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/AssociateUnencryptedProviderRequest.cs @@ -9,8 +9,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Text; - using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId.Messages; internal class AssociateUnencryptedProviderRequest : AssociateUnencryptedRequest, IAssociateRequestProvider { /// <summary> diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs index ab3b993..5812a96 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs @@ -27,8 +27,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="securitySettings">The security settings.</param> internal OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings) : this(cryptoKeyStore, nonceStore, new OpenIdProviderMessageFactory(), securitySettings) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); + Requires.NotNull(securitySettings, "securitySettings"); } /// <summary> @@ -40,9 +40,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="securitySettings">The security settings.</param> private OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, ProviderSecuritySettings securitySettings) : base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings)) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); - Contract.Requires<ArgumentNullException>(messageTypeProvider != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); + Requires.NotNull(messageTypeProvider, "messageTypeProvider"); + Requires.NotNull(securitySettings, "securitySettings"); } /// <summary> @@ -55,9 +55,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// An array of binding elements which may be used to construct the channel. /// </returns> private static IChannelBindingElement[] InitializeBindingElements(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); - Contract.Requires<ArgumentNullException>(nonceStore != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); + Requires.NotNull(securitySettings, "securitySettings"); + Requires.NotNull(nonceStore, "nonceStore"); SigningBindingElement signingElement; signingElement = new ProviderSigningBindingElement(cryptoKeyStore, securitySettings); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs index 65d0398..e257e63 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs @@ -38,8 +38,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="associationStore">The association store used to look up the secrets needed for signing.</param> /// <param name="securitySettings">The security settings.</param> internal ProviderSigningBindingElement(IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(associationStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(associationStore, "associationStore"); + Requires.NotNull(securitySettings, "securitySettings"); this.opAssociations = associationStore; this.opSecuritySettings = securitySettings; @@ -177,7 +177,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <c>true</c> if the relying party is vulnerable; otherwise, <c>false</c>. /// </returns> private static bool IsRelyingPartyVulnerableToReplays(SignedResponseRequest request, IndirectSignedResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); // OpenID 2.0 includes replay protection as part of the protocol. if (response.Version.Major >= 2) { @@ -217,8 +217,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// the inclusion and order of message parts that will be signed. /// </returns> private string GetSignedParameterOrder(ITamperResistantOpenIdMessage signedMessage) { - Contract.Requires<InvalidOperationException>(this.Channel != null); - Contract.Requires<ArgumentNullException>(signedMessage != null); + Requires.ValidState(this.Channel != null); + Requires.NotNull(signedMessage, "signedMessage"); Protocol protocol = Protocol.Lookup(signedMessage.Version); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Extensions/ExtensionsInteropProviderHelper.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Extensions/ExtensionsInteropProviderHelper.cs index c70bdd4..0174d3f 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Extensions/ExtensionsInteropProviderHelper.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Extensions/ExtensionsInteropProviderHelper.cs @@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// or a fabricated one based on the Attribute Exchange extension if found, /// or <c>null</c> if no attribute extension request is found.</returns> internal static ClaimsRequest UnifyExtensionsAsSreg(this Provider.IHostProcessedRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); var req = (Provider.HostProcessedRequest)request; var sreg = req.GetExtension<ClaimsRequest>(); @@ -145,8 +145,8 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="typeUri">The type URI of the attribute in axschema.org format.</param> /// <returns>The demand level for the attribute.</returns> private static DemandLevel GetDemandLevelFor(FetchRequest ax, string typeUri) { - Contract.Requires<ArgumentNullException>(ax != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNull(ax, "ax"); + Requires.NotNullOrEmpty(typeUri, "typeUri"); foreach (AXAttributeFormats format in ExtensionsInteropHelper.ForEachFormat(AXAttributeFormats.All)) { string typeUriInFormat = ExtensionsInteropHelper.TransformAXFormat(typeUri, format); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/HmacShaAssociationProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/HmacShaAssociationProvider.cs index 7aff483..e31c5a4 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/HmacShaAssociationProvider.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/HmacShaAssociationProvider.cs @@ -39,10 +39,10 @@ namespace DotNetOpenAuth.OpenId { /// The new association is NOT automatically put into an association store. This must be done by the caller. /// </remarks> internal static HmacShaAssociation Create(Protocol protocol, string associationType, AssociationRelyingPartyType associationUse, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(protocol != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType)); - Contract.Requires<ArgumentNullException>(associationStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(protocol, "protocol"); + Requires.NotNullOrEmpty(associationType, "associationType"); + Requires.NotNull(associationStore, "associationStore"); + Requires.NotNull(securitySettings, "securitySettings"); Contract.Ensures(Contract.Result<HmacShaAssociation>() != null); int secretLength = HmacShaAssociation.GetSecretLength(protocol, associationType); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs index 7537ab6..9a6cdee 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateRequestProviderTools.cs @@ -7,9 +7,9 @@ namespace DotNetOpenAuth.OpenId.Messages { using System; using System.Collections.Generic; + using System.Diagnostics.Contracts; using System.Linq; using System.Text; - using System.Diagnostics.Contracts; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Provider; @@ -29,9 +29,9 @@ namespace DotNetOpenAuth.OpenId.Messages { /// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para> /// </remarks> internal static IProtocolMessage CreateResponse(IAssociateRequestProvider requestMessage, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(requestMessage != null, "requestMessage"); - Contract.Requires<ArgumentNullException>(associationStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(requestMessage, "requestMessage"); + Requires.NotNull(associationStore, "associationStore"); + Requires.NotNull(securitySettings, "securitySettings"); AssociateRequest request = (AssociateRequest)requestMessage; IProtocolMessage response; @@ -60,8 +60,8 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="securitySettings">The security settings that apply to this Provider.</param> /// <returns>The response to send to the Relying Party.</returns> private static AssociateUnsuccessfulResponse CreateUnsuccessfulResponse(IAssociateRequestProvider requestMessage, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(requestMessage != null, "requestMessage"); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(requestMessage, "requestMessage"); + Requires.NotNull(securitySettings, "securitySettings"); var unsuccessfulResponse = new AssociateUnsuccessfulResponse(requestMessage.Version, (AssociateRequest)requestMessage); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs index 3db33c9..4ac2021 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProvider.cs @@ -10,8 +10,8 @@ namespace DotNetOpenAuth.OpenId.Messages { using System.Diagnostics.Contracts; using System.Linq; using System.Text; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Provider; -using DotNetOpenAuth.Messaging; /// <summary> /// An outgoing successful association response from the OpenID Provider. diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs index 0b34e1f..fd8ce67 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/AssociateSuccessfulResponseProviderContract.cs @@ -27,9 +27,9 @@ namespace DotNetOpenAuth.OpenId.Messages { /// The created association. /// </returns> Association IAssociateSuccessfulResponseProvider.CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentNullException>(associationStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(request, "request"); + Requires.NotNull(associationStore, "associationStore"); + Requires.NotNull(securitySettings, "securitySettings"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs index 8f9a240..1e417e6 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Messages/CheckAuthenticationResponseProvider.cs @@ -24,7 +24,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="provider">The OpenID Provider that is preparing to send this response.</param> internal CheckAuthenticationResponseProvider(CheckAuthenticationRequest request, OpenIdProvider provider) : base(request.Version, request) { - Contract.Requires<ArgumentNullException>(provider != null); + Requires.NotNull(provider, "provider"); // The channel's binding elements have already set the request's IsValid property // appropriately. We just copy it into the response message. diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/OpenIdProviderUtilities.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/OpenIdProviderUtilities.cs index 5468ab2..f09d0e9 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/OpenIdProviderUtilities.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/OpenIdProviderUtilities.cs @@ -34,9 +34,9 @@ namespace DotNetOpenAuth.OpenId { /// quite different operations in either scenario. /// </remarks> internal static Association CreateAssociation(AssociateRequest request, IAssociateSuccessfulResponseProvider response, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentNullException>(response != null, "response"); - Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings"); + Requires.NotNull(request, "request"); + Requires.NotNull(response, "response"); + Requires.NotNull(securitySettings, "securitySettings"); // We need to initialize some common properties based on the created association. var association = response.CreateAssociationAtProvider(request, associationStore, securitySettings); @@ -57,9 +57,9 @@ namespace DotNetOpenAuth.OpenId { /// <c>true</c> if the specified containing message is valid; otherwise, <c>false</c>. /// </returns> internal static bool IsValid(this IProviderAssociationStore associationStore, IProtocolMessage containingMessage, bool isPrivateAssociation, string handle) { - Contract.Requires<ArgumentNullException>(associationStore != null); - Contract.Requires<ArgumentNullException>(containingMessage != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle)); + Requires.NotNull(associationStore, "associationStore"); + Requires.NotNull(containingMessage, "containingMessage"); + Requires.NotNullOrEmpty(handle, "handle"); try { return associationStore.Deserialize(containingMessage, isPrivateAssociation, handle) != null; } catch (ProtocolException) { diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs index 974d729..581d39e 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs @@ -30,8 +30,8 @@ namespace DotNetOpenAuth.OpenId.Provider { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "AuthenticationRequest", Justification = "Type name"), SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code contracts require it.")] internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request) : base(provider, request) { - Contract.Requires<ArgumentNullException>(provider != null); - Contract.Requires<ArgumentException>(!(request is CheckIdRequest)); + Requires.NotNull(provider, "provider"); + Requires.True(!(request is CheckIdRequest), "request"); this.positiveResponse = new IndirectSignedResponse(request); } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs index a8ac41e..bf3d909 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AssociationDataBag.cs @@ -86,8 +86,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// A formatter for serialization. /// </returns> internal static IDataBagFormatter<AssociationDataBag> CreateFormatter(ICryptoKeyStore cryptoKeyStore, string bucket, TimeSpan? minimumAge = null) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket)); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); + Requires.NotNullOrEmpty(bucket, "bucket"); Contract.Ensures(Contract.Result<IDataBagFormatter<AssociationDataBag>>() != null); return new BinaryDataBagFormatter<AssociationDataBag>(cryptoKeyStore, bucket, signed: true, encrypted: true, minimumAge: minimumAge); } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs index d22f858..09b1073 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="request">The incoming authentication request message.</param> internal AuthenticationRequest(OpenIdProvider provider, CheckIdRequest request) : base(provider, request) { - Contract.Requires<ArgumentNullException>(provider != null); + Requires.NotNull(provider, "provider"); this.positiveResponse = new PositiveAssertionResponse(request); @@ -216,7 +216,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </summary> /// <param name="identifier">The value to set to the <see cref="ClaimedIdentifier"/> and <see cref="LocalIdentifier"/> properties.</param> internal void ResetClaimedAndLocalIdentifiers(Identifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); this.positiveResponse.ClaimedIdentifier = identifier; this.positiveResponse.LocalIdentifier = identifier; diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs index 41e082b..0d98e67 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs @@ -32,7 +32,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="securitySettings">The security settings.</param> internal AutoResponsiveRequest(IDirectedProtocolMessage request, IProtocolMessage response, ProviderSecuritySettings securitySettings) : base(request, securitySettings) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); this.response = response; } @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="securitySettings">The security settings.</param> internal AutoResponsiveRequest(IProtocolMessage response, ProviderSecuritySettings securitySettings) : base(IndirectResponseBase.GetVersion(response), securitySettings) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); this.response = response; } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs index 2fdcebb..3647a63 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs @@ -36,7 +36,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="request">The incoming request message.</param> protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request) : base(request, provider.SecuritySettings) { - Contract.Requires<ArgumentNullException>(provider != null); + Requires.NotNull(provider, "provider"); this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel); Reporting.RecordEventOccurrence(this, request.Realm); @@ -132,7 +132,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Result of realm discovery. /// </returns> private RelyingPartyDiscoveryResult IsReturnUrlDiscoverableCore(IDirectWebRequestHandler requestHandler) { - Contract.Requires<ArgumentNullException>(requestHandler != null); + Requires.NotNull(requestHandler, "requestHandler"); ErrorUtilities.VerifyInternal(this.Realm != null, "Realm should have been read or derived by now."); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs index 985bb54..9197761 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IDirectedIdentityIdentifierProvider.cs @@ -59,9 +59,9 @@ namespace DotNetOpenAuth.OpenId.Provider { /// openid.claimed_id and openid.local_id parameters. Must not be null. /// </returns> Uri IDirectedIdentityIdentifierProvider.GetIdentifier(Identifier localIdentifier, Realm relyingPartyRealm) { - Contract.Requires<ArgumentNullException>(localIdentifier != null); - Contract.Requires<ArgumentNullException>(relyingPartyRealm != null); - Contract.Requires<ArgumentException>(((IDirectedIdentityIdentifierProvider)this).IsUserLocalIdentifier(localIdentifier), OpenIdStrings.ArgumentIsPpidIdentifier); + Requires.NotNull(localIdentifier, "localIdentifier"); + Requires.NotNull(relyingPartyRealm, "relyingPartyRealm"); + Requires.True(((IDirectedIdentityIdentifierProvider)this).IsUserLocalIdentifier(localIdentifier), "localIdentifier", OpenIdStrings.ArgumentIsPpidIdentifier); throw new NotImplementedException(); } @@ -73,7 +73,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <c>true</c> if the given identifier is the valid, unique identifier for some uesr (and NOT a PPID); otherwise, <c>false</c>. /// </returns> bool IDirectedIdentityIdentifierProvider.IsUserLocalIdentifier(Identifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs index 5a554c1..6c749f6 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/IProviderAssociationStore.cs @@ -65,8 +65,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// The association handle that represents this association. /// </returns> string IProviderAssociationStore.Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) { - Contract.Requires<ArgumentNullException>(secret != null); - Contract.Requires<ArgumentException>(expiresUtc.Kind == DateTimeKind.Utc); + Requires.NotNull(secret, "secret"); + Requires.True(expiresUtc.Kind == DateTimeKind.Utc, "expiresUtc"); Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>())); throw new NotImplementedException(); } @@ -82,8 +82,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </returns> /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception> Association IProviderAssociationStore.Deserialize(IProtocolMessage containingMessage, bool privateAssociation, string handle) { - Contract.Requires<ArgumentNullException>(containingMessage != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle)); + Requires.NotNull(containingMessage, "containingMessage"); + Requires.NotNullOrEmpty(handle, "handle"); throw new NotImplementedException(); } } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs index e794433..b3cb4a4 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs @@ -65,7 +65,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="applicationStore">The application store to use. Cannot be null.</param> public OpenIdProvider(IOpenIdApplicationStore applicationStore) : this((INonceStore)applicationStore, (ICryptoKeyStore)applicationStore) { - Contract.Requires<ArgumentNullException>(applicationStore != null); + Requires.NotNull(applicationStore, "applicationStore"); Contract.Ensures(this.SecuritySettings != null); Contract.Ensures(this.Channel != null); } @@ -76,8 +76,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="nonceStore">The nonce store to use. Cannot be null.</param> /// <param name="cryptoKeyStore">The crypto key store. Cannot be null.</param> private OpenIdProvider(INonceStore nonceStore, ICryptoKeyStore cryptoKeyStore) { - Contract.Requires<ArgumentNullException>(nonceStore != null); - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); + Requires.NotNull(nonceStore, "nonceStore"); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); Contract.Ensures(this.SecuritySettings != null); Contract.Ensures(this.Channel != null); @@ -101,7 +101,7 @@ namespace DotNetOpenAuth.OpenId.Provider { [EditorBrowsable(EditorBrowsableState.Advanced)] public static IOpenIdApplicationStore HttpApplicationStore { get { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); Contract.Ensures(Contract.Result<IOpenIdApplicationStore>() != null); HttpContext context = HttpContext.Current; var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]; @@ -136,7 +136,7 @@ namespace DotNetOpenAuth.OpenId.Provider { } internal set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); this.securitySettings = value; } } @@ -248,7 +248,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <exception cref="ProtocolException">Thrown if the incoming message is recognized /// but deviates from the protocol specification irrecoverably.</exception> public IRequest GetRequest(HttpRequestInfo httpRequestInfo) { - Contract.Requires<ArgumentNullException>(httpRequestInfo != null); + Requires.NotNull(httpRequestInfo, "httpRequestInfo"); IDirectedProtocolMessage incomingMessage = null; try { @@ -328,9 +328,9 @@ namespace DotNetOpenAuth.OpenId.Provider { [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")] [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use the Respond method instead, and prepare for execution to continue on this page beyond the call to Respond.")] public void SendResponse(IRequest request) { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentException>(request.IsResponseReady); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); + Requires.NotNull(request, "request"); + Requires.True(request.IsResponseReady, "request"); this.ApplyBehaviorsToResponse(request); Request requestInternal = (Request)request; @@ -349,9 +349,9 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception> [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")] public void Respond(IRequest request) { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentException>(request.IsResponseReady); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); + Requires.NotNull(request, "request"); + Requires.True(request.IsResponseReady, "request"); this.ApplyBehaviorsToResponse(request); Request requestInternal = (Request)request; @@ -366,8 +366,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception> [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")] public OutgoingWebResponse PrepareResponse(IRequest request) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentException>(request.IsResponseReady); + Requires.NotNull(request, "request"); + Requires.True(request.IsResponseReady, "request"); this.ApplyBehaviorsToResponse(request); Request requestInternal = (Request)request; @@ -390,12 +390,12 @@ namespace DotNetOpenAuth.OpenId.Provider { /// be the same as <paramref name="claimedIdentifier"/>.</param> /// <param name="extensions">The extensions.</param> public void SendUnsolicitedAssertion(Uri providerEndpoint, Realm relyingPartyRealm, Identifier claimedIdentifier, Identifier localIdentifier, params IExtensionMessage[] extensions) { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentException>(providerEndpoint.IsAbsoluteUri); - Contract.Requires<ArgumentNullException>(relyingPartyRealm != null); - Contract.Requires<ArgumentNullException>(claimedIdentifier != null); - Contract.Requires<ArgumentNullException>(localIdentifier != null); + Requires.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.True(providerEndpoint.IsAbsoluteUri, "providerEndpoint"); + Requires.NotNull(relyingPartyRealm, "relyingPartyRealm"); + Requires.NotNull(claimedIdentifier, "claimedIdentifier"); + Requires.NotNull(localIdentifier, "localIdentifier"); this.PrepareUnsolicitedAssertion(providerEndpoint, relyingPartyRealm, claimedIdentifier, localIdentifier, extensions).Respond(); } @@ -420,12 +420,12 @@ namespace DotNetOpenAuth.OpenId.Provider { /// the user agent to allow the redirect with assertion to happen. /// </returns> public OutgoingWebResponse PrepareUnsolicitedAssertion(Uri providerEndpoint, Realm relyingPartyRealm, Identifier claimedIdentifier, Identifier localIdentifier, params IExtensionMessage[] extensions) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentException>(providerEndpoint.IsAbsoluteUri); - Contract.Requires<ArgumentNullException>(relyingPartyRealm != null); - Contract.Requires<ArgumentNullException>(claimedIdentifier != null); - Contract.Requires<ArgumentNullException>(localIdentifier != null); - Contract.Requires<InvalidOperationException>(this.Channel.WebRequestHandler != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.True(providerEndpoint.IsAbsoluteUri, "providerEndpoint"); + Requires.NotNull(relyingPartyRealm, "relyingPartyRealm"); + Requires.NotNull(claimedIdentifier, "claimedIdentifier"); + Requires.NotNull(localIdentifier, "localIdentifier"); + Requires.ValidState(this.Channel.WebRequestHandler != null); // Although the RP should do their due diligence to make sure that this OP // is authorized to send an assertion for the given claimed identifier, @@ -529,8 +529,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Either the <see cref="IRequest"/> to return to the host site or null to indicate no response could be reasonably created and that the caller should rethrow the exception. /// </returns> private IRequest GetErrorResponse(ProtocolException ex, HttpRequestInfo httpRequestInfo, IDirectedProtocolMessage incomingMessage) { - Contract.Requires<ArgumentNullException>(ex != null); - Contract.Requires<ArgumentNullException>(httpRequestInfo != null); + Requires.NotNull(ex, "ex"); + Requires.NotNull(httpRequestInfo, "httpRequestInfo"); Logger.OpenId.Error("An exception was generated while processing an incoming OpenID request.", ex); IErrorMessage errorMessage; @@ -616,8 +616,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="cryptoKeyStore">The crypto key store.</param> /// <param name="securitySettings">The security settings.</param> internal SwitchingAssociationStore(ICryptoKeyStore cryptoKeyStore, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); + Requires.NotNull(securitySettings, "securitySettings"); this.securitySettings = securitySettings; this.associationHandleEncoder = new ProviderAssociationHandleEncoder(cryptoKeyStore); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs index 46e172c..9ebae1d 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/PrivatePersonalIdentifierProviderBase.cs @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </summary> /// <param name="baseIdentifier">The base URI on which to append the anonymous part.</param> protected PrivatePersonalIdentifierProviderBase(Uri baseIdentifier) { - Contract.Requires<ArgumentNullException>(baseIdentifier != null); + Requires.NotNull(baseIdentifier, "baseIdentifier"); this.Hasher = HashAlgorithm.Create(HashAlgorithmName); this.Encoder = Encoding.UTF8; @@ -102,7 +102,7 @@ namespace DotNetOpenAuth.OpenId.Provider { } set { - Contract.Requires<ArgumentOutOfRangeException>(value > 0); + Requires.InRange(value > 0, "value"); this.newSaltLength = value; } } @@ -157,8 +157,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <returns> /// <c>true</c> if the given identifier is the valid, unique identifier for some uesr (and NOT a PPID); otherwise, <c>false</c>. /// </returns> - public virtual bool IsUserLocalIdentifier(Identifier identifier) - { + public virtual bool IsUserLocalIdentifier(Identifier identifier) { return !identifier.ToString().StartsWith(this.BaseIdentifier.AbsoluteUri, StringComparison.Ordinal); } @@ -181,7 +180,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <returns>The full PPID Identifier.</returns> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "NOT equivalent overload. The recommended one breaks on relative URIs.")] protected virtual Uri AppendIdentifiers(string uriHash) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uriHash)); + Requires.NotNullOrEmpty(uriHash, "uriHash"); if (string.IsNullOrEmpty(this.BaseIdentifier.Query)) { // The uriHash will appear on the path itself. diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs index 5de560c..0e7c174 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationHandleEncoder.cs @@ -32,7 +32,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </summary> /// <param name="cryptoKeyStore">The crypto key store.</param> public ProviderAssociationHandleEncoder(ICryptoKeyStore cryptoKeyStore) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); this.cryptoKeyStore = cryptoKeyStore; } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs index 9801aac..179699a 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/ProviderAssociationKeyStorage.cs @@ -35,7 +35,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </summary> /// <param name="cryptoKeyStore">The store where association secrets will be recorded.</param> internal ProviderAssociationKeyStorage(ICryptoKeyStore cryptoKeyStore) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); this.cryptoKeyStore = cryptoKeyStore; } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs index 4e54ef9..c5b6dac 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs @@ -54,8 +54,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="request">The incoming request message.</param> /// <param name="securitySettings">The security settings from the channel.</param> protected Request(IDirectedProtocolMessage request, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(request, "request"); + Requires.NotNull(securitySettings, "securitySettings"); this.request = request; this.SecuritySettings = securitySettings; @@ -69,8 +69,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <param name="version">The version.</param> /// <param name="securitySettings">The security settings.</param> protected Request(Version version, ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(version != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(version, "version"); + Requires.NotNull(securitySettings, "securitySettings"); this.protocolVersion = version; this.SecuritySettings = securitySettings; @@ -99,7 +99,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <exception cref="InvalidOperationException">Thrown if <see cref="IsResponseReady"/> is <c>false</c>.</exception> internal IProtocolMessage Response { get { - Contract.Requires<InvalidOperationException>(this.IsResponseReady, OpenIdStrings.ResponseNotReady); + Requires.ValidState(this.IsResponseReady, OpenIdStrings.ResponseNotReady); Contract.Ensures(Contract.Result<IProtocolMessage>() != null); if (this.responseExtensions.Count > 0) { diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/RequestContract.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/RequestContract.cs index dee140e..ae7104c 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/RequestContract.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/RequestContract.cs @@ -39,7 +39,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </summary> protected override IProtocolMessage ResponseMessage { get { - Contract.Requires<InvalidOperationException>(this.IsResponseReady); + Requires.ValidState(this.IsResponseReady); Contract.Ensures(Contract.Result<IProtocolMessage>() != null); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdHelper.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdHelper.cs index b98e0d6..3325084 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdHelper.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/Mvc/OpenIdHelper.cs @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.Mvc { /// <param name="html">The <see cref="HtmlHelper"/> on the view.</param> /// <returns>HTML that should be sent directly to the browser.</returns> public static string OpenIdSelectorStyles(this HtmlHelper html) { - Contract.Requires<ArgumentNullException>(html != null); + Requires.NotNull(html, "html"); Contract.Ensures(Contract.Result<string>() != null); using (var result = new StringWriter(CultureInfo.CurrentCulture)) { @@ -63,7 +63,7 @@ namespace DotNetOpenAuth.Mvc { /// </returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "False positive")] public static string OpenIdSelectorScripts(this HtmlHelper html, OpenIdSelector selectorOptions, OpenIdAjaxOptions additionalOptions) { - Contract.Requires<ArgumentNullException>(html != null); + Requires.NotNull(html, "html"); Contract.Ensures(Contract.Result<string>() != null); bool selectorOptionsOwned = false; @@ -207,9 +207,9 @@ window.openid_trace = {1}; // causes lots of messages"; /// HTML that should be sent directly to the browser. /// </returns> public static string OpenIdSelectorOPButton(this HtmlHelper html, Identifier providerIdentifier, string imageUrl) { - Contract.Requires<ArgumentNullException>(html != null); - Contract.Requires<ArgumentNullException>(providerIdentifier != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl)); + Requires.NotNull(html, "html"); + Requires.NotNull(providerIdentifier, "providerIdentifier"); + Requires.NotNullOrEmpty(imageUrl, "imageUrl"); Contract.Ensures(Contract.Result<string>() != null); return OpenIdSelectorButton(html, providerIdentifier, "OPButton", imageUrl); @@ -225,8 +225,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// HTML that should be sent directly to the browser. /// </returns> public static string OpenIdSelectorOpenIdButton(this HtmlHelper html, string imageUrl) { - Contract.Requires<ArgumentNullException>(html != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl)); + Requires.NotNull(html, "html"); + Requires.NotNullOrEmpty(imageUrl, "imageUrl"); Contract.Ensures(Contract.Result<string>() != null); return OpenIdSelectorButton(html, "OpenIDButton", "OpenIDButton", imageUrl); @@ -242,8 +242,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// </returns> [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type.")] public static string OpenIdSelector(this HtmlHelper html, params SelectorButton[] buttons) { - Contract.Requires<ArgumentNullException>(html != null); - Contract.Requires<ArgumentNullException>(buttons != null); + Requires.NotNull(html, "html"); + Requires.NotNull(buttons, "buttons"); Contract.Ensures(Contract.Result<string>() != null); using (var writer = new StringWriter(CultureInfo.CurrentCulture)) { @@ -307,9 +307,9 @@ window.openid_trace = {1}; // causes lots of messages"; /// </returns> [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type.")] private static string OpenIdSelectorButton(this HtmlHelper html, string id, string cssClass, string imageUrl) { - Contract.Requires<ArgumentNullException>(html != null); - Contract.Requires<ArgumentNullException>(id != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl)); + Requires.NotNull(html, "html"); + Requires.NotNull(id, "id"); + Requires.NotNullOrEmpty(imageUrl, "imageUrl"); Contract.Ensures(Contract.Result<string>() != null); using (var writer = new StringWriter(CultureInfo.CurrentCulture)) { @@ -357,8 +357,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// <param name="writer">The writer to emit the tags to.</param> /// <param name="scriptUrls">The locations of the scripts to import.</param> private static void WriteScriptTagsUrls(this TextWriter writer, IEnumerable<string> scriptUrls) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentNullException>(scriptUrls != null); + Requires.NotNull(writer, "writer"); + Requires.NotNull(scriptUrls, "scriptUrls"); foreach (string script in scriptUrls) { writer.WriteLine("<script type='text/javascript' src='{0}'></script>", script); @@ -371,8 +371,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// <param name="writer">The writer to emit the tags to.</param> /// <param name="resourceName">Name of the resource.</param> private static void WriteScriptTags(this TextWriter writer, string resourceName) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(resourceName)); + Requires.NotNull(writer, "writer"); + Requires.NotNullOrEmpty(resourceName, "resourceName"); WriteScriptTags(writer, new[] { resourceName }); } @@ -383,8 +383,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// <param name="writer">The writer to emit the tags to.</param> /// <param name="resourceNames">The resource names.</param> private static void WriteScriptTags(this TextWriter writer, IEnumerable<string> resourceNames) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentNullException>(resourceNames != null); + Requires.NotNull(writer, "writer"); + Requires.NotNull(resourceNames, "resourceNames"); writer.WriteScriptTagsUrls(resourceNames.Select(r => Util.GetWebResourceUrl(typeof(OpenIdRelyingPartyControlBase), r))); } @@ -395,8 +395,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// <param name="writer">The writer to emit the tags to.</param> /// <param name="script">The script to inline on the page.</param> private static void WriteScriptBlock(this TextWriter writer, string script) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(script)); + Requires.NotNull(writer, "writer"); + Requires.NotNullOrEmpty(script, "script"); writer.WriteLine("<script type='text/javascript' language='javascript'><!--"); writer.WriteLine("//<![CDATA["); @@ -410,8 +410,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// <param name="writer">The writer to emit the tags to.</param> /// <param name="resourceName">Name of the resource containing the CSS content.</param> private static void WriteStylesheetLink(this TextWriter writer, string resourceName) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(resourceName)); + Requires.NotNull(writer, "writer"); + Requires.NotNullOrEmpty(resourceName, "resourceName"); WriteStylesheetLinkUrl(writer, Util.GetWebResourceUrl(typeof(OpenIdRelyingPartyAjaxControlBase), resourceName)); } @@ -422,8 +422,8 @@ window.openid_trace = {1}; // causes lots of messages"; /// <param name="writer">The writer to emit the tags to.</param> /// <param name="stylesheet">The stylesheet to link in.</param> private static void WriteStylesheetLinkUrl(this TextWriter writer, string stylesheet) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(stylesheet)); + Requires.NotNull(writer, "writer"); + Requires.NotNullOrEmpty(stylesheet, "stylesheet"); writer.WriteLine("<link rel='stylesheet' type='text/css' href='{0}' />", stylesheet); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs index 42bfbde..8e915cd 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs @@ -143,7 +143,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </code> /// </remarks> public OutgoingWebResponse AsAjaxDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { - Contract.Requires<ArgumentNullException>(requests != null); + Requires.NotNull(requests, "requests"); var serializer = new JavaScriptSerializer(); return new OutgoingWebResponse { @@ -160,7 +160,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// The JSON result to return to the user agent. /// </returns> public string AsAjaxPreloadedDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { - Contract.Requires<ArgumentNullException>(requests != null); + Requires.NotNull(requests, "requests"); var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(this.AsJsonPreloadedDiscoveryResult(requests)); @@ -175,7 +175,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="requests">The discovery results from just <i>one</i> identifier to serialize as a JSON response.</param> /// <returns>A JSON object, not yet serialized.</returns> internal object AsJsonDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { - Contract.Requires<ArgumentNullException>(requests != null); + Requires.NotNull(requests, "requests"); requests = requests.CacheGeneratedResults(); @@ -205,7 +205,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// A JSON object, not yet serialized to a string. /// </returns> private object AsJsonPreloadedDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { - Contract.Requires<ArgumentNullException>(requests != null); + Requires.NotNull(requests, "requests"); // We prepare a JSON object with this interface: // Array discoveryWrappers; @@ -233,7 +233,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <c>false</c> to create a checkid_setup request.</param> /// <returns>The absolute URL that carries the entire OpenID message.</returns> private Uri GetRedirectUrl(IAuthenticationRequest request, bool immediate) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); request.Mode = immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup; return request.RedirectingResponse.GetDirectUriRequest(this.Channel); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs index 8be097f..7fbc3ee 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs @@ -430,7 +430,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value)); + Requires.NotNullOrEmpty(value, "value"); this.ViewState[NameViewStateKey] = value ?? string.Empty; } } @@ -478,7 +478,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value)); + Requires.NotNullOrEmpty(value, "value"); this.ViewState[LogOnTextViewStateKey] = value ?? string.Empty; } } @@ -514,7 +514,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value)); + Requires.NotNullOrEmpty(value, "value"); this.ViewState[RetryTextViewStateKey] = value ?? string.Empty; } } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdEventArgs.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdEventArgs.cs index 5668cf4..cf38b61 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdEventArgs.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdEventArgs.cs @@ -22,7 +22,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="request">The outgoing authentication request.</param> internal OpenIdEventArgs(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); this.Request = request; this.ClaimedIdentifier = request.ClaimedIdentifier; @@ -36,7 +36,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The incoming authentication response.</param> internal OpenIdEventArgs(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); this.Response = response; this.ClaimedIdentifier = response.ClaimedIdentifier; diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdMobileTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdMobileTextBox.cs index fc80b32..d4b6769 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdMobileTextBox.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdMobileTextBox.cs @@ -583,8 +583,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </remarks> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Uri(Uri, string) accepts second arguments that Uri(Uri, new Uri(string)) does not that we must support.")] public IAuthenticationRequest CreateRequest() { - Contract.Requires<InvalidOperationException>(this.Request == null, OpenIdStrings.CreateRequestAlreadyCalled); - Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.Text), OpenIdStrings.OpenIdTextBoxEmpty); + Requires.ValidState(this.Request == null, OpenIdStrings.CreateRequestAlreadyCalled); + Requires.ValidState(!string.IsNullOrEmpty(this.Text), OpenIdStrings.OpenIdTextBoxEmpty); try { // Resolve the trust root, and swap out the scheme and port if necessary to match the @@ -669,7 +669,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response.</param> protected virtual void OnLoggedIn(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Authenticated, "Firing OnLoggedIn event without an authenticated response."); var loggedIn = this.LoggedIn; @@ -688,7 +688,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response.</param> protected virtual void OnFailed(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Failed, "Firing Failed event for the wrong response type."); var failed = this.Failed; @@ -702,7 +702,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response.</param> protected virtual void OnCanceled(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Canceled, "Firing Canceled event for the wrong response type."); var canceled = this.Canceled; @@ -716,7 +716,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response.</param> protected virtual void OnSetupRequired(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.SetupRequired, "Firing SetupRequired event for the wrong response type."); // Why are we firing Failed when we're OnSetupRequired? Backward compatibility. @@ -734,7 +734,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="request">The authentication request to add the extensions to.</param> private void AddProfileArgs(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); request.AddExtension(new ClaimsRequest() { Nickname = this.RequestNickname, diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs index eaaba8c..9c0004b 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs @@ -241,7 +241,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </remarks> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "By design")] public void RegisterClientScriptExtension<T>(string propertyName) where T : IClientScriptExtensionResponse { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(propertyName)); + Requires.NotNullOrEmpty(propertyName, "propertyName"); this.RelyingParty.RegisterClientScriptExtension<T>(propertyName); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs index eb0eacd..ff345d4 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs @@ -359,7 +359,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(value)); + Requires.NotNullOrEmpty(value, "value"); if (Page != null && !DesignMode) { // Validate new value by trying to construct a Realm object based on it. @@ -522,7 +522,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="request">The request.</param> public void LogOn(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); if (this.IsPopupAppropriate(request)) { this.ScriptPopupWindow(request); @@ -562,7 +562,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>. /// </returns> protected internal virtual IEnumerable<IAuthenticationRequest> CreateRequests(Identifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); // If this control is actually a member of another OpenID RP control, // delegate creation of requests to the parent control. @@ -604,7 +604,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>. /// </returns> protected IEnumerable<IAuthenticationRequest> CreateRequests() { - Contract.Requires<InvalidOperationException>(this.Identifier != null, OpenIdStrings.NoIdentifierSet); + Requires.ValidState(this.Identifier != null, OpenIdStrings.NoIdentifierSet); return this.CreateRequests(this.Identifier); } @@ -714,8 +714,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response.</param> protected virtual void OnLoggedIn(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); - Contract.Requires<ArgumentException>(response.Status == AuthenticationStatus.Authenticated); + Requires.NotNull(response, "response"); + Requires.True(response.Status == AuthenticationStatus.Authenticated, "response"); var loggedIn = this.LoggedIn; OpenIdEventArgs args = new OpenIdEventArgs(response); @@ -747,7 +747,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Returns whether the login should proceed. False if some event handler canceled the request. /// </returns> protected virtual bool OnLoggingIn(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); EventHandler<OpenIdEventArgs> loggingIn = this.LoggingIn; @@ -764,8 +764,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response.</param> protected virtual void OnCanceled(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); - Contract.Requires<ArgumentException>(response.Status == AuthenticationStatus.Canceled); + Requires.NotNull(response, "response"); + Requires.True(response.Status == AuthenticationStatus.Canceled, "response"); var canceled = this.Canceled; if (canceled != null) { @@ -778,8 +778,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response.</param> protected virtual void OnFailed(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); - Contract.Requires<ArgumentException>(response.Status == AuthenticationStatus.Failed); + Requires.NotNull(response, "response"); + Requires.True(response.Status == AuthenticationStatus.Failed, "response"); var failed = this.Failed; if (failed != null) { @@ -811,7 +811,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="relyingParty">The relying party.</param> [SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "relyingParty", Justification = "This makes it possible for overrides to see the value before it is set on a field.")] protected virtual void ConfigureRelyingParty(OpenIdRelyingParty relyingParty) { - Contract.Requires<ArgumentNullException>(relyingParty != null); + Requires.NotNull(relyingParty, "relyingParty"); // Only set RequireSsl to true, as we don't want to override // a .config setting of true with false. @@ -828,7 +828,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <c>true</c> if a popup should be used; <c>false</c> otherwise. /// </returns> protected virtual bool IsPopupAppropriate(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); switch (this.Popup) { case PopupBehavior.Never: @@ -850,8 +850,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="request">The outgoing authentication request.</param> /// <param name="windowStatus">The text to try to display in the status bar on mouse hover.</param> protected void RenderOpenIdMessageTransmissionAsAnchorAttributes(HtmlTextWriter writer, IAuthenticationRequest request, string windowStatus) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(writer, "writer"); + Requires.NotNull(request, "request"); // We render a standard HREF attribute for non-javascript browsers. writer.AddAttribute(HtmlTextWriterAttribute.Href, request.RedirectingResponse.GetDirectUriRequest(this.RelyingParty.Channel).AbsoluteUri); @@ -1004,7 +1004,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="request">The authentication request to send.</param> /// <returns>The javascript that should execute.</returns> private string CreateGetOrPostAHrefValue(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); Uri directUri = request.RedirectingResponse.GetDirectUriRequest(this.RelyingParty.Channel); return "window.dnoa_internal.GetOrPost(" + MessagingUtilities.GetSafeJavascriptValue(directUri.AbsoluteUri) + ");"; @@ -1015,8 +1015,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="request">The request.</param> private void ScriptPopupWindow(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<InvalidOperationException>(this.RelyingParty != null); + Requires.NotNull(request, "request"); + Requires.ValidState(this.RelyingParty != null); StringBuilder startupScript = new StringBuilder(); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs index 335b435..1dea39a 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs @@ -683,7 +683,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="request">The authentication request to add the extensions to.</param> private void AddProfileArgs(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); var sreg = new ClaimsRequest() { Nickname = this.RequestNickname, diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButtonContract.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButtonContract.cs index c70218a..709ad2d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButtonContract.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorButtonContract.cs @@ -30,7 +30,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="writer">The writer.</param> protected internal override void RenderLeadingAttributes(HtmlTextWriter writer) { - Contract.Requires<ArgumentNullException>(writer != null); + Requires.NotNull(writer, "writer"); } /// <summary> @@ -39,8 +39,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="writer">The writer.</param> /// <param name="selector">The containing selector control.</param> protected internal override void RenderButtonContent(HtmlTextWriter writer, OpenIdSelector selector) { - Contract.Requires<ArgumentNullException>(writer != null); - Contract.Requires<ArgumentNullException>(selector != null); + Requires.NotNull(writer, "writer"); + Requires.NotNull(selector, "selector"); } } } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorOpenIdButton.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorOpenIdButton.cs index ac4dcbf..26b10e8 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorOpenIdButton.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorOpenIdButton.cs @@ -30,7 +30,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="imageUrl">The image to display on the button.</param> public SelectorOpenIdButton(string imageUrl) : this() { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl)); + Requires.NotNullOrEmpty(imageUrl, "imageUrl"); this.Image = imageUrl; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorProviderButton.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorProviderButton.cs index 2195e73..efd6c50 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorProviderButton.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/SelectorProviderButton.cs @@ -32,8 +32,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="imageUrl">The image to display on the button.</param> public SelectorProviderButton(Identifier providerIdentifier, string imageUrl) : this() { - Contract.Requires<ArgumentNullException>(providerIdentifier != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(imageUrl)); + Requires.NotNull(providerIdentifier, "providerIdentifier"); + Requires.NotNullOrEmpty(imageUrl, "imageUrl"); this.OPIdentifier = providerIdentifier; this.Image = imageUrl; diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs index 20fc886..099573d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ExtensionsBindingElementRelyingParty.cs @@ -29,8 +29,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="securitySettings">The security settings.</param> internal ExtensionsBindingElementRelyingParty(IOpenIdExtensionFactory extensionFactory, RelyingPartySecuritySettings securitySettings) : base(extensionFactory, securitySettings, !securitySettings.IgnoreUnsignedExtensions) { - Contract.Requires<ArgumentNullException>(extensionFactory != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(extensionFactory, "extensionFactory"); + Requires.NotNull(securitySettings, "securitySettings"); this.relyingPartySecuritySettings = securitySettings; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs index 03266ec..4739d84 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="securitySettings">The security settings to apply.</param> internal OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings) : this(cryptoKeyStore, nonceStore, new OpenIdRelyingPartyMessageFactory(), securitySettings, false) { - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(securitySettings, "securitySettings"); } /// <summary> @@ -40,9 +40,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param> private OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, RelyingPartySecuritySettings securitySettings, bool nonVerifying) : base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings, nonVerifying)) { - Contract.Requires<ArgumentNullException>(messageTypeProvider != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); - Contract.Requires<ArgumentException>(!nonVerifying || securitySettings is RelyingPartySecuritySettings); + Requires.NotNull(messageTypeProvider, "messageTypeProvider"); + Requires.NotNull(securitySettings, "securitySettings"); + Requires.True(!nonVerifying || securitySettings is RelyingPartySecuritySettings); } /// <summary> @@ -74,7 +74,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// An array of binding elements which may be used to construct the channel. /// </returns> private static IChannelBindingElement[] InitializeBindingElements(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings, bool nonVerifying) { - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(securitySettings, "securitySettings"); SigningBindingElement signingElement; signingElement = nonVerifying ? null : new RelyingPartySigningBindingElement(new CryptoKeyStoreAsRelyingPartyAssociationStore(cryptoKeyStore ?? new MemoryCryptoKeyStore())); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs index 3649543..46cd103 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs @@ -83,8 +83,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="nonceStore">The nonce store to use.</param> /// <param name="securitySettings">The security settings of the RP.</param> internal ReturnToNonceBindingElement(INonceStore nonceStore, RelyingPartySecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(nonceStore != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(nonceStore, "nonceStore"); + Requires.NotNull(securitySettings, "securitySettings"); this.nonceStore = nonceStore; this.securitySettings = securitySettings; @@ -264,7 +264,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="value">The base64-encoded value of the nonce.</param> /// <returns>The instantiated and initialized nonce.</returns> internal static CustomNonce Deserialize(string value) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value)); + Requires.NotNullOrEmpty(value, "value"); byte[] nonce = MessagingUtilities.FromBase64WebSafeString(value); Contract.Assume(nonce != null); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/ExtensionsInteropRelyingPartyHelper.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/ExtensionsInteropRelyingPartyHelper.cs index 87eca8c..134aa16 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/ExtensionsInteropRelyingPartyHelper.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/ExtensionsInteropRelyingPartyHelper.cs @@ -37,7 +37,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")] public static void SpreadSregToAX(this RelyingParty.IAuthenticationRequest request, AXAttributeFormats attributeFormats) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); var req = (RelyingParty.AuthenticationRequest)request; var sreg = req.AppliedExtensions.OfType<ClaimsRequest>().SingleOrDefault(); @@ -93,7 +93,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// Never <c>null</c>.</returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sreg", Justification = "Abbreviation")] public static ClaimsResponse UnifyExtensionsAsSreg(this RelyingParty.IAuthenticationResponse response, bool allowUnsigned) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); var resp = (RelyingParty.IAuthenticationResponse)response; var sreg = allowUnsigned ? resp.GetUntrustedExtension<ClaimsResponse>() : resp.GetExtension<ClaimsResponse>(); @@ -143,7 +143,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="attributeFormat">The attribute formats the RP will try if this discovery fails.</param> /// <returns>The AX format(s) to use based on the Provider's advertised AX support.</returns> private static bool TryDetectOPAttributeFormat(RelyingParty.IAuthenticationRequest request, out AXAttributeFormats attributeFormat) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); attributeFormat = ExtensionsInteropHelper.DetectAXFormat(request.DiscoveryResult.Capabilities); return attributeFormat != AXAttributeFormats.None; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/UI/UIUtilities.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/UI/UIUtilities.cs index cee6882..a24aaba 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/UI/UIUtilities.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Extensions/UI/UIUtilities.cs @@ -34,9 +34,9 @@ namespace DotNetOpenAuth.OpenId.Extensions.UI { /// <param name="windowName">The name to assign to the popup window.</param> /// <returns>A string starting with 'window.open' and forming just that one method call.</returns> internal static string GetWindowPopupScript(OpenIdRelyingParty relyingParty, IAuthenticationRequest request, string windowName) { - Contract.Requires<ArgumentNullException>(relyingParty != null); - Contract.Requires<ArgumentNullException>(request != null); - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(windowName)); + Requires.NotNull(relyingParty, "relyingParty"); + Requires.NotNull(request, "request"); + Requires.NotNullOrEmpty(windowName, "windowName"); Uri popupUrl = request.RedirectingResponse.GetDirectUriRequest(relyingParty.Channel); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs index 215ea24..6d60030 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs @@ -158,7 +158,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="xrds">The XRDs to search.</param> /// <returns>A sequence of services.</returns> private static IEnumerable<ServiceElement> GetDescribedByServices(IEnumerable<XrdElement> xrds) { - Contract.Requires<ArgumentNullException>(xrds != null); + Requires.NotNull(xrds, "xrds"); Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null); var describedBy = from xrd in xrds @@ -175,9 +175,9 @@ namespace DotNetOpenAuth.OpenId { /// <param name="requestHandler">The request handler.</param> /// <returns>The discovered services.</returns> private static IEnumerable<IdentifierDiscoveryResult> GetExternalServices(IEnumerable<XrdElement> xrds, UriIdentifier identifier, IDirectWebRequestHandler requestHandler) { - Contract.Requires<ArgumentNullException>(xrds != null); - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(requestHandler != null); + Requires.NotNull(xrds, "xrds"); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(requestHandler, "requestHandler"); Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); var results = new List<IdentifierDiscoveryResult>(); @@ -214,9 +214,9 @@ namespace DotNetOpenAuth.OpenId { /// <exception cref="ProtocolException">Thrown if the XRDS document has an invalid or a missing signature.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "XmlDSig", Justification = "xml")] private static void ValidateXmlDSig(XrdsDocument document, UriIdentifier identifier, IncomingWebResponse response, string signingHost) { - Contract.Requires<ArgumentNullException>(document != null); - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(document, "document"); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(response, "response"); var signatureNode = document.Node.SelectSingleNode("/xrds:XRDS/ds:Signature", document.XmlNamespaceResolver); ErrorUtilities.VerifyProtocol(signatureNode != null, OpenIdStrings.MissingElement, "Signature"); @@ -299,9 +299,9 @@ namespace DotNetOpenAuth.OpenId { /// </returns> /// <exception cref="ProtocolException">Thrown if the XRDS document could not be obtained.</exception> private static IncomingWebResponse GetXrdsResponse(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, Uri xrdsLocation) { - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(requestHandler != null); - Contract.Requires<ArgumentNullException>(xrdsLocation != null); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(requestHandler, "requestHandler"); + Requires.NotNull(xrdsLocation, "xrdsLocation"); Contract.Ensures(Contract.Result<IncomingWebResponse>() != null); var request = (HttpWebRequest)WebRequest.Create(xrdsLocation); @@ -325,8 +325,8 @@ namespace DotNetOpenAuth.OpenId { /// <returns>A HTTP response carrying an XRDS document, or <c>null</c> if one could not be obtained.</returns> /// <exception cref="ProtocolException">Thrown if the XRDS document could not be obtained.</exception> private IncomingWebResponse GetXrdsResponse(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) { - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(requestHandler != null); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(requestHandler, "requestHandler"); Uri xrdsLocation = this.GetXrdsLocation(identifier, requestHandler, out signingHost); if (xrdsLocation == null) { return null; @@ -345,8 +345,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="signingHost">The host name on the certificate that should be used to verify the signature in the XRDS.</param> /// <returns>An absolute URI, or <c>null</c> if one could not be determined.</returns> private Uri GetXrdsLocation(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) { - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(requestHandler != null); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(requestHandler, "requestHandler"); using (var hostMetaResponse = this.GetHostMeta(identifier, requestHandler, out signingHost)) { if (hostMetaResponse == null) { return null; @@ -377,8 +377,8 @@ namespace DotNetOpenAuth.OpenId { /// The host-meta response, or <c>null</c> if no host-meta document could be obtained. /// </returns> private IncomingWebResponse GetHostMeta(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) { - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(requestHandler != null); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(requestHandler, "requestHandler"); foreach (var hostMetaProxy in this.GetHostMetaLocations(identifier)) { var hostMetaLocation = hostMetaProxy.GetProxy(identifier); var request = (HttpWebRequest)WebRequest.Create(hostMetaLocation); @@ -413,7 +413,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="identifier">The identifier.</param> /// <returns>A sequence of URIs that MAY provide the host-meta for a given identifier.</returns> private IEnumerable<HostMetaProxy> GetHostMetaLocations(UriIdentifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); // First try the proxies, as they are considered more "secure" than the local // host-meta for a domain since the domain may be defaced. @@ -440,8 +440,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="proxyFormat">The proxy formatting string.</param> /// <param name="signingHostFormat">The signing host formatting string.</param> public HostMetaProxy(string proxyFormat, string signingHostFormat) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(proxyFormat)); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(signingHostFormat)); + Requires.NotNullOrEmpty(proxyFormat, "proxyFormat"); + Requires.NotNullOrEmpty(signingHostFormat, "signingHostFormat"); this.ProxyFormat = proxyFormat; this.SigningHostFormat = signingHostFormat; } @@ -469,7 +469,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="identifier">The identifier being discovered.</param> /// <returns>The an absolute URI.</returns> public virtual Uri GetProxy(UriIdentifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); return new Uri(string.Format(CultureInfo.InvariantCulture, this.ProxyFormat, Uri.EscapeDataString(identifier.Uri.Host))); } @@ -479,7 +479,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="identifier">The identifier being discovered.</param> /// <returns>A host name.</returns> public virtual string GetSigningHost(UriIdentifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); return string.Format(CultureInfo.InvariantCulture, this.SigningHostFormat, identifier.Uri.Host, this.GetProxy(identifier).Host); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/AuthenticationResponseShim.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/AuthenticationResponseShim.cs index c0354ac..c0d2b35 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/AuthenticationResponseShim.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/AuthenticationResponseShim.cs @@ -30,7 +30,7 @@ namespace DotNetOpenAuth.OpenId.Interop { /// </summary> /// <param name="response">The response.</param> internal AuthenticationResponseShim(IAuthenticationResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); this.response = response; var claimsResponse = this.response.GetExtension<ClaimsResponse>(); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/ClaimsResponseShim.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/ClaimsResponseShim.cs index 689777b..fa3b874 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/ClaimsResponseShim.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/ClaimsResponseShim.cs @@ -31,7 +31,7 @@ namespace DotNetOpenAuth.OpenId.Interop { /// <param name="response">The Simple Registration response to wrap.</param> internal ClaimsResponseShim(ClaimsResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); this.response = response; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs index 04b39e1..99f1a3e 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateRequestRelyingParty.cs @@ -27,8 +27,8 @@ namespace DotNetOpenAuth.OpenId.Messages { /// and the provider OpenID version. /// </returns> internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider) { - Contract.Requires<ArgumentNullException>(securityRequirements != null); - Contract.Requires<ArgumentNullException>(provider != null); + Requires.NotNull(securityRequirements, "securityRequirements"); + Requires.NotNull(provider, "provider"); // Apply our knowledge of the endpoint's transport, OpenID version, and // security requirements to decide the best association. @@ -57,10 +57,10 @@ namespace DotNetOpenAuth.OpenId.Messages { /// and the provider OpenID version. /// </returns> internal static AssociateRequest Create(SecuritySettings securityRequirements, IProviderEndpoint provider, string associationType, string sessionType) { - Contract.Requires<ArgumentNullException>(securityRequirements != null); - Contract.Requires<ArgumentNullException>(provider != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType)); - Contract.Requires<ArgumentNullException>(sessionType != null); + Requires.NotNull(securityRequirements, "securityRequirements"); + Requires.NotNull(provider, "provider"); + Requires.NotNullOrEmpty(associationType, "associationType"); + Requires.NotNull(sessionType, "sessionType"); bool unencryptedAllowed = provider.Uri.IsTransportSecure(); if (unencryptedAllowed) { diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs index 35cb928..c8f8f17 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Messages/AssociateSuccessfulResponseRelyingPartyContract.cs @@ -26,7 +26,7 @@ namespace DotNetOpenAuth { /// The created association. /// </returns> Association IAssociateSuccessfulResponseRelyingParty.CreateAssociationAtRelyingParty(AssociateRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs index d8b8840..eb501c5 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs @@ -42,8 +42,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="associationStore">The association store. May be null for dumb mode relying parties.</param> /// <param name="securitySettings">The security settings.</param> internal AssociationManager(Channel channel, IRelyingPartyAssociationStore associationStore, RelyingPartySecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(channel != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(channel, "channel"); + Requires.NotNull(securitySettings, "securitySettings"); this.channel = channel; this.associationStore = associationStore; @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); this.channel = value; } } @@ -74,7 +74,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); this.securitySettings = value; } } @@ -104,7 +104,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="provider">The provider to create an association with.</param> /// <returns>The association if one exists and has useful life remaining. Otherwise <c>null</c>.</returns> internal Association GetExistingAssociation(IProviderEndpoint provider) { - Contract.Requires<ArgumentNullException>(provider != null); + Requires.NotNull(provider, "provider"); // If the RP has no application store for associations, there's no point in creating one. if (this.associationStore == null) { @@ -149,7 +149,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Any new association is automatically added to the <see cref="associationStore"/>. /// </remarks> private Association CreateNewAssociation(IProviderEndpoint provider) { - Contract.Requires<ArgumentNullException>(provider != null); + Requires.NotNull(provider, "provider"); // If there is no association store, there is no point in creating an association. if (this.associationStore == null) { @@ -183,7 +183,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// the given Provider given the current security settings. /// </returns> private Association CreateNewAssociation(IProviderEndpoint provider, AssociateRequest associateRequest, int retriesRemaining) { - Contract.Requires<ArgumentNullException>(provider != null); + Requires.NotNull(provider, "provider"); if (associateRequest == null || retriesRemaining < 0) { // this can happen if security requirements and protocol conflict diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Associations.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Associations.cs index b171bec..e65750f 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Associations.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Associations.cs @@ -60,7 +60,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="association">The association to add to the collection.</param> public void Set(Association association) { - Contract.Requires<ArgumentNullException>(association != null); + Requires.NotNull(association, "association"); Contract.Ensures(this.Get(association.Handle) == association); lock (this.associations) { this.associations.Remove(association.Handle); // just in case one already exists. @@ -77,7 +77,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <returns>The desired association, or null if none with the given handle could be found.</returns> [Pure] public Association Get(string handle) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(handle)); + Requires.NotNullOrEmpty(handle, "handle"); lock (this.associations) { if (this.associations.Contains(handle)) { @@ -94,7 +94,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="handle">The handle to the required association.</param> /// <returns>Whether an <see cref="Association"/> with the given handle was in the collection for removal.</returns> public bool Remove(string handle) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(handle)); + Requires.NotNullOrEmpty(handle, "handle"); lock (this.associations) { return this.associations.Remove(handle); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs index d79038c..f742a3d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs @@ -69,10 +69,10 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="returnToUrl">The base return_to URL that the Provider should return the user to to complete authentication. This should not include callback parameters as these should be added using the <see cref="AddCallbackArguments(string, string)"/> method.</param> /// <param name="relyingParty">The relying party that created this instance.</param> private AuthenticationRequest(IdentifierDiscoveryResult discoveryResult, Realm realm, Uri returnToUrl, OpenIdRelyingParty relyingParty) { - Contract.Requires<ArgumentNullException>(discoveryResult != null); - Contract.Requires<ArgumentNullException>(realm != null); - Contract.Requires<ArgumentNullException>(returnToUrl != null); - Contract.Requires<ArgumentNullException>(relyingParty != null); + Requires.NotNull(discoveryResult, "discoveryResult"); + Requires.NotNull(realm, "realm"); + Requires.NotNull(returnToUrl, "returnToUrl"); + Requires.NotNull(relyingParty, "relyingParty"); this.DiscoveryResult = discoveryResult; this.RelyingParty = relyingParty; @@ -319,9 +319,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Never null, but may be empty. /// </returns> internal static IEnumerable<AuthenticationRequest> Create(Identifier userSuppliedIdentifier, OpenIdRelyingParty relyingParty, Realm realm, Uri returnToUrl, bool createNewAssociationsAsNeeded) { - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); - Contract.Requires<ArgumentNullException>(relyingParty != null); - Contract.Requires<ArgumentNullException>(realm != null); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.NotNull(relyingParty, "relyingParty"); + Requires.NotNull(realm, "realm"); Contract.Ensures(Contract.Result<IEnumerable<AuthenticationRequest>>() != null); // Normalize the portion of the return_to path that correlates to the realm for capitalization. @@ -496,8 +496,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="relyingParty">The relying party.</param> /// <returns>A filtered and sorted list of endpoints; may be empty if the input was empty or the filter removed all endpoints.</returns> private static List<IdentifierDiscoveryResult> FilterAndSortEndpoints(IEnumerable<IdentifierDiscoveryResult> endpoints, OpenIdRelyingParty relyingParty) { - Contract.Requires<ArgumentNullException>(endpoints != null); - Contract.Requires<ArgumentNullException>(relyingParty != null); + Requires.NotNull(endpoints, "endpoints"); + Requires.NotNull(relyingParty, "relyingParty"); bool anyFilteredOut = false; var filteredEndpoints = new List<IdentifierDiscoveryResult>(); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs index 02ed3b0..1614145 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs @@ -24,7 +24,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="keyStore">The key store.</param> internal CryptoKeyStoreAsRelyingPartyAssociationStore(ICryptoKeyStore keyStore) { - Contract.Requires<ArgumentNullException>(keyStore != null); + Requires.NotNull(keyStore, "keyStore"); Contract.Ensures(this.keyStore == keyStore); this.keyStore = keyStore; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/FailedAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/FailedAuthenticationResponse.cs index 682e3ff..b9266d3 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/FailedAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/FailedAuthenticationResponse.cs @@ -28,7 +28,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="exception">The exception that resulted in the failed authentication.</param> internal FailedAuthenticationResponse(Exception exception) { - Contract.Requires<ArgumentNullException>(exception != null); + Requires.NotNull(exception, "exception"); this.Exception = exception; diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs index 21a2c53..52e828c 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs @@ -88,8 +88,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// TODO: what should implementations do on association handle conflict? /// </remarks> void IRelyingPartyAssociationStore.StoreAssociation(Uri providerEndpoint, Association association) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentNullException>(association != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.NotNull(association, "association"); throw new NotImplementedException(); } @@ -111,8 +111,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// ignored and a new association created. /// </remarks> Association IRelyingPartyAssociationStore.GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentNullException>(securityRequirements != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.NotNull(securityRequirements, "securityRequirements"); throw new NotImplementedException(); } @@ -125,7 +125,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle. /// </returns> Association IRelyingPartyAssociationStore.GetAssociation(Uri providerEndpoint, string handle) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); Contract.Requires(!String.IsNullOrEmpty(handle)); throw new NotImplementedException(); } @@ -143,7 +143,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// before this call. /// </remarks> bool IRelyingPartyAssociationStore.RemoveAssociation(Uri providerEndpoint, string handle) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); Contract.Requires(!String.IsNullOrEmpty(handle)); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs index cfbccef..2942c9d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs @@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> Identifier ISetupRequiredAuthenticationResponse.UserSuppliedIdentifier { get { - Contract.Requires<InvalidOperationException>(((IAuthenticationResponse)this).Status == AuthenticationStatus.SetupRequired, OpenIdStrings.OperationOnlyValidForSetupRequiredState); + Requires.ValidState(((IAuthenticationResponse)this).Status == AuthenticationStatus.SetupRequired, OpenIdStrings.OperationOnlyValidForSetupRequiredState); throw new System.NotImplementedException(); } } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs index 9e3824d..e6b84f5 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The negative assertion response received by the Relying Party.</param> internal NegativeAuthenticationResponse(NegativeAssertionResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); this.response = response; Reporting.RecordEventOccurrence(this, string.Empty); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs index d39d2ca..20382b3 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs @@ -114,7 +114,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // If we are a smart-mode RP (supporting associations), then we MUST also be // capable of storing nonces to prevent replay attacks. // If we're a dumb-mode RP, then 2.0 OPs are responsible for preventing replays. - Contract.Requires<ArgumentException>(cryptoKeyStore == null || nonceStore != null, OpenIdStrings.AssociationStoreRequiresNonceStore); + Requires.True(cryptoKeyStore == null || nonceStore != null, null, OpenIdStrings.AssociationStoreRequiresNonceStore); this.securitySettings = OpenIdElement.Configuration.RelyingParty.SecuritySettings.CreateSecuritySettings(); @@ -195,7 +195,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); this.channel = value; this.AssociationManager.Channel = value; } @@ -211,7 +211,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } internal set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); this.securitySettings = value; this.AssociationManager.SecuritySettings = value; } @@ -244,7 +244,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); this.endpointOrder = value; } } @@ -335,9 +335,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </returns> /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl) { - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); - Contract.Requires<ArgumentNullException>(realm != null); - Contract.Requires<ArgumentNullException>(returnToUrl != null); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.NotNull(realm, "realm"); + Requires.NotNull(returnToUrl, "returnToUrl"); Contract.Ensures(Contract.Result<IAuthenticationRequest>() != null); try { return this.CreateRequests(userSuppliedIdentifier, realm, returnToUrl).First(); @@ -368,8 +368,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm) { - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); - Contract.Requires<ArgumentNullException>(realm != null); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.NotNull(realm, "realm"); Contract.Ensures(Contract.Result<IAuthenticationRequest>() != null); try { var result = this.CreateRequests(userSuppliedIdentifier, realm).First(); @@ -397,7 +397,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier) { - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Contract.Ensures(Contract.Result<IAuthenticationRequest>() != null); try { return this.CreateRequests(userSuppliedIdentifier).First(); @@ -434,9 +434,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// An empty enumerable is returned instead.</para> /// </remarks> public virtual IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl) { - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); - Contract.Requires<ArgumentNullException>(realm != null); - Contract.Requires<ArgumentNullException>(returnToUrl != null); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.NotNull(realm, "realm"); + Requires.NotNull(returnToUrl, "returnToUrl"); Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null); return AuthenticationRequest.Create(userSuppliedIdentifier, this, realm, returnToUrl, true).Cast<IAuthenticationRequest>().CacheGeneratedResults(); @@ -468,9 +468,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </remarks> /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm) { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); - Contract.Requires<ArgumentNullException>(realm != null); + Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.NotNull(realm, "realm"); Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null); // This next code contract is a BAD idea, because it causes each authentication request to be generated @@ -516,8 +516,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </remarks> /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier) { - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); - Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); Contract.Ensures(Contract.Result<IEnumerable<IAuthenticationRequest>>() != null); return this.CreateRequests(userSuppliedIdentifier, Realm.AutoDetect); @@ -531,7 +531,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> /// </remarks> public IAuthenticationResponse GetResponse() { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); return this.GetResponse(this.Channel.GetRequestFromContext()); } @@ -541,7 +541,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="httpRequestInfo">The HTTP request that may be carrying an authentication response from the Provider.</param> /// <returns>The processed authentication response if there is any; <c>null</c> otherwise.</returns> public IAuthenticationResponse GetResponse(HttpRequestInfo httpRequestInfo) { - Contract.Requires<ArgumentNullException>(httpRequestInfo != null); + Requires.NotNull(httpRequestInfo, "httpRequestInfo"); try { var message = this.Channel.ReadFromRequest(httpRequestInfo); PositiveAssertionResponse positiveAssertion; @@ -584,7 +584,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> /// </remarks> public OutgoingWebResponse ProcessResponseFromPopup() { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); return this.ProcessResponseFromPopup(this.Channel.GetRequestFromContext()); @@ -596,7 +596,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="request">The incoming HTTP request that is expected to carry an OpenID authentication response.</param> /// <returns>The HTTP response to send to this HTTP request.</returns> public OutgoingWebResponse ProcessResponseFromPopup(HttpRequestInfo request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); return this.ProcessResponseFromPopup(request, null); @@ -614,7 +614,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </remarks> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "By design")] public void RegisterClientScriptExtension<T>(string propertyName) where T : IClientScriptExtensionResponse { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(propertyName)); + Requires.NotNullOrEmpty(propertyName, "propertyName"); ErrorUtilities.VerifyArgumentNamed(!this.clientScriptExtensions.ContainsValue(propertyName), "propertyName", OpenIdStrings.ClientScriptExtensionPropertyNameCollision, propertyName); foreach (var ext in this.clientScriptExtensions.Keys) { ErrorUtilities.VerifyArgument(ext != typeof(T), OpenIdStrings.ClientScriptExtensionTypeCollision, typeof(T).FullName); @@ -683,7 +683,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </returns> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "OpenID", Justification = "real word"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "iframe", Justification = "Code contracts")] internal OutgoingWebResponse ProcessResponseFromPopup(HttpRequestInfo request, Action<AuthenticationStatus> callback) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null); string extensionsJson = null; @@ -740,7 +740,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="identifier">The identifier to discover services for.</param> /// <returns>A non-null sequence of services discovered for the identifier.</returns> internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); IEnumerable<IdentifierDiscoveryResult> results = Enumerable.Empty<IdentifierDiscoveryResult>(); @@ -828,7 +828,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// parameters. (i.e. "callback('arg1', 2)"). No escaping is done by this method.</param> /// <returns>The entire HTTP response to send to the popup window or iframe to perform the invocation.</returns> private static OutgoingWebResponse InvokeParentPageScript(string methodCall) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(methodCall)); + Requires.NotNullOrEmpty(methodCall, "methodCall"); Logger.OpenId.DebugFormat("Sending Javascript callback: {0}", methodCall); StringBuilder builder = new StringBuilder(); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAnonymousResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAnonymousResponse.cs index fc334b0..de82bed 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAnonymousResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAnonymousResponse.cs @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="response">The response message.</param> protected internal PositiveAnonymousResponse(IndirectSignedResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); this.response = response; if (response.ProviderEndpoint != null && response.Version != null) { diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs index 3e2298c..1123912 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs @@ -26,7 +26,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="relyingParty">The relying party.</param> internal PositiveAuthenticationResponse(PositiveAssertionResponse response, OpenIdRelyingParty relyingParty) : base(response) { - Contract.Requires<ArgumentNullException>(relyingParty != null); + Requires.NotNull(relyingParty, "relyingParty"); this.Endpoint = IdentifierDiscoveryResult.CreateForClaimedIdentifier( this.Response.ClaimedIdentifier, diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs index 80b424a..141b4f7 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponseSnapshot.cs @@ -33,7 +33,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="copyFrom">The authentication response to copy from.</param> internal PositiveAuthenticationResponseSnapshot(IAuthenticationResponse copyFrom) { - Contract.Requires<ArgumentNullException>(copyFrom != null); + Requires.NotNull(copyFrom, "copyFrom"); this.ClaimedIdentifier = copyFrom.ClaimedIdentifier; this.FriendlyIdentifierForDisplay = copyFrom.FriendlyIdentifierForDisplay; diff --git a/src/DotNetOpenAuth.OpenId/Configuration/OpenIdElement.cs b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdElement.cs index af038f2..e7b856e 100644 --- a/src/DotNetOpenAuth.OpenId/Configuration/OpenIdElement.cs +++ b/src/DotNetOpenAuth.OpenId/Configuration/OpenIdElement.cs @@ -87,7 +87,7 @@ namespace DotNetOpenAuth.Configuration { } set { - Contract.Requires<ArgumentOutOfRangeException>(value > TimeSpan.Zero); + Requires.InRange(value > TimeSpan.Zero, "value"); this[MaxAuthenticationTimePropertyName] = value; } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Association.cs b/src/DotNetOpenAuth.OpenId/OpenId/Association.cs index d063aa1..ff30a36 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Association.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Association.cs @@ -35,11 +35,11 @@ namespace DotNetOpenAuth.OpenId { /// <param name="totalLifeLength">How long the association will be useful.</param> /// <param name="issued">The UTC time of when this association was originally issued by the Provider.</param> protected Association(string handle, byte[] secret, TimeSpan totalLifeLength, DateTime issued) { - Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(handle)); - Contract.Requires<ArgumentNullException>(secret != null); - Contract.Requires<ArgumentOutOfRangeException>(totalLifeLength > TimeSpan.Zero); - Contract.Requires<ArgumentException>(issued.Kind == DateTimeKind.Utc); - Contract.Requires<ArgumentOutOfRangeException>(issued <= DateTime.UtcNow); + Requires.NotNullOrEmpty(handle, "handle"); + Requires.NotNull(secret, "secret"); + Requires.InRange(totalLifeLength > TimeSpan.Zero, "totalLifeLength"); + Requires.True(issued.Kind == DateTimeKind.Utc, "issued"); + Requires.InRange(issued <= DateTime.UtcNow, "issued"); Contract.Ensures(this.TotalLifeLength == totalLifeLength); this.Handle = handle; @@ -162,8 +162,8 @@ namespace DotNetOpenAuth.OpenId { /// IRelyingPartyAssociationStore.GetAssociation method. /// </returns> public static Association Deserialize(string handle, DateTime expiresUtc, byte[] privateData) { - Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(handle)); - Contract.Requires<ArgumentNullException>(privateData != null); + Requires.NotNullOrEmpty(handle, "handle"); + Requires.NotNull(privateData, "privateData"); Contract.Ensures(Contract.Result<Association>() != null); expiresUtc = expiresUtc.ToUniversalTimeSafe(); @@ -278,7 +278,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="data">The data to sign. This data will not be changed (the signature is the return value).</param> /// <returns>The calculated signature of the data.</returns> protected internal byte[] Sign(byte[] data) { - Contract.Requires<ArgumentNullException>(data != null); + Requires.NotNull(data, "data"); using (HashAlgorithm hasher = this.CreateHasher()) { return hasher.ComputeHash(data); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/AssociationContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/AssociationContract.cs index 57f4fd9..e36028e 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/AssociationContract.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/AssociationContract.cs @@ -46,7 +46,7 @@ namespace DotNetOpenAuth.OpenId { /// </returns> [Pure] internal override string GetAssociationType(Protocol protocol) { - Contract.Requires<ArgumentNullException>(protocol != null); + Requires.NotNull(protocol, "protocol"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs index ace8d69..705f737 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs @@ -33,8 +33,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="securitySettings">The security settings.</param> /// <param name="receiveUnsignedExtensions">Security setting for relying parties. Should be true for Providers.</param> internal ExtensionsBindingElement(IOpenIdExtensionFactory extensionFactory, SecuritySettings securitySettings, bool receiveUnsignedExtensions) { - Contract.Requires<ArgumentNullException>(extensionFactory != null); - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(extensionFactory, "extensionFactory"); + Requires.NotNull(securitySettings, "securitySettings"); this.ExtensionFactory = extensionFactory; this.receiveUnsignedExtensions = receiveUnsignedExtensions; @@ -238,7 +238,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// A dictionary of message parts, including only signed parts when appropriate. /// </returns> private IDictionary<string, string> GetExtensionsDictionary(IProtocolMessage message, bool ignoreUnsigned) { - Contract.Requires<InvalidOperationException>(this.Channel != null); + Requires.ValidState(this.Channel != null); IndirectSignedResponse signedResponse = message as IndirectSignedResponse; if (signedResponse != null && ignoreUnsigned) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs index 46c2139..1993cb4 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs @@ -101,7 +101,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </remarks> [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Not a problem for this type.")] public static byte[] GetBytes(IEnumerable<KeyValuePair<string, string>> keysAndValues) { - Contract.Requires<ArgumentNullException>(keysAndValues != null); + Requires.NotNull(keysAndValues, "keysAndValues"); using (MemoryStream ms = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(ms, textEncoding)) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs index cc49a95..a2a5c88 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs @@ -48,7 +48,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param> protected OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements) : base(messageTypeProvider, bindingElements) { - Contract.Requires<ArgumentNullException>(messageTypeProvider != null); + Requires.NotNull(messageTypeProvider, "messageTypeProvider"); // Customize the binding element order, since we play some tricks for higher // security and backward compatibility with older OpenID versions. diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs index bc7b2a1..25a29bb 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs @@ -58,7 +58,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </summary> /// <param name="cryptoKeyStore">The crypto key store.</param> internal ReturnToSignatureBindingElement(ICryptoKeyStore cryptoKeyStore) { - Contract.Requires<ArgumentNullException>(cryptoKeyStore != null); + Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); this.cryptoKeyStore = cryptoKeyStore; } @@ -173,7 +173,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// or other minor changes do not invalidate the signature. /// </remarks> private byte[] GetReturnToSignature(Uri returnTo, CryptoKey cryptoKey = null) { - Contract.Requires<ArgumentNullException>(returnTo != null); + Requires.NotNull(returnTo, "returnTo"); // 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 diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs index f186adc..95a748e 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs @@ -120,9 +120,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="association">The association to use to sign the message.</param> /// <returns>The calculated signature of the method.</returns> protected string GetSignature(ITamperResistantOpenIdMessage signedMessage, Association association) { - Contract.Requires<ArgumentNullException>(signedMessage != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(signedMessage.SignedParameterOrder)); - Contract.Requires<ArgumentNullException>(association != null); + Requires.NotNull(signedMessage, "signedMessage"); + Requires.True(!String.IsNullOrEmpty(signedMessage.SignedParameterOrder), "signedMessage"); + Requires.NotNull(association, "association"); // Prepare the parts to sign, taking care to replace an openid.mode value // of check_authentication with its original id_res so the signature matches. diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs index c46cd12..bf8b18d 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElementContract.cs @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// The association to use to sign or verify the message. /// </returns> protected override Association GetAssociation(ITamperResistantOpenIdMessage signedMessage) { - Contract.Requires<ArgumentNullException>(signedMessage != null); + Requires.NotNull(signedMessage, "signedMessage"); throw new NotImplementedException(); } @@ -57,7 +57,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// The referenced association; or <c>null</c> if such an association cannot be found. /// </returns> protected override Association GetSpecificAssociation(ITamperResistantOpenIdMessage signedMessage) { - Contract.Requires<ArgumentNullException>(signedMessage != null); + Requires.NotNull(signedMessage, "signedMessage"); throw new NotImplementedException(); } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/DiffieHellmanUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/DiffieHellmanUtilities.cs index 249f1f3..78f90c9 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/DiffieHellmanUtilities.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/DiffieHellmanUtilities.cs @@ -37,8 +37,8 @@ namespace DotNetOpenAuth.OpenId { /// <returns>The hashing algorithm to use.</returns> /// <exception cref="ProtocolException">Thrown if no match could be found for the given <paramref name="sessionType"/>.</exception> public static HashAlgorithm Lookup(Protocol protocol, string sessionType) { - Contract.Requires<ArgumentNullException>(protocol != null); - Contract.Requires<ArgumentNullException>(sessionType != null); + Requires.NotNull(protocol, "protocol"); + Requires.NotNull(sessionType, "sessionType"); // We COULD use just First instead of FirstOrDefault, but we want to throw ProtocolException instead of InvalidOperationException. DHSha match = diffieHellmanSessionTypes.FirstOrDefault(dhsha => String.Equals(dhsha.GetName(protocol), sessionType, StringComparison.Ordinal)); @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="hashSizeInBits">The hash size (in bits) that the DH session must have.</param> /// <returns>The value to be used for the openid.session_type parameter, or null if no match was found.</returns> internal static string GetNameForSize(Protocol protocol, int hashSizeInBits) { - Contract.Requires<ArgumentNullException>(protocol != null); + Requires.NotNull(protocol, "protocol"); DHSha match = diffieHellmanSessionTypes.FirstOrDefault(dhsha => dhsha.Algorithm.HashSize == hashSizeInBits); return match != null ? match.GetName(protocol) : null; } @@ -73,10 +73,10 @@ namespace DotNetOpenAuth.OpenId { /// The secret itself if the encrypted version of the secret was given in <paramref name="remotePublicKey"/>. /// </returns> internal static byte[] SHAHashXorSecret(HashAlgorithm hasher, DiffieHellman dh, byte[] remotePublicKey, byte[] plainOrEncryptedSecret) { - Contract.Requires<ArgumentNullException>(hasher != null); - Contract.Requires<ArgumentNullException>(dh != null); - Contract.Requires<ArgumentNullException>(remotePublicKey != null); - Contract.Requires<ArgumentNullException>(plainOrEncryptedSecret != null); + Requires.NotNull(hasher, "hasher"); + Requires.NotNull(dh, "dh"); + Requires.NotNull(remotePublicKey, "remotePublicKey"); + Requires.NotNull(plainOrEncryptedSecret, "plainOrEncryptedSecret"); byte[] sharedBlock = dh.DecryptKeyExchange(remotePublicKey); byte[] sharedBlockHash = hasher.ComputeHash(EnsurePositive(sharedBlock)); @@ -102,7 +102,7 @@ namespace DotNetOpenAuth.OpenId { /// This is to be consistent with OpenID spec section 4.2. /// </remarks> internal static byte[] EnsurePositive(byte[] inputBytes) { - Contract.Requires<ArgumentNullException>(inputBytes != null); + Requires.NotNull(inputBytes, "inputBytes"); if (inputBytes.Length == 0) { throw new ArgumentException(MessagingStrings.UnexpectedEmptyArray, "inputBytes"); } @@ -128,8 +128,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="algorithm">The hashing algorithm used in this particular Diffie-Hellman session type.</param> /// <param name="getName">A function that will return the value of the openid.session_type parameter for a given version of OpenID.</param> public DHSha(HashAlgorithm algorithm, Func<Protocol, string> getName) { - Contract.Requires<ArgumentNullException>(algorithm != null); - Contract.Requires<ArgumentNullException>(getName != null); + Requires.NotNull(algorithm, "algorithm"); + Requires.NotNull(getName, "getName"); this.GetName = getName; this.Algorithm = algorithm; diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AliasManager.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AliasManager.cs index 0a84266..f6878ec 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AliasManager.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AliasManager.cs @@ -45,7 +45,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="typeUri">The type URI.</param> /// <returns>The alias assigned to this type URI. Never null.</returns> public string GetAlias(string typeUri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(typeUri, "typeUri"); string alias; return this.typeUriToAliasMap.TryGetValue(typeUri, out alias) ? alias : this.AssignNewAlias(typeUri); } @@ -56,8 +56,8 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="alias">The alias.</param> /// <param name="typeUri">The type URI.</param> public void SetAlias(string alias, string typeUri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias)); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(alias, "alias"); + Requires.NotNullOrEmpty(typeUri, "typeUri"); this.aliasToTypeUriMap.Add(alias, typeUri); this.typeUriToAliasMap.Add(typeUri, alias); } @@ -68,7 +68,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="typeUris">The type URIs to create aliases for.</param> /// <param name="preferredTypeUriToAliases">An optional dictionary of URI/alias pairs that suggest preferred aliases to use if available for certain type URIs.</param> public void AssignAliases(IEnumerable<string> typeUris, IDictionary<string, string> preferredTypeUriToAliases) { - Contract.Requires<ArgumentNullException>(typeUris != null); + Requires.NotNull(typeUris, "typeUris"); // First go through the actually used type URIs and see which ones have matching preferred aliases. if (preferredTypeUriToAliases != null) { @@ -103,7 +103,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// </summary> /// <param name="preferredTypeUriToAliases">A dictionary of type URI keys and alias values.</param> public void SetPreferredAliasesWhereNotSet(IDictionary<string, string> preferredTypeUriToAliases) { - Contract.Requires<ArgumentNullException>(preferredTypeUriToAliases != null); + Requires.NotNull(preferredTypeUriToAliases, "preferredTypeUriToAliases"); foreach (var pair in preferredTypeUriToAliases) { if (this.typeUriToAliasMap.ContainsKey(pair.Key)) { @@ -128,7 +128,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <returns>The Type URI.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if the given alias does not have a matching TypeURI.</exception> public string ResolveAlias(string alias) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias)); + Requires.NotNullOrEmpty(alias, "alias"); string typeUri = this.TryResolveAlias(alias); if (typeUri == null) { throw new ArgumentOutOfRangeException("alias"); @@ -142,7 +142,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="alias">The alias.</param> /// <returns>The Type URI for the given alias, or null if none for that alias exist.</returns> public string TryResolveAlias(string alias) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias)); + Requires.NotNullOrEmpty(alias, "alias"); string typeUri = null; this.aliasToTypeUriMap.TryGetValue(alias, out typeUri); return typeUri; @@ -154,7 +154,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="alias">The alias in question.</param> /// <returns>True if the alias has already been assigned. False otherwise.</returns> public bool IsAliasUsed(string alias) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(alias)); + Requires.NotNullOrEmpty(alias, "alias"); return this.aliasToTypeUriMap.ContainsKey(alias); } @@ -166,7 +166,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <c>true</c> if the given type URI already has an alias assigned; <c>false</c> otherwise. /// </returns> public bool IsAliasAssignedTo(string typeUri) { - Contract.Requires<ArgumentNullException>(typeUri != null); + Requires.NotNull(typeUri, "typeUri"); return this.typeUriToAliasMap.ContainsKey(typeUri); } @@ -176,7 +176,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="typeUri">The type URI to assign a new alias to.</param> /// <returns>The newly generated alias.</returns> private string AssignNewAlias(string typeUri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(typeUri, "typeUri"); ErrorUtilities.VerifyInternal(!this.typeUriToAliasMap.ContainsKey(typeUri), "Oops! This type URI already has an alias!"); string alias = string.Format(CultureInfo.InvariantCulture, AliasFormat, this.typeUriToAliasMap.Count + 1); this.typeUriToAliasMap.Add(typeUri, alias); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXUtilities.cs index 2b947f7..96cc437 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXUtilities.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AXUtilities.cs @@ -21,7 +21,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// <param name="collection">The attribute request collection.</param> /// <param name="typeUri">The type URI of the required attribute.</param> public static void AddRequired(this ICollection<AttributeRequest> collection, string typeUri) { - Contract.Requires<ArgumentNullException>(collection != null); + Requires.NotNull(collection, "collection"); collection.Add(new AttributeRequest(typeUri, true)); } @@ -31,7 +31,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// <param name="collection">The attribute request collection.</param> /// <param name="typeUri">The type URI of the requested attribute.</param> public static void AddOptional(this ICollection<AttributeRequest> collection, string typeUri) { - Contract.Requires<ArgumentNullException>(collection != null); + Requires.NotNull(collection, "collection"); collection.Add(new AttributeRequest(typeUri, false)); } @@ -43,7 +43,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// <param name="typeUri">The type URI of the attribute.</param> /// <param name="values">The attribute values.</param> public static void Add(this ICollection<AttributeValues> collection, string typeUri, params string[] values) { - Contract.Requires<ArgumentNullException>(collection != null); + Requires.NotNull(collection, "collection"); collection.Add(new AttributeValues(typeUri, values)); } @@ -53,8 +53,8 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// <param name="fields">The dictionary to fill with serialized attributes.</param> /// <param name="attributes">The attributes.</param> internal static void SerializeAttributes(IDictionary<string, string> fields, IEnumerable<AttributeValues> attributes) { - Contract.Requires<ArgumentNullException>(fields != null); - Contract.Requires<ArgumentNullException>(attributes != null); + Requires.NotNull(fields, "fields"); + Requires.NotNull(attributes, "attributes"); AliasManager aliasManager = new AliasManager(); foreach (var att in attributes) { @@ -123,7 +123,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// <param name="fields">The data included in the extension message.</param> /// <returns>The alias manager that provides lookup between aliases and type URIs.</returns> private static AliasManager ParseAliases(IDictionary<string, string> fields) { - Contract.Requires<ArgumentNullException>(fields != null); + Requires.NotNull(fields, "fields"); AliasManager aliasManager = new AliasManager(); const string TypePrefix = "type."; diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeRequest.cs index 2dc9c69..cbcbff6 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeRequest.cs @@ -36,7 +36,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// </summary> /// <param name="typeUri">The unique TypeURI for that describes the attribute being sought.</param> public AttributeRequest(string typeUri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(typeUri, "typeUri"); this.TypeUri = typeUri; } @@ -84,7 +84,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { } set { - Contract.Requires<ArgumentOutOfRangeException>(value > 0); + Requires.InRange(value > 0, "value"); this.count = value; } } @@ -99,8 +99,8 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// the <see cref="FetchResponse"/> object. /// </returns> public AttributeValues Respond(params string[] values) { - Contract.Requires<ArgumentNullException>(values != null); - Contract.Requires<ArgumentException>(values.Length <= this.Count); + Requires.NotNull(values, "values"); + Requires.True(values.Length <= this.Count, "values"); return new AttributeValues(this.TypeUri, values); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeValues.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeValues.cs index b2fc1fe..37ebe38 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeValues.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/AttributeExchange/AttributeValues.cs @@ -25,7 +25,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// <param name="typeUri">The TypeURI that uniquely identifies the attribute.</param> /// <param name="values">The values for the attribute.</param> public AttributeValues(string typeUri, params string[] values) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(typeUri, "typeUri"); this.TypeUri = typeUri; this.Values = (IList<string>)values ?? EmptyList<string>.Instance; @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.AttributeExchange { /// </summary> /// <param name="typeUri">The TypeURI of the attribute whose values are being provided.</param> internal AttributeValues(string typeUri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(typeUri, "typeUri"); this.TypeUri = typeUri; this.Values = new List<string>(1); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionArgumentsManager.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionArgumentsManager.cs index 0a78df1..328d81f 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionArgumentsManager.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionArgumentsManager.cs @@ -64,7 +64,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="query">The parameters in the OpenID message.</param> /// <returns>The newly created instance of <see cref="ExtensionArgumentsManager"/>.</returns> public static ExtensionArgumentsManager CreateIncomingExtensions(IDictionary<string, string> query) { - Contract.Requires<ArgumentNullException>(query != null); + Requires.NotNull(query, "query"); var mgr = new ExtensionArgumentsManager(); mgr.protocol = Protocol.Detect(query); mgr.isReadMode = true; @@ -134,9 +134,9 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="extensionTypeUri">The extension type URI.</param> /// <param name="arguments">The arguments for this extension to add to the message.</param> public void AddExtensionArguments(string extensionTypeUri, IDictionary<string, string> arguments) { - Contract.Requires<InvalidOperationException>(!this.ReadMode); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(extensionTypeUri)); - Contract.Requires<ArgumentNullException>(arguments != null); + Requires.ValidState(!this.ReadMode); + Requires.NotNullOrEmpty(extensionTypeUri, "extensionTypeUri"); + Requires.NotNull(arguments, "arguments"); if (arguments.Count == 0) { return; } @@ -162,7 +162,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// </param> /// <returns>A dictionary of key=value pairs to add to the message to carry the extension.</returns> internal IDictionary<string, string> GetArgumentsToSend(bool includeOpenIdPrefix) { - Contract.Requires<InvalidOperationException>(!this.ReadMode); + Requires.ValidState(!this.ReadMode); Dictionary<string, string> args = new Dictionary<string, string>(); foreach (var typeUriAndExtension in this.extensions) { string typeUri = typeUriAndExtension.Key; @@ -195,8 +195,8 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// The fields included in the given extension, or null if the extension is not present. /// </returns> internal IDictionary<string, string> GetExtensionArguments(string extensionTypeUri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(extensionTypeUri)); - Contract.Requires<InvalidOperationException>(this.ReadMode); + Requires.NotNullOrEmpty(extensionTypeUri, "extensionTypeUri"); + Requires.ValidState(this.ReadMode); IDictionary<string, string> extensionArgs; this.extensions.TryGetValue(extensionTypeUri, out extensionArgs); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionsInteropHelper.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionsInteropHelper.cs index 13da4f3..f0af03d 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionsInteropHelper.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ExtensionsInteropHelper.cs @@ -58,7 +58,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="targetFormat">The target format. Only one flag should be set.</param> /// <returns>The AX attribute type URI in the target format.</returns> internal static string TransformAXFormat(string axSchemaOrgFormatTypeUri, AXAttributeFormats targetFormat) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(axSchemaOrgFormatTypeUri)); + Requires.NotNullOrEmpty(axSchemaOrgFormatTypeUri, "axSchemaOrgFormatTypeUri"); switch (targetFormat) { case AXAttributeFormats.AXSchemaOrg: @@ -78,7 +78,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="typeURIs">The type URIs to scan for recognized formats.</param> /// <returns>The first AX type URI format recognized in the list.</returns> internal static AXAttributeFormats DetectAXFormat(IEnumerable<string> typeURIs) { - Contract.Requires<ArgumentNullException>(typeURIs != null); + Requires.NotNull(typeURIs, "typeURIs"); if (typeURIs.Any(uri => uri.StartsWith("http://axschema.org/", StringComparison.Ordinal))) { return AXAttributeFormats.AXSchemaOrg; @@ -103,8 +103,8 @@ namespace DotNetOpenAuth.OpenId.Extensions { /// <param name="axSchemaOrgFormatAttribute">The attribute in axschema.org format.</param> /// <param name="demandLevel">The demand level.</param> internal static void FetchAttribute(FetchRequest ax, AXAttributeFormats format, string axSchemaOrgFormatAttribute, DemandLevel demandLevel) { - Contract.Requires<ArgumentNullException>(ax != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(axSchemaOrgFormatAttribute)); + Requires.NotNull(ax, "ax"); + Requires.NotNullOrEmpty(axSchemaOrgFormatAttribute, "axSchemaOrgFormatAttribute"); string typeUri = TransformAXFormat(axSchemaOrgFormatAttribute, format); if (!ax.Attributes.Contains(typeUri)) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs index eeaea31..d8ffb63 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PapeUtilities.cs @@ -46,7 +46,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy { /// <returns>The concatenated string of elements.</returns> /// <exception cref="FormatException">Thrown if any element in the sequence includes a space.</exception> internal static string ConcatenateListOfElements(IEnumerable<string> values) { - Contract.Requires<ArgumentNullException>(values != null); + Requires.NotNull(values, "values"); StringBuilder valuesList = new StringBuilder(); foreach (string value in values.Distinct()) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs index 246ec07..1fddc22 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/ProviderAuthenticationPolicy/PolicyResponse.cs @@ -83,7 +83,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy { } set { - Contract.Requires<ArgumentException>(!value.HasValue || value.Value.Kind != DateTimeKind.Unspecified, OpenIdStrings.UnspecifiedDateTimeKindNotAllowed); + Requires.True(!value.HasValue || value.Value.Kind != DateTimeKind.Unspecified, "value", OpenIdStrings.UnspecifiedDateTimeKindNotAllowed); // Make sure that whatever is set here, it becomes UTC time. if (value.HasValue) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs index cec8042..18f63d4 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsRequest.cs @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.SimpleRegistration { /// <param name="typeUri">The type URI this extension was recognized by in the OpenID message.</param> internal ClaimsRequest(string typeUri) : this() { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(typeUri, "typeUri"); this.typeUriDeserializedFrom = typeUri; } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs index d4df028..b50833b 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/SimpleRegistration/ClaimsResponse.cs @@ -70,7 +70,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.SimpleRegistration { /// </param> internal ClaimsResponse(string typeUriToUse) : base(new Version(1, 0), typeUriToUse, Constants.AdditionalTypeUris) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUriToUse)); + Requires.NotNullOrEmpty(typeUriToUse, "typeUriToUse"); } /// <summary> diff --git a/src/DotNetOpenAuth.OpenId/OpenId/HmacShaAssociation.cs b/src/DotNetOpenAuth.OpenId/OpenId/HmacShaAssociation.cs index 6955f48..d723756 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/HmacShaAssociation.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/HmacShaAssociation.cs @@ -61,10 +61,10 @@ namespace DotNetOpenAuth.OpenId { /// <param name="totalLifeLength">The time duration the association will be good for.</param> private HmacShaAssociation(HmacSha typeIdentity, string handle, byte[] secret, TimeSpan totalLifeLength) : base(handle, secret, totalLifeLength, DateTime.UtcNow) { - Contract.Requires<ArgumentNullException>(typeIdentity != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle)); - Contract.Requires<ArgumentNullException>(secret != null); - Contract.Requires<ArgumentOutOfRangeException>(totalLifeLength > TimeSpan.Zero); + Requires.NotNull(typeIdentity, "typeIdentity"); + Requires.NotNullOrEmpty(handle, "handle"); + Requires.NotNull(secret, "secret"); + Requires.InRange(totalLifeLength > TimeSpan.Zero, "totalLifeLength"); Contract.Ensures(this.TotalLifeLength == totalLifeLength); ErrorUtilities.VerifyProtocol(secret.Length == typeIdentity.SecretLength, OpenIdStrings.AssociationSecretAndTypeLengthMismatch, secret.Length, typeIdentity.GetAssociationType(Protocol.Default)); @@ -91,9 +91,9 @@ namespace DotNetOpenAuth.OpenId { /// <param name="totalLifeLength">How long the association will be good for.</param> /// <returns>The newly created association.</returns> public static HmacShaAssociation Create(Protocol protocol, string associationType, string handle, byte[] secret, TimeSpan totalLifeLength) { - Contract.Requires<ArgumentNullException>(protocol != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType)); - Contract.Requires<ArgumentNullException>(secret != null); + Requires.NotNull(protocol, "protocol"); + Requires.NotNullOrEmpty(associationType, "associationType"); + Requires.NotNull(secret, "secret"); Contract.Ensures(Contract.Result<HmacShaAssociation>() != null); HmacSha match = hmacShaAssociationTypes.FirstOrDefault(sha => String.Equals(sha.GetAssociationType(protocol), associationType, StringComparison.Ordinal)); ErrorUtilities.VerifyProtocol(match != null, OpenIdStrings.NoAssociationTypeFoundByName, associationType); @@ -108,8 +108,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="totalLifeLength">Total lifetime.</param> /// <returns>The newly created association.</returns> public static HmacShaAssociation Create(string handle, byte[] secret, TimeSpan totalLifeLength) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle)); - Contract.Requires<ArgumentNullException>(secret != null); + Requires.NotNullOrEmpty(handle, "handle"); + Requires.NotNull(secret, "secret"); Contract.Ensures(Contract.Result<HmacShaAssociation>() != null); HmacSha shaType = hmacShaAssociationTypes.FirstOrDefault(sha => sha.SecretLength == secret.Length); @@ -145,8 +145,8 @@ namespace DotNetOpenAuth.OpenId { /// True if a qualifying association could be found; false otherwise. /// </returns> internal static bool TryFindBestAssociation(Protocol protocol, bool highSecurityIsBetter, SecuritySettings securityRequirements, bool requireMatchingDHSessionType, out string associationType, out string sessionType) { - Contract.Requires<ArgumentNullException>(protocol != null); - Contract.Requires<ArgumentNullException>(securityRequirements != null); + Requires.NotNull(protocol, "protocol"); + Requires.NotNull(securityRequirements, "securityRequirements"); associationType = null; sessionType = null; @@ -186,9 +186,9 @@ namespace DotNetOpenAuth.OpenId { /// <c>true</c> if the named association and session types are compatible; otherwise, <c>false</c>. /// </returns> internal static bool IsDHSessionCompatible(Protocol protocol, string associationType, string sessionType) { - Contract.Requires<ArgumentNullException>(protocol != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType)); - Contract.Requires<ArgumentNullException>(sessionType != null); + Requires.NotNull(protocol, "protocol"); + Requires.NotNullOrEmpty(associationType, "associationType"); + Requires.NotNull(sessionType, "sessionType"); // All association types can work when no DH session is used at all. if (string.Equals(sessionType, protocol.Args.SessionType.NoEncryption, StringComparison.Ordinal)) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs index fcea327..f5cefe2 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs @@ -56,8 +56,8 @@ namespace DotNetOpenAuth.OpenId { /// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty. /// </returns> IEnumerable<IdentifierDiscoveryResult> IIdentifierDiscoveryService.Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) { - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(requestHandler != null); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(requestHandler, "requestHandler"); Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IProviderEndpoint.cs b/src/DotNetOpenAuth.OpenId/OpenId/IProviderEndpoint.cs index 5d8918d..e2a8929 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/IProviderEndpoint.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/IProviderEndpoint.cs @@ -134,8 +134,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// the extension in the request and see if a response comes back for that extension. /// </remarks> bool IProviderEndpoint.IsExtensionSupported(Type extensionType) { - Contract.Requires<ArgumentNullException>(extensionType != null); - Contract.Requires<ArgumentException>(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType)); + Requires.NotNullSubtype<IOpenIdMessageExtension>(extensionType, "extensionType"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Identifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/Identifier.cs index b54d1fc..aeb0e6b 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Identifier.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Identifier.cs @@ -103,7 +103,7 @@ namespace DotNetOpenAuth.OpenId { [SuppressMessage("Microsoft.Usage", "CA2225:OperatorOverloadsHaveNamedAlternates", Justification = "Our named alternate is Parse.")] [DebuggerStepThrough] public static implicit operator Identifier(string identifier) { - Contract.Requires<ArgumentException>(identifier == null || identifier.Length > 0); + Requires.True(identifier == null || identifier.Length > 0, "identifier"); Contract.Ensures((identifier == null) == (Contract.Result<Identifier>() == null)); if (identifier == null) { @@ -151,7 +151,7 @@ namespace DotNetOpenAuth.OpenId { /// <returns>An <see cref="Identifier"/> instance for the given value.</returns> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Some of these identifiers are not properly formatted to be Uris at this stage.")] public static Identifier Parse(string identifier) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(identifier)); + Requires.NotNullOrEmpty(identifier, "identifier"); Contract.Ensures(Contract.Result<Identifier>() != null); return Parse(identifier, false); @@ -168,7 +168,7 @@ namespace DotNetOpenAuth.OpenId { /// </returns> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Some of these identifiers are not properly formatted to be Uris at this stage.")] public static Identifier Parse(string identifier, bool serializeExactValue) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(identifier)); + Requires.NotNullOrEmpty(identifier, "identifier"); Contract.Ensures(Contract.Result<Identifier>() != null); Identifier id; @@ -214,7 +214,7 @@ namespace DotNetOpenAuth.OpenId { /// </returns> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Some of these identifiers are not properly formatted to be Uris at this stage.")] public static bool IsValid(string identifier) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(identifier)); + Requires.NotNullOrEmpty(identifier, "identifier"); return XriIdentifier.IsValidXri(identifier) || UriIdentifier.IsValidUri(identifier); } @@ -275,7 +275,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="identifier">The identifier.</param> /// <returns>Either <see cref="XriIdentifier"/> or <see cref="UriIdentifier"/>.</returns> internal static Identifier Reparse(Identifier identifier) { - Contract.Requires<ArgumentNullException>(identifier != null); + Requires.NotNull(identifier, "identifier"); Contract.Ensures(Contract.Result<Identifier>() != null); return Parse(identifier, identifier.IsDeserializedInstance); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryResult.cs b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryResult.cs index c851f24..07abf1e 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryResult.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryResult.cs @@ -49,8 +49,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="servicePriority">The service priority.</param> /// <param name="uriPriority">The URI priority.</param> private IdentifierDiscoveryResult(ProviderEndpointDescription providerEndpoint, Identifier claimedIdentifier, Identifier userSuppliedIdentifier, Identifier providerLocalIdentifier, int? servicePriority, int? uriPriority) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentNullException>(claimedIdentifier != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.NotNull(claimedIdentifier, "claimedIdentifier"); this.ProviderEndpoint = providerEndpoint.Uri; this.Capabilities = new ReadOnlyCollection<string>(providerEndpoint.Capabilities); this.Version = providerEndpoint.Version; @@ -366,7 +366,7 @@ namespace DotNetOpenAuth.OpenId { /// <c>true</c> if the extension is supported by this endpoint; otherwise, <c>false</c>. /// </returns> public bool IsExtensionSupported(IOpenIdMessageExtension extension) { - Contract.Requires<ArgumentNullException>(extension != null); + Requires.NotNull(extension, "extension"); // Consider the primary case. if (this.IsTypeUriPresent(extension.TypeUri)) { @@ -392,7 +392,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="uriPriority">The URI priority.</param> /// <returns>The created <see cref="IdentifierDiscoveryResult"/> instance</returns> internal static IdentifierDiscoveryResult CreateForProviderIdentifier(Identifier providerIdentifier, ProviderEndpointDescription providerEndpoint, int? servicePriority, int? uriPriority) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); Protocol protocol = Protocol.Lookup(providerEndpoint.Version); @@ -440,7 +440,7 @@ namespace DotNetOpenAuth.OpenId { /// <c>true</c> if the type URI is present on the specified provider endpoint; otherwise, <c>false</c>. /// </returns> internal bool IsTypeUriPresent(string typeUri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(typeUri)); + Requires.NotNullOrEmpty(typeUri, "typeUri"); return this.Capabilities.Contains(typeUri); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationRequest.cs index db69d3d..273c444 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/CheckAuthenticationRequest.cs @@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="channel">The channel. This is used only within the constructor and is not stored in a field.</param> internal CheckAuthenticationRequest(IndirectSignedResponse message, Channel channel) : base(message.Version, message.ProviderEndpoint, GetProtocolConstant(message.Version, p => p.Args.Mode.check_authentication), MessageTransport.Direct) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); // Copy all message parts from the id_res message into this one, // except for the openid.mode parameter. diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectResponseBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectResponseBase.cs index e7619bc..da6a1f6 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectResponseBase.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/DirectResponseBase.cs @@ -54,7 +54,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="responseVersion">The OpenID version of the response message.</param> /// <param name="originatingRequest">The originating request. May be null in case the request is unrecognizable and this is an error response.</param> protected DirectResponseBase(Version responseVersion, IDirectedProtocolMessage originatingRequest) { - Contract.Requires<ArgumentNullException>(responseVersion != null); + Requires.NotNull(responseVersion, "responseVersion"); this.Version = responseVersion; this.originatingRequest = originatingRequest; diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectResponseBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectResponseBase.cs index fce6028..f23d912 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectResponseBase.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectResponseBase.cs @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="mode">The value of the openid.mode parameter.</param> protected IndirectResponseBase(SignedResponseRequest request, string mode) : base(GetVersion(request), GetReturnTo(request), mode, MessageTransport.Indirect) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); this.OriginatingRequest = request; } @@ -91,7 +91,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// instead of a <see cref="NullReferenceException"/>. /// </remarks> internal static Version GetVersion(IProtocolMessage message) { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); return message.Version; } @@ -105,7 +105,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// instead of a <see cref="NullReferenceException"/>. /// </remarks> private static Uri GetReturnTo(SignedResponseRequest message) { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); ErrorUtilities.VerifyProtocol(message.ReturnTo != null, OpenIdStrings.ReturnToRequiredForResponse); return message.ReturnTo; } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectSignedResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectSignedResponse.cs index baeae16..9a60757 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectSignedResponse.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/IndirectSignedResponse.cs @@ -57,7 +57,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// </param> internal IndirectSignedResponse(SignedResponseRequest request) : base(request, Protocol.Lookup(GetVersion(request)).Args.Mode.id_res) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); this.ReturnTo = request.ReturnTo; this.ProviderEndpoint = request.Recipient.StripQueryArgumentsWithPrefix(Protocol.openid.Prefix); @@ -72,7 +72,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="channel">The channel. This is used only within the constructor and is not stored in a field.</param> internal IndirectSignedResponse(CheckAuthenticationRequest previouslySignedMessage, Channel channel) : base(GetVersion(previouslySignedMessage), previouslySignedMessage.ReturnTo, Protocol.Lookup(GetVersion(previouslySignedMessage)).Args.Mode.id_res) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); // Copy all message parts from the check_authentication message into this one, // except for the openid.mode parameter. @@ -324,7 +324,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// cannot verify the private signature made by the relying party. /// </remarks> internal string GetReturnToArgument(string key) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key)); + Requires.NotNullOrEmpty(key, "key"); ErrorUtilities.VerifyInternal(this.ReturnTo != null, "ReturnTo was expected to be required but is null."); string value; @@ -350,7 +350,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// A dictionary of the signed message parts. /// </returns> internal IDictionary<string, string> GetSignedMessageParts(Channel channel) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); ITamperResistantOpenIdMessage signedSelf = this; if (signedSelf.SignedParameterOrder == null) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs index 5b6cb05..a6303ab 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs @@ -114,8 +114,8 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="channel">The channel to use to simulate construction of the message.</param> /// <returns>The value to use for the user_setup_url parameter.</returns> private static Uri ConstructUserSetupUrl(CheckIdRequest immediateRequest, Channel channel) { - Contract.Requires<ArgumentNullException>(immediateRequest != null); - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(immediateRequest, "immediateRequest"); + Requires.NotNull(channel, "channel"); ErrorUtilities.VerifyInternal(immediateRequest.Immediate, "Only immediate requests should be sent here."); var setupRequest = new CheckIdRequest(immediateRequest.Version, immediateRequest.Recipient, AuthenticationRequestMode.Setup); @@ -132,7 +132,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="request">The request that we're responding to.</param> /// <returns>The value of the openid.mode parameter to use.</returns> private static string GetMode(SignedResponseRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); Protocol protocol = Protocol.Lookup(request.Version); return request.Immediate ? protocol.Args.Mode.setup_needed : protocol.Args.Mode.cancel; diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/RequestBase.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/RequestBase.cs index 8e4cb9d..a24c7db 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/RequestBase.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/RequestBase.cs @@ -49,8 +49,8 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <param name="mode">The value for the openid.mode parameter.</param> /// <param name="transport">A value indicating whether the message will be transmitted directly or indirectly.</param> protected RequestBase(Version version, Uri providerEndpoint, string mode, MessageTransport transport) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(mode)); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.NotNullOrEmpty(mode, "mode"); this.Recipient = providerEndpoint; this.Mode = mode; @@ -178,7 +178,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// instead of a <see cref="NullReferenceException"/>. /// </remarks> protected static string GetProtocolConstant(Version protocolVersion, Func<Protocol, string> mode) { - Contract.Requires<ArgumentNullException>(protocolVersion != null); + Requires.NotNull(protocolVersion, "protocolVersion"); return mode(Protocol.Lookup(protocolVersion)); } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/SignedResponseRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/SignedResponseRequest.cs index b1c9283..3719f96 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/SignedResponseRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/SignedResponseRequest.cs @@ -144,7 +144,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// when and if a positive assertion comes back from the Provider. /// </remarks> internal void AddReturnToArguments(IEnumerable<KeyValuePair<string, string>> keysValues) { - Contract.Requires<ArgumentNullException>(keysValues != null); + Requires.NotNull(keysValues, "keysValues"); ErrorUtilities.VerifyOperation(this.ReturnTo != null, OpenIdStrings.ReturnToRequiredForOperation); UriBuilder returnToBuilder = new UriBuilder(this.ReturnTo); returnToBuilder.AppendAndReplaceQueryArgs(keysValues); @@ -175,7 +175,7 @@ namespace DotNetOpenAuth.OpenId.Messages { /// </param> /// <returns>checkid_immediate or checkid_setup</returns> private static string GetMode(Version version, AuthenticationRequestMode mode) { - Contract.Requires<ArgumentNullException>(version != null); + Requires.NotNull(version, "version"); Protocol protocol = Protocol.Lookup(version); return mode == AuthenticationRequestMode.Immediate ? protocol.Args.Mode.checkid_immediate : protocol.Args.Mode.checkid_setup; diff --git a/src/DotNetOpenAuth.OpenId/OpenId/NoDiscoveryIdentifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/NoDiscoveryIdentifier.cs index 7dc2c0c..d1704fc 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/NoDiscoveryIdentifier.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/NoDiscoveryIdentifier.cs @@ -29,7 +29,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="claimSsl">Whether this Identifier should claim to be SSL-secure, although no discovery will never generate service endpoints anyway.</param> internal NoDiscoveryIdentifier(Identifier wrappedIdentifier, bool claimSsl) : base(wrappedIdentifier.OriginalString, claimSsl) { - Contract.Requires<ArgumentNullException>(wrappedIdentifier != null); + Requires.NotNull(wrappedIdentifier, "wrappedIdentifier"); this.wrappedIdentifier = wrappedIdentifier; } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs index 95b3427..b7f857e 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs @@ -47,7 +47,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="message">The message.</param> /// <returns>The OpenID protocol instance.</returns> internal static Protocol GetProtocol(this IProtocolMessage message) { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); return Protocol.Lookup(message.Version); } @@ -116,8 +116,8 @@ namespace DotNetOpenAuth.OpenId { /// <returns>The fully-qualified realm.</returns> [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "DotNetOpenAuth.OpenId.Realm", Justification = "Using ctor for validation.")] internal static UriBuilder GetResolvedRealm(Page page, string realm, HttpRequestInfo requestContext) { - Contract.Requires<ArgumentNullException>(page != null); - Contract.Requires<ArgumentNullException>(requestContext != null); + Requires.NotNull(page, "page"); + Requires.NotNull(requestContext, "requestContext"); // Allow for *. realm notation, as well as ASP.NET ~/ shortcuts. @@ -159,7 +159,7 @@ namespace DotNetOpenAuth.OpenId { /// can plug in. /// </remarks> internal static IList<IOpenIdExtensionFactory> GetExtensionFactories(this Channel channel) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); var extensionsBindingElement = channel.BindingElements.OfType<ExtensionsBindingElement>().SingleOrDefault(); ErrorUtilities.VerifyOperation(extensionsBindingElement != null, OpenIdStrings.UnsupportedChannelConfiguration); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs index 9f1e0d7..9f996a5 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdXrdsHelper.cs @@ -26,7 +26,7 @@ namespace DotNetOpenAuth.OpenId { /// or for Provider's to perform RP discovery/verification as part of authentication. /// </remarks> internal static IEnumerable<RelyingPartyEndpointDescription> FindRelyingPartyReceivingEndpoints(this XrdsDocument xrds) { - Contract.Requires<ArgumentNullException>(xrds != null); + Requires.NotNull(xrds, "xrds"); Contract.Ensures(Contract.Result<IEnumerable<RelyingPartyEndpointDescription>>() != null); return from service in xrds.FindReturnToServices() @@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="xrds">The XrdsDocument to search.</param> /// <returns>A sequence of the icon URLs in preferred order.</returns> internal static IEnumerable<Uri> FindRelyingPartyIcons(this XrdsDocument xrds) { - Contract.Requires<ArgumentNullException>(xrds != null); + Requires.NotNull(xrds, "xrds"); Contract.Ensures(Contract.Result<IEnumerable<Uri>>() != null); return from xrd in xrds.XrdElements @@ -57,7 +57,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="xrds">The XrdsDocument instance to use in this process.</param> /// <returns>A sequence of service elements.</returns> private static IEnumerable<ServiceElement> FindReturnToServices(this XrdsDocument xrds) { - Contract.Requires<ArgumentNullException>(xrds != null); + Requires.NotNull(xrds, "xrds"); Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null); return from xrd in xrds.XrdElements diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Protocol.cs b/src/DotNetOpenAuth.OpenId/OpenId/Protocol.cs index 5aacfd2..a651f3c 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Protocol.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Protocol.cs @@ -157,7 +157,7 @@ namespace DotNetOpenAuth.OpenId { /// of an incoming OpenID <i>indirect</i> message or <i>direct request</i>. /// </summary> internal static Protocol Detect(IDictionary<string, string> query) { - Contract.Requires<ArgumentNullException>(query != null); + Requires.NotNull(query, "query"); return query.ContainsKey(V20.openid.ns) ? V20 : V11; } /// <summary> @@ -165,7 +165,7 @@ namespace DotNetOpenAuth.OpenId { /// of an incoming OpenID <i>direct</i> response message. /// </summary> internal static Protocol DetectFromDirectResponse(IDictionary<string, string> query) { - Contract.Requires<ArgumentNullException>(query != null); + Requires.NotNull(query, "query"); return query.ContainsKey(V20.openidnp.ns) ? V20 : V11; } /// <summary> @@ -173,7 +173,7 @@ namespace DotNetOpenAuth.OpenId { /// of XRDS Service Type URIs included for some service. /// </summary> internal static Protocol Detect(IEnumerable<string> serviceTypeURIs) { - Contract.Requires<ArgumentNullException>(serviceTypeURIs != null); + Requires.NotNull(serviceTypeURIs, "serviceTypeURIs"); return FindBestVersion(p => p.OPIdentifierServiceTypeURI, serviceTypeURIs) ?? FindBestVersion(p => p.ClaimedIdentifierServiceTypeURI, serviceTypeURIs) ?? FindBestVersion(p => p.RPReturnToTypeURI, serviceTypeURIs); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IAuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IAuthenticationRequest.cs index 4942397..1045282 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IAuthenticationRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IAuthenticationRequest.cs @@ -176,8 +176,8 @@ namespace DotNetOpenAuth.OpenId.Provider { set { IAuthenticationRequest req = this; - Contract.Requires<InvalidOperationException>(!req.IsDelegatedIdentifier, OpenIdStrings.ClaimedIdentifierCannotBeSetOnDelegatedAuthentication); - Contract.Requires<InvalidOperationException>(!req.IsDirectedIdentity || !(req.LocalIdentifier != null && req.LocalIdentifier != value), OpenIdStrings.IdentifierSelectRequiresMatchingIdentifiers); + Requires.ValidState(!req.IsDelegatedIdentifier, OpenIdStrings.ClaimedIdentifierCannotBeSetOnDelegatedAuthentication); + Requires.ValidState(!req.IsDirectedIdentity || !(req.LocalIdentifier != null && req.LocalIdentifier != value), OpenIdStrings.IdentifierSelectRequiresMatchingIdentifiers); } } @@ -293,8 +293,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// request before the <see cref="IAuthenticationRequest.ClaimedIdentifier"/> property is set. /// </exception> void IAuthenticationRequest.SetClaimedIdentifierFragment(string fragment) { - Contract.Requires<InvalidOperationException>(!(((IAuthenticationRequest)this).IsDirectedIdentity && ((IAuthenticationRequest)this).ClaimedIdentifier == null), OpenIdStrings.ClaimedIdentifierMustBeSetFirst); - Contract.Requires<InvalidOperationException>(!(((IAuthenticationRequest)this).ClaimedIdentifier is XriIdentifier), OpenIdStrings.FragmentNotAllowedOnXRIs); + Requires.ValidState(!(((IAuthenticationRequest)this).IsDirectedIdentity && ((IAuthenticationRequest)this).ClaimedIdentifier == null), OpenIdStrings.ClaimedIdentifierMustBeSetFirst); + Requires.ValidState(!(((IAuthenticationRequest)this).ClaimedIdentifier is XriIdentifier), OpenIdStrings.FragmentNotAllowedOnXRIs); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs index 4064ef1..809c0f3 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs @@ -193,7 +193,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para> /// </remarks> RelyingPartyDiscoveryResult IHostProcessedRequest.IsReturnUrlDiscoverable(IDirectWebRequestHandler webRequestHandler) { - Contract.Requires<ArgumentNullException>(webRequestHandler != null); + Requires.NotNull(webRequestHandler, "webRequestHandler"); throw new System.NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs index 01b4ac8..9750625 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs @@ -74,7 +74,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// incompatible with each other. /// </remarks> void IProviderBehavior.ApplySecuritySettings(ProviderSecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(securitySettings, "securitySettings"); throw new System.NotImplementedException(); } @@ -92,7 +92,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// itself as that instance may be shared across many requests. /// </remarks> bool IProviderBehavior.OnIncomingRequest(IRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); throw new System.NotImplementedException(); } @@ -105,7 +105,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// from handling it; <c>false</c> to allow other behaviors to process this request. /// </returns> bool IProviderBehavior.OnOutgoingResponse(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); throw new System.NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IRequest.cs index 1cb1a4b..1870bfe 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IRequest.cs @@ -107,7 +107,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// </summary> /// <param name="extension">The extension to add to the response message.</param> void IRequest.AddResponseExtension(IOpenIdMessageExtension extension) { - Contract.Requires<ArgumentNullException>(extension != null); + Requires.NotNull(extension, "extension"); throw new NotImplementedException(); } @@ -140,7 +140,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// An instance of the extension initialized with values passed in with the request. /// </returns> IOpenIdMessageExtension IRequest.GetExtension(Type extensionType) { - Contract.Requires<ArgumentNullException>(extensionType != null); + Requires.NotNull(extensionType, "extensionType"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ProviderEndpointDescription.cs b/src/DotNetOpenAuth.OpenId/OpenId/ProviderEndpointDescription.cs index 6514ffd..092ec22 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ProviderEndpointDescription.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ProviderEndpointDescription.cs @@ -29,8 +29,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="providerEndpoint">The OpenID Provider endpoint URL.</param> /// <param name="openIdVersion">The OpenID version supported by this particular endpoint.</param> internal ProviderEndpointDescription(Uri providerEndpoint, Version openIdVersion) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentNullException>(openIdVersion != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.NotNull(openIdVersion, "openIdVersion"); this.Uri = providerEndpoint; this.Version = openIdVersion; @@ -43,8 +43,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="providerEndpoint">The URI the provider listens on for OpenID requests.</param> /// <param name="serviceTypeURIs">The set of services offered by this endpoint.</param> internal ProviderEndpointDescription(Uri providerEndpoint, IEnumerable<string> serviceTypeURIs) { - Contract.Requires<ArgumentNullException>(providerEndpoint != null); - Contract.Requires<ArgumentNullException>(serviceTypeURIs != null); + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.NotNull(serviceTypeURIs, "serviceTypeURIs"); this.Uri = providerEndpoint; this.Capabilities = new ReadOnlyCollection<string>(serviceTypeURIs.ToList()); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs index c00653b..685b922 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs @@ -75,7 +75,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="realmUrl">The realm URL to use in the new instance.</param> [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification = "Not all realms are valid URLs (because of wildcards).")] public Realm(string realmUrl) { - Contract.Requires<ArgumentNullException>(realmUrl != null); // not non-zero check so we throw UriFormatException later + Requires.NotNull(realmUrl, "realmUrl"); // not non-zero check so we throw UriFormatException later this.DomainWildcard = Regex.IsMatch(realmUrl, WildcardDetectionPattern); this.uri = new Uri(Regex.Replace(realmUrl, WildcardDetectionPattern, m => m.Groups[1].Value)); if (!this.uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) && @@ -90,7 +90,7 @@ namespace DotNetOpenAuth.OpenId { /// </summary> /// <param name="realmUrl">The realm URL of the Relying Party.</param> public Realm(Uri realmUrl) { - Contract.Requires<ArgumentNullException>(realmUrl != null); + Requires.NotNull(realmUrl, "realmUrl"); this.uri = realmUrl; if (!this.uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) && !this.uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) { @@ -123,7 +123,7 @@ namespace DotNetOpenAuth.OpenId { /// </remarks> public static Realm AutoDetect { get { - Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + Requires.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); Contract.Ensures(Contract.Result<Realm>() != null); HttpRequestInfo requestInfo = new HttpRequestInfo(HttpContext.Current.Request); @@ -489,7 +489,7 @@ namespace DotNetOpenAuth.OpenId { /// when we should be throwing an <see cref="ArgumentNullException"/>. /// </remarks> private static string SafeUriBuilderToString(UriBuilder realmUriBuilder) { - Contract.Requires<ArgumentNullException>(realmUriBuilder != null); + Requires.NotNull(realmUriBuilder, "realmUriBuilder"); // Note: we MUST use ToString. Uri property throws if wildcard is present. // Note that Uri.ToString() should generally be avoided, but UriBuilder.ToString() diff --git a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequestContract.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequestContract.cs index cd36cc7..fa16c41 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequestContract.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequestContract.cs @@ -73,26 +73,26 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } void IAuthenticationRequest.AddCallbackArguments(IDictionary<string, string> arguments) { - Contract.Requires<ArgumentNullException>(arguments != null); - Contract.Requires<ArgumentException>(arguments.Keys.All(k => !String.IsNullOrEmpty(k))); - Contract.Requires<ArgumentException>(arguments.Values.All(v => v != null)); + Requires.NotNull(arguments, "arguments"); + Requires.True(arguments.Keys.All(k => !String.IsNullOrEmpty(k)), "arguments"); + Requires.True(arguments.Values.All(v => v != null), "arguments"); throw new NotImplementedException(); } void IAuthenticationRequest.AddCallbackArguments(string key, string value) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key)); - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNullOrEmpty(key, "key"); + Requires.NotNull(value, "value"); throw new NotImplementedException(); } void IAuthenticationRequest.SetCallbackArgument(string key, string value) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key)); - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNullOrEmpty(key, "key"); + Requires.NotNull(value, "value"); throw new NotImplementedException(); } void IAuthenticationRequest.AddExtension(IOpenIdMessageExtension extension) { - Contract.Requires<ArgumentNullException>(extension != null); + Requires.NotNull(extension, "extension"); throw new NotImplementedException(); } @@ -101,8 +101,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } void IAuthenticationRequest.SetUntrustedCallbackArgument(string key, string value) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(key)); - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNullOrEmpty(key, "key"); + Requires.NotNull(value, "value"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationResponse.cs index a24220f..7b55f65 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationResponse.cs @@ -367,7 +367,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <para>Note that these values are NOT protected against tampering in transit.</para> /// </remarks> string IAuthenticationResponse.GetCallbackArgument(string key) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(key)); + Requires.NotNullOrEmpty(key, "key"); throw new NotImplementedException(); } @@ -432,8 +432,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// have not been tampered with since the Provider sent the message.</para> /// </remarks> IOpenIdMessageExtension IAuthenticationResponse.GetExtension(Type extensionType) { - Contract.Requires<ArgumentNullException>(extensionType != null); - Contract.Requires<ArgumentException>(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType)); + Requires.NotNullSubtype<IOpenIdMessageExtension>(extensionType, "extensionType"); ////ErrorUtilities.VerifyArgument(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType), string.Format(CultureInfo.CurrentCulture, OpenIdStrings.TypeMustImplementX, typeof(IOpenIdMessageExtension).FullName)); throw new NotImplementedException(); } @@ -485,8 +484,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// have not been tampered with since the Provider sent the message.</para> /// </remarks> IOpenIdMessageExtension IAuthenticationResponse.GetUntrustedExtension(Type extensionType) { - Contract.Requires<ArgumentNullException>(extensionType != null); - Contract.Requires<ArgumentException>(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType)); + Requires.NotNullSubtype<IOpenIdMessageExtension>(extensionType, "extensionType"); ////ErrorUtilities.VerifyArgument(typeof(IOpenIdMessageExtension).IsAssignableFrom(extensionType), string.Format(CultureInfo.CurrentCulture, OpenIdStrings.TypeMustImplementX, typeof(IOpenIdMessageExtension).FullName)); throw new NotImplementedException(); } @@ -506,7 +504,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// used to make a security-sensitive decision. /// </remarks> string IAuthenticationResponse.GetUntrustedCallbackArgument(string key) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(key)); + Requires.NotNullOrEmpty(key, "key"); throw new NotImplementedException(); } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IRelyingPartyBehavior.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IRelyingPartyBehavior.cs index 1bfa0db..28cad6d 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IRelyingPartyBehavior.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IRelyingPartyBehavior.cs @@ -64,7 +64,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// incompatible with each other. /// </remarks> void IRelyingPartyBehavior.ApplySecuritySettings(RelyingPartySecuritySettings securitySettings) { - Contract.Requires<ArgumentNullException>(securitySettings != null); + Requires.NotNull(securitySettings, "securitySettings"); } /// <summary> @@ -76,7 +76,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// without malfunctioning. /// </remarks> void IRelyingPartyBehavior.OnOutgoingAuthenticationRequest(IAuthenticationRequest request) { - Contract.Requires<ArgumentNullException>(request != null); + Requires.NotNull(request, "request"); } /// <summary> @@ -84,7 +84,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="assertion">The positive assertion.</param> void IRelyingPartyBehavior.OnIncomingPositiveAssertion(IAuthenticationResponse assertion) { - Contract.Requires<ArgumentNullException>(assertion != null); + Requires.NotNull(assertion, "assertion"); } #endregion diff --git a/src/DotNetOpenAuth.OpenId/OpenId/RelyingPartyDescription.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingPartyDescription.cs index 7926e8f..ab0fd13 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/RelyingPartyDescription.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingPartyDescription.cs @@ -28,8 +28,8 @@ namespace DotNetOpenAuth.OpenId { /// The Type URIs of supported services advertised on a relying party's XRDS document. /// </param> internal RelyingPartyEndpointDescription(Uri returnTo, string[] supportedServiceTypeUris) { - Contract.Requires<ArgumentNullException>(returnTo != null); - Contract.Requires<ArgumentNullException>(supportedServiceTypeUris != null); + Requires.NotNull(returnTo, "returnTo"); + Requires.NotNull(supportedServiceTypeUris, "supportedServiceTypeUris"); this.ReturnToEndpoint = returnTo; this.Protocol = GetProtocolFromServices(supportedServiceTypeUris); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/SecuritySettings.cs b/src/DotNetOpenAuth.OpenId/OpenId/SecuritySettings.cs index 26f6d2a..a083cc6 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/SecuritySettings.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/SecuritySettings.cs @@ -88,7 +88,7 @@ namespace DotNetOpenAuth.OpenId { /// <c>true</c> if the association is permitted given the security requirements; otherwise, <c>false</c>. /// </returns> internal bool IsAssociationInPermittedRange(Association association) { - Contract.Requires<ArgumentNullException>(association != null); + Requires.NotNull(association, "association"); return association.HashBitLength >= this.MinimumHashBitLength && association.HashBitLength <= this.MaximumHashBitLength; } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/UriIdentifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/UriIdentifier.cs index 3737135..aa72869 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/UriIdentifier.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/UriIdentifier.cs @@ -99,7 +99,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="uri">The value this identifier will represent.</param> internal UriIdentifier(string uri) : this(uri, false) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uri)); + Requires.NotNullOrEmpty(uri, "uri"); } /// <summary> @@ -109,7 +109,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="requireSslDiscovery">if set to <c>true</c> [require SSL discovery].</param> internal UriIdentifier(string uri, bool requireSslDiscovery) : base(uri, requireSslDiscovery) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uri)); + Requires.NotNullOrEmpty(uri, "uri"); Uri canonicalUri; bool schemePrepended; if (!TryCanonicalize(uri, out canonicalUri, requireSslDiscovery, out schemePrepended)) { @@ -137,7 +137,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="requireSslDiscovery">if set to <c>true</c> [require SSL discovery].</param> internal UriIdentifier(Uri uri, bool requireSslDiscovery) : base(uri != null ? uri.OriginalString : null, requireSslDiscovery) { - Contract.Requires<ArgumentNullException>(uri != null); + Requires.NotNull(uri, "uri"); string uriAsString = uri.OriginalString; if (schemeSubstitution) { @@ -422,7 +422,7 @@ namespace DotNetOpenAuth.OpenId { /// require network access are also done, such as lower-casing the hostname in the URI. /// </remarks> private static bool TryCanonicalize(string uri, out Uri canonicalUri, bool forceHttpsDefaultScheme, out bool schemePrepended) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(uri)); + Requires.NotNullOrEmpty(uri, "uri"); canonicalUri = null; try { @@ -454,7 +454,7 @@ namespace DotNetOpenAuth.OpenId { /// </remarks> [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "The user will see the result of this operation and they want to see it in lower case.")] private static bool TryCanonicalize(string uri, out Uri canonicalUri) { - Contract.Requires<ArgumentNullException>(uri != null); + Requires.NotNull(uri, "uri"); if (schemeSubstitution) { UriBuilder uriBuilder = new UriBuilder(uri); @@ -475,7 +475,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="normal">The ordinary URL or scheme name.</param> /// <returns>The non-compressing equivalent scheme or URL for the given value.</returns> private static string NormalSchemeToSpecialRoundTrippingScheme(string normal) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(normal)); + Requires.NotNullOrEmpty(normal, "normal"); Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>())); ErrorUtilities.VerifyInternal(schemeSubstitution, "Wrong schemeSubstitution value."); @@ -503,7 +503,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="schemePrepended">if set to <c>true</c>, the scheme was prepended during normalization.</param> /// <returns>The somewhat normalized URL.</returns> private static string DoSimpleCanonicalize(string uri, bool forceHttpsDefaultScheme, out bool schemePrepended) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(uri)); + Requires.NotNullOrEmpty(uri, "uri"); schemePrepended = false; uri = uri.Trim(); @@ -546,7 +546,7 @@ namespace DotNetOpenAuth.OpenId { /// </summary> /// <param name="value">The value.</param> internal SimpleUri(string value) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(value)); + Requires.NotNullOrEmpty(value, "value"); bool schemePrepended; value = DoSimpleCanonicalize(value, false, out schemePrepended); @@ -664,7 +664,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="path">The path to normalize.</param> /// <returns>The given path, with exactly those characters escaped which should be.</returns> private static string NormalizePathEscaping(string path) { - Contract.Requires<ArgumentNullException>(path != null); + Requires.NotNull(path, "path"); string[] segments = path.Split('/'); for (int i = 0; i < segments.Length; i++) { @@ -695,7 +695,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="standardScheme">The standard scheme that this parser will be subverting.</param> public NonPathCompressingUriParser(string standardScheme) : base(GenericUriParserOptions.DontCompressPath | GenericUriParserOptions.IriParsing | GenericUriParserOptions.Idn) { - Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(standardScheme)); + Requires.NotNullOrEmpty(standardScheme, "standardScheme"); this.standardScheme = standardScheme; } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs index d80c59e..52bb92e 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs @@ -72,8 +72,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="requestHandler">The request handler.</param> /// <returns>The XRDS document.</returns> private static XrdsDocument DownloadXrds(XriIdentifier identifier, IDirectWebRequestHandler requestHandler) { - Contract.Requires<ArgumentNullException>(identifier != null); - Contract.Requires<ArgumentNullException>(requestHandler != null); + Requires.NotNull(identifier, "identifier"); + Requires.NotNull(requestHandler, "requestHandler"); Contract.Ensures(Contract.Result<XrdsDocument>() != null); XrdsDocument doc; using (var xrdsResponse = Yadis.Request(requestHandler, GetXrdsUrl(identifier), identifier.IsDiscoverySecureEndToEnd)) { diff --git a/src/DotNetOpenAuth.OpenId/OpenId/XriIdentifier.cs b/src/DotNetOpenAuth.OpenId/OpenId/XriIdentifier.cs index b31d577..28460f1 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/XriIdentifier.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/XriIdentifier.cs @@ -44,8 +44,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="xri">The string value of the XRI.</param> internal XriIdentifier(string xri) : this(xri, false) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(xri)); - Contract.Requires<FormatException>(IsValidXri(xri), OpenIdStrings.InvalidXri); + Requires.NotNullOrEmpty(xri, "xri"); + Requires.Format(IsValidXri(xri), OpenIdStrings.InvalidXri); } /// <summary> @@ -58,8 +58,8 @@ namespace DotNetOpenAuth.OpenId { /// </param> internal XriIdentifier(string xri, bool requireSsl) : base(xri, requireSsl) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(xri)); - Contract.Requires<FormatException>(IsValidXri(xri), OpenIdStrings.InvalidXri); + Requires.NotNullOrEmpty(xri, "xri"); + Requires.Format(IsValidXri(xri), OpenIdStrings.InvalidXri); Contract.Assume(xri != null); // Proven by IsValidXri this.OriginalXri = xri; this.canonicalXri = CanonicalizeXri(xri); @@ -131,7 +131,7 @@ namespace DotNetOpenAuth.OpenId { /// <c>true</c> if the given string constitutes a valid XRI; otherwise, <c>false</c>. /// </returns> internal static bool IsValidXri(string xri) { - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(xri)); + Requires.NotNullOrEmpty(xri, "xri"); xri = xri.Trim(); // TODO: better validation code here @@ -182,7 +182,7 @@ namespace DotNetOpenAuth.OpenId { /// <returns>The canonicalized form of the XRI.</returns> /// <remarks>The canonical form, per the OpenID spec, is no scheme and no whitespace on either end.</remarks> private static string CanonicalizeXri(string xri) { - Contract.Requires<ArgumentNullException>(xri != null); + Requires.NotNull(xri, "xri"); Contract.Ensures(Contract.Result<string>() != null); xri = xri.Trim(); if (xri.StartsWith(XriScheme, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/DotNetOpenAuth.OpenId/OpenIdXrdsHelper.cs b/src/DotNetOpenAuth.OpenId/OpenIdXrdsHelper.cs index 6b2fb54..617c467 100644 --- a/src/DotNetOpenAuth.OpenId/OpenIdXrdsHelper.cs +++ b/src/DotNetOpenAuth.OpenId/OpenIdXrdsHelper.cs @@ -28,9 +28,9 @@ namespace DotNetOpenAuth.OpenId { /// A sequence of OpenID Providers that can assert ownership of the <paramref name="claimedIdentifier"/>. /// </returns> internal static IEnumerable<IdentifierDiscoveryResult> CreateServiceEndpoints(this IEnumerable<XrdElement> xrds, UriIdentifier claimedIdentifier, UriIdentifier userSuppliedIdentifier) { - Contract.Requires<ArgumentNullException>(xrds != null); - Contract.Requires<ArgumentNullException>(claimedIdentifier != null); - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); + Requires.NotNull(xrds, "xrds"); + Requires.NotNull(claimedIdentifier, "claimedIdentifier"); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); var endpoints = new List<IdentifierDiscoveryResult>(); @@ -50,8 +50,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="userSuppliedIdentifier">The user-supplied i-name that was used to discover this XRDS document.</param> /// <returns>A sequence of OpenID Providers that can assert ownership of the canonical ID given in this document.</returns> internal static IEnumerable<IdentifierDiscoveryResult> CreateServiceEndpoints(this IEnumerable<XrdElement> xrds, XriIdentifier userSuppliedIdentifier) { - Contract.Requires<ArgumentNullException>(xrds != null); - Contract.Requires<ArgumentNullException>(userSuppliedIdentifier != null); + Requires.NotNull(xrds, "xrds"); + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); var endpoints = new List<IdentifierDiscoveryResult>(); @@ -69,8 +69,8 @@ namespace DotNetOpenAuth.OpenId { /// <param name="opIdentifier">The OP Identifier entered (and resolved) by the user. Essentially the user-supplied identifier.</param> /// <returns>A sequence of the providers that can offer directed identity services.</returns> private static IEnumerable<IdentifierDiscoveryResult> GenerateOPIdentifierServiceEndpoints(this IEnumerable<XrdElement> xrds, Identifier opIdentifier) { - Contract.Requires<ArgumentNullException>(xrds != null); - Contract.Requires<ArgumentNullException>(opIdentifier != null); + Requires.NotNull(xrds, "xrds"); + Requires.NotNull(opIdentifier, "opIdentifier"); Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); return from service in xrds.FindOPIdentifierServices() from uri in service.UriElements @@ -90,8 +90,8 @@ namespace DotNetOpenAuth.OpenId { /// A sequence of the providers that can assert ownership of the given identifier. /// </returns> private static IEnumerable<IdentifierDiscoveryResult> GenerateClaimedIdentifierServiceEndpoints(this IEnumerable<XrdElement> xrds, UriIdentifier claimedIdentifier, UriIdentifier userSuppliedIdentifier) { - Contract.Requires<ArgumentNullException>(xrds != null); - Contract.Requires<ArgumentNullException>(claimedIdentifier != null); + Requires.NotNull(xrds, "xrds"); + Requires.NotNull(claimedIdentifier, "claimedIdentifier"); Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); return from service in xrds.FindClaimedIdentifierServices() @@ -110,7 +110,7 @@ namespace DotNetOpenAuth.OpenId { /// <returns>A sequence of the providers that can assert ownership of the given identifier.</returns> private static IEnumerable<IdentifierDiscoveryResult> GenerateClaimedIdentifierServiceEndpoints(this IEnumerable<XrdElement> xrds, XriIdentifier userSuppliedIdentifier) { // Cannot use code contracts because this method uses yield return. - ////Contract.Requires<ArgumentNullException>(xrds != null); + ////Requires.NotNull(xrds, "xrds"); ////Contract.Ensures(Contract.Result<IEnumerable<IdentifierDiscoveryResult>>() != null); ErrorUtilities.VerifyArgumentNotNull(xrds, "xrds"); @@ -137,7 +137,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="xrds">The XrdsDocument instance to use in this process.</param> /// <returns>A sequence of service elements.</returns> private static IEnumerable<ServiceElement> FindOPIdentifierServices(this IEnumerable<XrdElement> xrds) { - Contract.Requires<ArgumentNullException>(xrds != null); + Requires.NotNull(xrds, "xrds"); Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null); return from xrd in xrds @@ -152,7 +152,7 @@ namespace DotNetOpenAuth.OpenId { /// <param name="xrds">The XrdsDocument instance to use in this process.</param> /// <returns>A sequence of the services offered.</returns> private static IEnumerable<ServiceElement> FindClaimedIdentifierServices(this IEnumerable<XrdElement> xrds) { - Contract.Requires<ArgumentNullException>(xrds != null); + Requires.NotNull(xrds, "xrds"); Contract.Ensures(Contract.Result<IEnumerable<ServiceElement>>() != null); return from xrd in xrds diff --git a/src/DotNetOpenAuth.OpenId/Xrds/TypeElement.cs b/src/DotNetOpenAuth.OpenId/Xrds/TypeElement.cs index c413629..e1ad188 100644 --- a/src/DotNetOpenAuth.OpenId/Xrds/TypeElement.cs +++ b/src/DotNetOpenAuth.OpenId/Xrds/TypeElement.cs @@ -20,8 +20,8 @@ namespace DotNetOpenAuth.Xrds { /// <param name="parent">The parent.</param> public TypeElement(XPathNavigator typeElement, ServiceElement parent) : base(typeElement, parent) { - Contract.Requires<ArgumentNullException>(typeElement != null); - Contract.Requires<ArgumentNullException>(parent != null); + Requires.NotNull(typeElement, "typeElement"); + Requires.NotNull(parent, "parent"); } /// <summary> diff --git a/src/DotNetOpenAuth.OpenId/Xrds/XrdsNode.cs b/src/DotNetOpenAuth.OpenId/Xrds/XrdsNode.cs index 39bd9b9..7a27a9c 100644 --- a/src/DotNetOpenAuth.OpenId/Xrds/XrdsNode.cs +++ b/src/DotNetOpenAuth.OpenId/Xrds/XrdsNode.cs @@ -31,8 +31,8 @@ namespace DotNetOpenAuth.Xrds { /// <param name="node">The node represented by this instance.</param> /// <param name="parentNode">The parent node.</param> protected XrdsNode(XPathNavigator node, XrdsNode parentNode) { - Contract.Requires<ArgumentNullException>(node != null); - Contract.Requires<ArgumentNullException>(parentNode != null); + Requires.NotNull(node, "node"); + Requires.NotNull(parentNode, "parentNode"); this.Node = node; this.ParentNode = parentNode; @@ -44,8 +44,8 @@ namespace DotNetOpenAuth.Xrds { /// </summary> /// <param name="document">The document's root node, which this instance represents.</param> protected XrdsNode(XPathNavigator document) { - Contract.Requires<ArgumentNullException>(document != null); - Contract.Requires<ArgumentException>(document.NameTable != null); + Requires.NotNull(document, "document"); + Requires.True(document.NameTable != null, null); this.Node = document; this.XmlNamespaceResolver = new XmlNamespaceManager(document.NameTable); diff --git a/src/DotNetOpenAuth.OpenId/Yadis/HtmlParser.cs b/src/DotNetOpenAuth.OpenId/Yadis/HtmlParser.cs index a6b64c1..9002acb 100644 --- a/src/DotNetOpenAuth.OpenId/Yadis/HtmlParser.cs +++ b/src/DotNetOpenAuth.OpenId/Yadis/HtmlParser.cs @@ -98,8 +98,8 @@ namespace DotNetOpenAuth.Yadis { /// <param name="attribute">The attribute.</param> /// <returns>A filtered sequence of attributes.</returns> internal static IEnumerable<T> WithAttribute<T>(this IEnumerable<T> sequence, string attribute) where T : HtmlControl { - Contract.Requires<ArgumentNullException>(sequence != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(attribute)); + Requires.NotNull(sequence, "sequence"); + Requires.NotNullOrEmpty(attribute, "attribute"); return sequence.Where(tag => tag.Attributes[attribute] != null); } diff --git a/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs index 0f46c5e..955f2f4 100644 --- a/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs +++ b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs @@ -135,8 +135,8 @@ namespace DotNetOpenAuth.Yadis { /// <param name="acceptTypes">The value of the Accept HTTP header to include in the request.</param> /// <returns>The HTTP response retrieved from the request.</returns> internal static IncomingWebResponse Request(IDirectWebRequestHandler requestHandler, Uri uri, bool requireSsl, params string[] acceptTypes) { - Contract.Requires<ArgumentNullException>(requestHandler != null); - Contract.Requires<ArgumentNullException>(uri != null); + Requires.NotNull(requestHandler, "requestHandler"); + Requires.NotNull(uri, "uri"); Contract.Ensures(Contract.Result<IncomingWebResponse>() != null); Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null); diff --git a/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/SelectorInfoCardButton.cs b/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/SelectorInfoCardButton.cs index c5dda1c..863c90a 100644 --- a/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/SelectorInfoCardButton.cs +++ b/src/DotNetOpenAuth.OpenIdInfoCard.UI/OpenId/RelyingParty/SelectorInfoCardButton.cs @@ -43,7 +43,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } set { - Contract.Requires<ArgumentNullException>(value != null); + Requires.NotNull(value, "value"); if (this.infoCardSelector != null) { Logger.Library.WarnFormat("{0}.InfoCardSelector property is being set multiple times.", GetType().Name); } diff --git a/src/DotNetOpenAuth.Test/CoordinatorBase.cs b/src/DotNetOpenAuth.Test/CoordinatorBase.cs index f25964c..84d0ff1 100644 --- a/src/DotNetOpenAuth.Test/CoordinatorBase.cs +++ b/src/DotNetOpenAuth.Test/CoordinatorBase.cs @@ -18,8 +18,8 @@ namespace DotNetOpenAuth.Test { private Action<T2> party2Action; protected CoordinatorBase(Action<T1> party1Action, Action<T2> party2Action) { - Contract.Requires<ArgumentNullException>(party1Action != null); - Contract.Requires<ArgumentNullException>(party2Action != null); + Requires.NotNull(party1Action, "party1Action"); + Requires.NotNull(party2Action, "party2Action"); this.party1Action = party1Action; this.party2Action = party2Action; diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj index 1a99152..4544ebe 100644 --- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj +++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj @@ -5,7 +5,7 @@ <ProjectRoot Condition="'$(ProjectRoot)' == ''">$(MSBuildProjectDirectory)\..\..\</ProjectRoot> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <CodeContractsAssemblyMode>1</CodeContractsAssemblyMode> + <CodeContractsAssemblyMode>0</CodeContractsAssemblyMode> </PropertyGroup> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.props" /> <PropertyGroup> @@ -44,7 +44,7 @@ <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> - <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking> + <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking> <CodeContractsCustomRewriterAssembly> </CodeContractsCustomRewriterAssembly> <CodeContractsCustomRewriterClass> @@ -75,6 +75,10 @@ <CodeContractsExtraRewriteOptions /> <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <CodeContractsRuntimeSkipQuantifiers>False</CodeContractsRuntimeSkipQuantifiers> + <CodeContractsEnumObligations>False</CodeContractsEnumObligations> + <CodeContractsCacheAnalysisResults>False</CodeContractsCacheAnalysisResults> + <CodeContractsAnalysisWarningLevel>0</CodeContractsAnalysisWarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> @@ -82,12 +86,12 @@ <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> - <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking> + <CodeContractsEnableRuntimeChecking>False</CodeContractsEnableRuntimeChecking> <CodeContractsCustomRewriterAssembly> </CodeContractsCustomRewriterAssembly> <CodeContractsCustomRewriterClass> </CodeContractsCustomRewriterClass> - <CodeContractsRuntimeCheckingLevel>None</CodeContractsRuntimeCheckingLevel> + <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel> <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface> <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure> <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires> @@ -113,6 +117,10 @@ <CodeContractsExtraRewriteOptions /> <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> + <CodeContractsRuntimeSkipQuantifiers>False</CodeContractsRuntimeSkipQuantifiers> + <CodeContractsEnumObligations>False</CodeContractsEnumObligations> + <CodeContractsCacheAnalysisResults>False</CodeContractsCacheAnalysisResults> + <CodeContractsAnalysisWarningLevel>0</CodeContractsAnalysisWarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU' "> <DebugSymbols>true</DebugSymbols> diff --git a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs index 506a6b2..af542db 100644 --- a/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs +++ b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs @@ -15,8 +15,8 @@ namespace DotNetOpenAuth.Test.Messaging { internal class CollectionAssert<T> { internal static void AreEquivalent(ICollection<T> expected, ICollection<T> actual) { - Contract.Requires<ArgumentNullException>(expected != null); - Contract.Requires<ArgumentNullException>(actual != null); + Requires.NotNull(expected, "expected"); + Requires.NotNull(actual, "actual"); ICollection expectedNonGeneric = new List<T>(expected); ICollection actualNonGeneric = new List<T>(actual); @@ -24,8 +24,8 @@ namespace DotNetOpenAuth.Test.Messaging { } internal static void AreEquivalentByEquality(ICollection<T> expected, ICollection<T> actual) { - Contract.Requires<ArgumentNullException>(expected != null); - Contract.Requires<ArgumentNullException>(actual != null); + Requires.NotNull(expected, "expected"); + Requires.NotNull(actual, "actual"); Assert.AreEqual(expected.Count, actual.Count); foreach (T value in expected) { @@ -34,7 +34,7 @@ namespace DotNetOpenAuth.Test.Messaging { } internal static void Contains(IEnumerable<T> sequence, T element) { - Contract.Requires<ArgumentNullException>(sequence != null); + Requires.NotNull(sequence, "sequence"); if (!sequence.Contains(element)) { Assert.Fail("Sequence did not include expected element '{0}'.", element); diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs index 99520a2..4d6f02b 100644 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs @@ -85,7 +85,7 @@ namespace DotNetOpenAuth.Test.Mocks { /// <param name="outgoingMessageFilter">The outgoing message filter. May be null.</param> internal CoordinatingChannel(Channel wrappedChannel, Action<IProtocolMessage> incomingMessageFilter, Action<IProtocolMessage> outgoingMessageFilter) : base(GetMessageFactory(wrappedChannel), wrappedChannel.BindingElements.ToArray()) { - Contract.Requires<ArgumentNullException>(wrappedChannel != null); + Requires.NotNull(wrappedChannel, "wrappedChannel"); this.wrappedChannel = wrappedChannel; this.incomingMessageFilter = incomingMessageFilter; @@ -219,7 +219,7 @@ namespace DotNetOpenAuth.Test.Mocks { /// channel since their message factory is not used. /// </remarks> protected virtual T CloneSerializedParts<T>(T message) where T : class, IProtocolMessage { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); IProtocolMessage clonedMessage; var messageAccessor = this.MessageDescriptions.GetAccessor(message); @@ -250,7 +250,7 @@ namespace DotNetOpenAuth.Test.Mocks { } private static IMessageFactory GetMessageFactory(Channel channel) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); return channel.MessageFactoryTestHook; } diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs index 3ea8647..3fcce19 100644 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs @@ -122,7 +122,7 @@ namespace DotNetOpenAuth.Test.Mocks { } private T CloneSerializedParts<T>(T message, HttpRequestInfo requestInfo) where T : class, IProtocolMessage { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); IProtocolMessage clonedMessage; var messageAccessor = this.MessageDescriptions.GetAccessor(message); diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs index 6b9e134..d07f794 100644 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs @@ -128,7 +128,7 @@ namespace DotNetOpenAuth.Test.Mocks { } private T CloneSerializedParts<T>(T message, HttpRequestInfo requestInfo) where T : class, IProtocolMessage { - Contract.Requires<ArgumentNullException>(message != null); + Requires.NotNull(message, "message"); IProtocolMessage clonedMessage; var messageAccessor = this.MessageDescriptions.GetAccessor(message); diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs index a744053..4655c30 100644 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs +++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs @@ -22,8 +22,8 @@ namespace DotNetOpenAuth.Test.Mocks { /// <param name="message">The direct response message to send to the remote channel. This message will be cloned.</param> /// <param name="receivingChannel">The receiving channel.</param> internal CoordinatingOutgoingWebResponse(IProtocolMessage message, CoordinatingChannel receivingChannel) { - Contract.Requires<ArgumentNullException>(message != null); - Contract.Requires<ArgumentNullException>(receivingChannel != null); + Requires.NotNull(message, "message"); + Requires.NotNull(receivingChannel, "receivingChannel"); this.receivingChannel = receivingChannel; this.OriginalMessage = message; diff --git a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs index c18ea33..7048107 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs @@ -23,7 +23,7 @@ namespace DotNetOpenAuth.Test.Mocks { private readonly Dictionary<Uri, IncomingWebResponse> registeredMockResponses = new Dictionary<Uri, IncomingWebResponse>(); private MockHttpRequest(IDirectWebRequestHandler mockHandler) { - Contract.Requires<ArgumentNullException>(mockHandler != null); + Requires.NotNull(mockHandler, "mockHandler"); this.MockWebRequestHandler = mockHandler; } @@ -42,7 +42,7 @@ namespace DotNetOpenAuth.Test.Mocks { } internal void RegisterMockResponse(IncomingWebResponse response) { - Contract.Requires<ArgumentNullException>(response != null); + Requires.NotNull(response, "response"); if (this.registeredMockResponses.ContainsKey(response.RequestUri)) { Logger.Http.WarnFormat("Mock HTTP response already registered for {0}.", response.RequestUri); } else { @@ -59,9 +59,9 @@ namespace DotNetOpenAuth.Test.Mocks { } internal void RegisterMockResponse(Uri requestUri, Uri responseUri, string contentType, WebHeaderCollection headers, string responseBody) { - Contract.Requires<ArgumentNullException>(requestUri != null); - Contract.Requires<ArgumentNullException>(responseUri != null); - Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(contentType)); + Requires.NotNull(requestUri, "requestUri"); + Requires.NotNull(responseUri, "responseUri"); + Requires.NotNullOrEmpty(contentType, "contentType"); // Set up the redirect if appropriate if (requestUri != responseUri) { @@ -84,7 +84,7 @@ namespace DotNetOpenAuth.Test.Mocks { } internal void RegisterMockXrdsResponse(IdentifierDiscoveryResult endpoint) { - Contract.Requires<ArgumentNullException>(endpoint != null); + Requires.NotNull(endpoint, "endpoint"); string identityUri; if (endpoint.ClaimedIdentifier == endpoint.Protocol.ClaimedIdentifierForOPIdentifier) { @@ -96,7 +96,7 @@ namespace DotNetOpenAuth.Test.Mocks { } internal void RegisterMockXrdsResponse(Uri respondingUri, IEnumerable<IdentifierDiscoveryResult> endpoints) { - Contract.Requires<ArgumentNullException>(endpoints != null); + Requires.NotNull(endpoints, "endpoints"); StringBuilder xrds = new StringBuilder(); xrds.AppendLine(@"<xrds:XRDS xmlns:xrds='xri://$xrds' xmlns:openid='http://openid.net/xmlns/1.0' xmlns='xri://$xrd*($v*2.0)'> diff --git a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs index 9f032b8..fe1cb81 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs @@ -26,9 +26,9 @@ namespace DotNetOpenAuth.Test.Mocks { public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<IdentifierDiscoveryResult> endpoints) : base(wrappedIdentifier.OriginalString, false) { - Contract.Requires<ArgumentNullException>(wrappedIdentifier != null); - Contract.Requires<ArgumentNullException>(mockHttpRequest != null); - Contract.Requires<ArgumentNullException>(endpoints != null); + Requires.NotNull(wrappedIdentifier, "wrappedIdentifier"); + Requires.NotNull(mockHttpRequest, "mockHttpRequest"); + Requires.NotNull(endpoints, "endpoints"); this.wrappedIdentifier = wrappedIdentifier; this.endpoints = endpoints; diff --git a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs index dd17735..16ea337 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs @@ -21,7 +21,7 @@ namespace DotNetOpenAuth.Test.Mocks { /// <param name="relyingPartyDescriptions">The relying party descriptions.</param> internal MockRealm(Realm wrappedRealm, params RelyingPartyEndpointDescription[] relyingPartyDescriptions) : base(wrappedRealm) { - Contract.Requires<ArgumentNullException>(relyingPartyDescriptions != null); + Requires.NotNull(relyingPartyDescriptions, "relyingPartyDescriptions"); this.relyingPartyDescriptions = relyingPartyDescriptions; } diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs index 5e00fac..57a2a74 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs @@ -248,7 +248,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { } private static string CreateAuthorizationHeader(IDictionary<string, string> fields) { - Contract.Requires<ArgumentNullException>(fields != null); + Requires.NotNull(fields, "fields"); StringBuilder authorization = new StringBuilder(); authorization.Append("OAuth "); diff --git a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs index f4baf4e..067b364 100644 --- a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs +++ b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs @@ -29,8 +29,8 @@ namespace DotNetOpenAuth.Test.OAuth { /// <param name="serviceProviderAction">The code path of the Service Provider.</param> internal OAuthCoordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action<WebConsumer> consumerAction, Action<ServiceProvider> serviceProviderAction) : base(consumerAction, serviceProviderAction) { - Contract.Requires<ArgumentNullException>(consumerDescription != null); - Contract.Requires<ArgumentNullException>(serviceDescription != null); + Requires.NotNull(consumerDescription, "consumerDescription"); + Requires.NotNull(serviceDescription, "serviceDescription"); this.consumerDescription = consumerDescription; this.serviceDescription = serviceDescription; diff --git a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs index ec0db22..a0d833d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs @@ -136,8 +136,8 @@ namespace DotNetOpenAuth.Test.OpenId { } private void ParameterizedAuthenticationTest(Protocol protocol, bool statelessRP, bool sharedAssociation, bool positive, bool immediate, bool tamper) { - Contract.Requires<ArgumentException>(!statelessRP || !sharedAssociation, "The RP cannot be stateless while sharing an association with the OP."); - Contract.Requires<ArgumentException>(positive || !tamper, "Cannot tamper with a negative response."); + Requires.True(!statelessRP || !sharedAssociation, null, "The RP cannot be stateless while sharing an association with the OP."); + Requires.True(positive || !tamper, null, "Cannot tamper with a negative response."); var securitySettings = new ProviderSecuritySettings(); var cryptoKeyStore = new MemoryCryptoKeyStore(); var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore); diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs index 0485254..0ef4bca 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs @@ -168,7 +168,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } private static void RegisterMockExtension(Channel channel) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); ExtensionTestUtilities.RegisterExtension(channel, MockOpenIdExtension.Factory); } @@ -179,7 +179,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <param name="protocol">The protocol to construct the message with.</param> /// <returns>The message ready to send from OP to RP.</returns> private IndirectSignedResponse CreateResponseWithExtensions(Protocol protocol) { - Contract.Requires<ArgumentNullException>(protocol != null); + Requires.NotNull(protocol, "protocol"); IndirectSignedResponse response = new IndirectSignedResponse(protocol.Version, RPUri); response.ProviderEndpoint = OPUri; diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs index eb2f867..4a78fc1 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs @@ -77,7 +77,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { } internal static void RegisterExtension(Channel channel, StandardOpenIdExtensionFactory.CreateDelegate extensionFactory) { - Contract.Requires<ArgumentNullException>(channel != null); + Requires.NotNull(channel, "channel"); var factory = (OpenIdExtensionFactoryAggregator)channel.BindingElements.OfType<ExtensionsBindingElement>().Single().ExtensionFactory; factory.Factories.OfType<StandardOpenIdExtensionFactory>().Single().RegisterExtension(extensionFactory); diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs index d4884e8..e5c3c64 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs @@ -37,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId { } private static Action<OpenIdRelyingParty> WrapAction(Action<OpenIdRelyingParty> action) { - Contract.Requires<ArgumentNullException>(action != null); + Requires.NotNull(action, "action"); return rp => { action(rp); @@ -46,7 +46,7 @@ namespace DotNetOpenAuth.Test.OpenId { } private static Action<OpenIdProvider> WrapAction(Action<OpenIdProvider> action) { - Contract.Requires<ArgumentNullException>(action != null); + Requires.NotNull(action, "action"); return op => { action(op); diff --git a/src/Mono.Math/Mono.Math.csproj b/src/Mono.Math/Mono.Math.csproj index a849aa5..c0d66b6 100644 --- a/src/Mono.Math/Mono.Math.csproj +++ b/src/Mono.Math/Mono.Math.csproj @@ -13,7 +13,6 @@ <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Mono.Math</RootNamespace> <AssemblyName>Mono.Math</AssemblyName> - <CodeContractsRewritingDisabled>true</CodeContractsRewritingDisabled> </PropertyGroup> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" /> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> diff --git a/src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj b/src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj index 13b02fe..c2b1055 100644 --- a/src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj +++ b/src/Org.Mentalis.Security.Cryptography/Org.Mentalis.Security.Cryptography.csproj @@ -13,7 +13,6 @@ <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Org.Mentalis.Security.Cryptography</RootNamespace> <AssemblyName>Org.Mentalis.Security.Cryptography</AssemblyName> - <CodeContractsRewritingDisabled>true</CodeContractsRewritingDisabled> </PropertyGroup> <Import Project="$(ProjectRoot)tools\DotNetOpenAuth.Product.props" /> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> |