diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/DotNetOAuth.Test/Test References/DotNetOAuth.accessor | 1 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj (renamed from src/DotNetOAuth.Test/DotNetOAuth.Test.csproj) | 232 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Logging.config (renamed from src/DotNetOAuth.Test/Logging.config) | 66 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs (renamed from src/DotNetOAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs) | 78 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs (renamed from src/DotNetOAuth.Test/Messaging/ChannelTests.cs) | 580 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs (renamed from src/DotNetOAuth.Test/Messaging/CollectionAssert.cs) | 38 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/HttpRequestInfoTests.cs (renamed from src/DotNetOAuth.Test/Messaging/HttpRequestInfoTests.cs) | 72 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs (renamed from src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs) | 260 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs (renamed from src/DotNetOAuth.Test/Messaging/MessagingTestBase.cs) | 376 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs (renamed from src/DotNetOAuth.Test/Messaging/MessagingUtilitiesTests.cs) | 198 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs (renamed from src/DotNetOAuth.Test/Messaging/ProtocolExceptionTests.cs) | 194 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs (renamed from src/DotNetOAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs) | 48 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs (renamed from src/DotNetOAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs) | 694 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/Reflection/MessagePartTests.cs (renamed from src/DotNetOAuth.Test/Messaging/Reflection/MessagePartTests.cs) | 202 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/Reflection/ValueMappingTests.cs (renamed from src/DotNetOAuth.Test/Messaging/Reflection/ValueMappingTests.cs) | 48 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs (renamed from src/DotNetOAuth.Test/Messaging/ResponseTests.cs) | 78 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs (renamed from src/DotNetOAuth.Test/Mocks/InMemoryTokenManager.cs) | 213 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs (renamed from src/DotNetOAuth.Test/Mocks/MockReplayProtectionBindingElement.cs) | 96 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/MockSigningBindingElement.cs (renamed from src/DotNetOAuth.Test/Mocks/MockSigningBindingElement.cs) | 96 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs (renamed from src/DotNetOAuth.Test/Mocks/MockTransformationBindingElement.cs) | 110 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs (renamed from src/DotNetOAuth.Test/Mocks/TestBadChannel.cs) | 108 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestBaseMessage.cs (renamed from src/DotNetOAuth.Test/Mocks/TestBaseMessage.cs) | 112 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestChannel.cs (renamed from src/DotNetOAuth.Test/Mocks/TestChannel.cs) | 70 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestDerivedMessage.cs (renamed from src/DotNetOAuth.Test/Mocks/TestDerivedMessage.cs) | 66 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs (renamed from src/DotNetOAuth.Test/Mocks/TestDirectedMessage.cs) | 86 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestExpiringMessage.cs (renamed from src/DotNetOAuth.Test/Mocks/TestExpiringMessage.cs) | 70 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestMessage.cs (renamed from src/DotNetOAuth.Test/Mocks/TestMessage.cs) | 126 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestMessageTypeProvider.cs (renamed from src/DotNetOAuth.Test/Mocks/TestMessageTypeProvider.cs) | 112 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestReplayProtectedMessage.cs (renamed from src/DotNetOAuth.Test/Mocks/TestReplayProtectedMessage.cs) | 60 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestSignedDirectedMessage.cs (renamed from src/DotNetOAuth.Test/Mocks/TestSignedDirectedMessage.cs) | 66 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs (renamed from src/DotNetOAuth.Test/Mocks/TestWebRequestHandler.cs) | 92 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs (renamed from src/DotNetOAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs) | 44 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs (renamed from src/DotNetOAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs) | 586 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs (renamed from src/DotNetOAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs) | 156 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs (renamed from src/DotNetOAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs) | 80 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs (renamed from src/DotNetOAuth.Test/OAuth/ConsumerDescription.cs) | 76 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/OAuth/ProtocolTests.cs (renamed from src/DotNetOAuth.Test/OAuth/ProtocolTests.cs) | 68 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs (renamed from src/DotNetOAuth.Test/OAuth/ServiceProviderDescriptionTests.cs) | 152 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs (renamed from src/DotNetOAuth.Test/Properties/AssemblyInfo.cs) | 58 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Scenarios/AppendixScenarios.cs (renamed from src/DotNetOAuth.Test/Scenarios/AppendixScenarios.cs) | 135 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Scenarios/CoordinatingOAuthChannel.cs (renamed from src/DotNetOAuth.Test/Scenarios/CoordinatingOAuthChannel.cs) | 288 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Scenarios/Coordinator.cs (renamed from src/DotNetOAuth.Test/Scenarios/Coordinator.cs) | 241 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Settings.StyleCop (renamed from src/DotNetOAuth.Test/Settings.StyleCop) | 56 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/Test References/DotNetOpenAuth.accessor | 1 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/TestBase.cs (renamed from src/DotNetOAuth.Test/TestBase.cs) | 90 | ||||
-rw-r--r-- | src/DotNetOpenAuth.Test/UriUtilTests.cs (renamed from src/DotNetOAuth.Test/UriUtilTests.cs) | 42 | ||||
-rw-r--r-- | src/DotNetOpenAuth.sln (renamed from src/DotNetOAuth.sln) | 232 | ||||
-rw-r--r-- | src/DotNetOpenAuth.vsmdi (renamed from src/DotNetOAuth.vsmdi) | 10 | ||||
-rw-r--r-- | src/DotNetOpenAuth/ClassDiagram.cd (renamed from src/DotNetOAuth/ClassDiagram.cd) | 106 | ||||
-rw-r--r-- | src/DotNetOpenAuth/DotNetOpenAuth.csproj (renamed from src/DotNetOAuth/DotNetOAuth.csproj) | 344 | ||||
-rw-r--r-- | src/DotNetOpenAuth/GlobalSuppressions.cs (renamed from src/DotNetOAuth/GlobalSuppressions.cs) | 30 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Logger.cs (renamed from src/DotNetOAuth/Logger.cs) | 1908 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Loggers/ILog.cs (renamed from src/DotNetOAuth/Loggers/ILog.cs) | 1932 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Loggers/Log4NetLogger.cs (renamed from src/DotNetOAuth/Loggers/Log4NetLogger.cs) | 422 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Loggers/NoOpLogger.cs (renamed from src/DotNetOAuth/Loggers/NoOpLogger.cs) | 358 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Loggers/TraceLogger.cs (renamed from src/DotNetOAuth/Loggers/TraceLogger.cs) | 664 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/Bindings.cd (renamed from src/DotNetOAuth/Messaging/Bindings/Bindings.cd) | 150 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs (renamed from src/DotNetOAuth/Messaging/Bindings/ExpiredMessageException.cs) | 74 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/IExpiringProtocolMessage.cs (renamed from src/DotNetOAuth/Messaging/Bindings/IExpiringProtocolMessage.cs) | 58 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/INonceStore.cs (renamed from src/DotNetOAuth/Messaging/Bindings/INonceStore.cs) | 74 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs (renamed from src/DotNetOAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs) | 48 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/InvalidSignatureException.cs (renamed from src/DotNetOAuth/Messaging/Bindings/InvalidSignatureException.cs) | 68 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/NonceMemoryStore.cs (renamed from src/DotNetOAuth/Messaging/Bindings/NonceMemoryStore.cs) | 144 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/ReplayedMessageException.cs (renamed from src/DotNetOAuth/Messaging/Bindings/ReplayedMessageException.cs) | 68 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/StandardExpirationBindingElement.cs (renamed from src/DotNetOAuth/Messaging/Bindings/StandardExpirationBindingElement.cs) | 238 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs (renamed from src/DotNetOAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs) | 270 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Channel.cs (renamed from src/DotNetOAuth/Messaging/Channel.cs) | 1386 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/ChannelEventArgs.cs (renamed from src/DotNetOAuth/Messaging/ChannelEventArgs.cs) | 62 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Exceptions.cd (renamed from src/DotNetOAuth/Messaging/Exceptions.cd) | 64 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/HttpDeliveryMethods.cs (renamed from src/DotNetOAuth/Messaging/HttpDeliveryMethods.cs) | 86 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/HttpRequestInfo.cs (renamed from src/DotNetOAuth/Messaging/HttpRequestInfo.cs) | 360 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/IChannelBindingElement.cs (renamed from src/DotNetOAuth/Messaging/IChannelBindingElement.cs) | 96 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/IDirectedProtocolMessage.cs (renamed from src/DotNetOAuth/Messaging/IDirectedProtocolMessage.cs) | 40 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/IMessageTypeProvider.cs (renamed from src/DotNetOAuth/Messaging/IMessageTypeProvider.cs) | 82 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/IProtocolMessage.cs (renamed from src/DotNetOAuth/Messaging/IProtocolMessage.cs) | 108 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/ITamperProtectionChannelBindingElement.cs (renamed from src/DotNetOAuth/Messaging/ITamperProtectionChannelBindingElement.cs) | 56 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/ITamperResistantProtocolMessage.cs (renamed from src/DotNetOAuth/Messaging/ITamperResistantProtocolMessage.cs) | 44 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessagePartAttribute.cs (renamed from src/DotNetOAuth/Messaging/MessagePartAttribute.cs) | 114 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessageProtections.cs (renamed from src/DotNetOAuth/Messaging/MessageProtections.cs) | 90 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessageReceivingEndpoint.cs (renamed from src/DotNetOAuth/Messaging/MessageReceivingEndpoint.cs) | 108 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessageSerializer.cs (renamed from src/DotNetOAuth/Messaging/MessageSerializer.cs) | 272 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessageTransport.cs (renamed from src/DotNetOAuth/Messaging/MessageTransport.cs) | 44 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Messaging.cd (renamed from src/DotNetOAuth/Messaging/Messaging.cd) | 122 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs (renamed from src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs) | 702 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessagingStrings.resx (renamed from src/DotNetOAuth/Messaging/MessagingStrings.resx) | 430 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/MessagingUtilities.cs (renamed from src/DotNetOAuth/Messaging/MessagingUtilities.cs) | 542 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/ProtocolException.cs (renamed from src/DotNetOAuth/Messaging/ProtocolException.cs) | 508 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs (renamed from src/DotNetOAuth/Messaging/Reflection/MessageDescription.cs) | 256 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Reflection/MessageDictionary.cs (renamed from src/DotNetOAuth/Messaging/Reflection/MessageDictionary.cs) | 640 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs (renamed from src/DotNetOAuth/Messaging/Reflection/MessagePart.cs) | 502 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Reflection/ValueMapping.cs (renamed from src/DotNetOAuth/Messaging/Reflection/ValueMapping.cs) | 84 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/Response.cs (renamed from src/DotNetOAuth/Messaging/Response.cs) | 356 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Messaging/UnprotectedMessageException.cs (renamed from src/DotNetOAuth/Messaging/UnprotectedMessageException.cs) | 74 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs) | 96 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/IOAuthDirectedMessage.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/IOAuthDirectedMessage.cs) | 50 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs) | 82 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/ITokenGenerator.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/ITokenGenerator.cs) | 80 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/ITokenManager.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/ITokenManager.cs) | 160 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/IWebRequestHandler.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/IWebRequestHandler.cs) | 62 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/OAuthChannel.cs) | 794 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/OAuthConsumerMessageTypeProvider.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/OAuthConsumerMessageTypeProvider.cs) | 194 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs) | 146 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/OAuthServiceProviderMessageTypeProvider.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/OAuthServiceProviderMessageTypeProvider.cs) | 212 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs) | 110 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs) | 96 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBase.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/SigningBindingElementBase.cs) | 484 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementChain.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/SigningBindingElementChain.cs) | 264 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/StandardTokenGenerator.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/StandardTokenGenerator.cs) | 136 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/StandardWebRequestHandler.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/StandardWebRequestHandler.cs) | 140 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ChannelElements/TokenType.cs (renamed from src/DotNetOAuth/OAuth/ChannelElements/TokenType.cs) | 60 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ConsumerBase.cs (renamed from src/DotNetOAuth/OAuth/ConsumerBase.cs) | 352 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/DesktopConsumer.cs (renamed from src/DotNetOAuth/OAuth/DesktopConsumer.cs) | 111 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/AccessProtectedResourceRequest.cs (renamed from src/DotNetOAuth/OAuth/Messages/AccessProtectedResourceRequest.cs) | 90 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenRequest.cs (renamed from src/DotNetOAuth/OAuth/Messages/AuthorizedTokenRequest.cs) | 106 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenResponse.cs (renamed from src/DotNetOAuth/OAuth/Messages/AuthorizedTokenResponse.cs) | 120 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/ITokenContainingMessage.cs (renamed from src/DotNetOAuth/OAuth/Messages/ITokenContainingMessage.cs) | 34 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/ITokenSecretContainingMessage.cs (renamed from src/DotNetOAuth/OAuth/Messages/ITokenSecretContainingMessage.cs) | 34 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/MessageBase.cs (renamed from src/DotNetOAuth/OAuth/Messages/MessageBase.cs) | 478 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/OAuth Messages.cd (renamed from src/DotNetOAuth/OAuth/Messages/OAuth Messages.cd) | 428 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/SignedMessageBase.cs (renamed from src/DotNetOAuth/OAuth/Messages/SignedMessageBase.cs) | 322 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenRequest.cs (renamed from src/DotNetOAuth/OAuth/Messages/UnauthorizedTokenRequest.cs) | 60 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenResponse.cs (renamed from src/DotNetOAuth/OAuth/Messages/UnauthorizedTokenResponse.cs) | 184 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationRequest.cs (renamed from src/DotNetOAuth/OAuth/Messages/UserAuthorizationRequest.cs) | 142 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationResponse.cs (renamed from src/DotNetOAuth/OAuth/Messages/UserAuthorizationResponse.cs) | 80 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/Protocol.cs (renamed from src/DotNetOAuth/OAuth/Protocol.cs) | 174 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ServiceProvider.cs (renamed from src/DotNetOAuth/OAuth/ServiceProvider.cs) | 792 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/ServiceProviderDescription.cs (renamed from src/DotNetOAuth/OAuth/ServiceProviderDescription.cs) | 174 | ||||
-rw-r--r-- | src/DotNetOpenAuth/OAuth/WebConsumer.cs (renamed from src/DotNetOAuth/OAuth/WebConsumer.cs) | 194 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Properties/AssemblyInfo.cs (renamed from src/DotNetOAuth/Properties/AssemblyInfo.cs) | 186 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Settings.StyleCop (renamed from src/DotNetOAuth/Settings.StyleCop) | 26 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Strings.Designer.cs (renamed from src/DotNetOAuth/Strings.Designer.cs) | 270 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Strings.resx (renamed from src/DotNetOAuth/Strings.resx) | 286 | ||||
-rw-r--r-- | src/DotNetOpenAuth/UriUtil.cs (renamed from src/DotNetOAuth/UriUtil.cs) | 62 | ||||
-rw-r--r-- | src/DotNetOpenAuth/Util.cs (renamed from src/DotNetOAuth/Util.cs) | 60 | ||||
-rw-r--r-- | src/LocalTestRun.testrunconfig | 42 |
135 files changed, 14559 insertions, 14561 deletions
diff --git a/src/DotNetOAuth.Test/Test References/DotNetOAuth.accessor b/src/DotNetOAuth.Test/Test References/DotNetOAuth.accessor deleted file mode 100644 index cf1be04..0000000 --- a/src/DotNetOAuth.Test/Test References/DotNetOAuth.accessor +++ /dev/null @@ -1 +0,0 @@ -DotNetOAuth.dll
diff --git a/src/DotNetOAuth.Test/DotNetOAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj index c2aa409..ae8525c 100644 --- a/src/DotNetOAuth.Test/DotNetOAuth.Test.csproj +++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj @@ -1,117 +1,117 @@ -<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProductVersion>9.0.30729</ProductVersion>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>DotNetOAuth.Test</RootNamespace>
- <AssemblyName>DotNetOAuth.Test</AssemblyName>
- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
- <FileAlignment>512</FileAlignment>
- <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>false</Optimize>
- <OutputPath>..\..\bin\Debug\</OutputPath>
- <DefineConstants>DEBUG;TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
- <OutputPath>..\..\bin\Release\</OutputPath>
- <DefineConstants>TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Sign)' == 'true' ">
- <SignAssembly>true</SignAssembly>
- <AssemblyOriginatorKeyFile>..\official-build-key.pfx</AssemblyOriginatorKeyFile>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\..\lib\log4net.dll</HintPath>
- </Reference>
- <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
- <Reference Include="System" />
- <Reference Include="System.Core">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Data" />
- <Reference Include="System.Data.DataSetExtensions">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Runtime.Serialization">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Web" />
- <Reference Include="System.Xml" />
- <Reference Include="System.Xml.Linq">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- </ItemGroup>
- <ItemGroup>
- <Compile Include="OAuth\ChannelElements\SigningBindingElementBaseTests.cs" />
- <Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElementTests.cs" />
- <Compile Include="OAuth\ConsumerDescription.cs" />
- <Compile Include="Messaging\CollectionAssert.cs" />
- <Compile Include="Messaging\MessageSerializerTests.cs" />
- <Compile Include="Messaging\Reflection\MessageDescriptionTests.cs" />
- <Compile Include="Messaging\Reflection\MessageDictionaryTests.cs" />
- <Compile Include="Messaging\MessagingTestBase.cs" />
- <Compile Include="Messaging\MessagingUtilitiesTests.cs" />
- <Compile Include="Messaging\ChannelTests.cs" />
- <Compile Include="Messaging\HttpRequestInfoTests.cs" />
- <Compile Include="Messaging\ProtocolExceptionTests.cs" />
- <Compile Include="Messaging\Bindings\StandardExpirationBindingElementTests.cs" />
- <Compile Include="Messaging\Reflection\MessagePartTests.cs" />
- <Compile Include="Messaging\Reflection\ValueMappingTests.cs" />
- <Compile Include="Mocks\InMemoryTokenManager.cs" />
- <Compile Include="Mocks\MockTransformationBindingElement.cs" />
- <Compile Include="Mocks\MockReplayProtectionBindingElement.cs" />
- <Compile Include="Mocks\TestBaseMessage.cs" />
- <Compile Include="Mocks\TestDerivedMessage.cs" />
- <Compile Include="Mocks\TestReplayProtectedMessage.cs" />
- <Compile Include="Mocks\TestDirectedMessage.cs" />
- <Compile Include="Mocks\TestBadChannel.cs" />
- <Compile Include="Mocks\TestExpiringMessage.cs" />
- <Compile Include="Mocks\TestSignedDirectedMessage.cs" />
- <Compile Include="Mocks\MockSigningBindingElement.cs" />
- <Compile Include="Mocks\TestWebRequestHandler.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthChannelTests.cs" />
- <Compile Include="Mocks\TestChannel.cs" />
- <Compile Include="Mocks\TestMessage.cs" />
- <Compile Include="Mocks\TestMessageTypeProvider.cs" />
- <Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElementTest.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="Messaging\ResponseTests.cs" />
- <Compile Include="OAuth\ProtocolTests.cs" />
- <Compile Include="Scenarios\AppendixScenarios.cs" />
- <Compile Include="Scenarios\CoordinatingOAuthChannel.cs" />
- <Compile Include="Scenarios\Coordinator.cs" />
- <Compile Include="OAuth\ServiceProviderDescriptionTests.cs" />
- <Compile Include="TestBase.cs" />
- <Compile Include="UriUtilTests.cs" />
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\DotNetOAuth\DotNetOAuth.csproj">
- <Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project>
- <Name>DotNetOAuth</Name>
- </ProjectReference>
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="Logging.config" />
- </ItemGroup>
- <ItemGroup>
- <Shadow Include="Test References\DotNetOAuth.accessor" />
- </ItemGroup>
- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
- <Import Project="..\..\tools\DotNetOAuth.Versioning.targets" />
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.30729</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>DotNetOpenAuth.Test</RootNamespace> + <AssemblyName>DotNetOpenAuth.Test</AssemblyName> + <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>..\..\bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>..\..\bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Sign)' == 'true' "> + <SignAssembly>true</SignAssembly> + <AssemblyOriginatorKeyFile>..\official-build-key.pfx</AssemblyOriginatorKeyFile> + </PropertyGroup> + <ItemGroup> + <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\lib\log4net.dll</HintPath> + </Reference> + <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> + <Reference Include="System" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data" /> + <Reference Include="System.Data.DataSetExtensions"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Runtime.Serialization"> + <RequiredTargetFramework>3.0</RequiredTargetFramework> + </Reference> + <Reference Include="System.Web" /> + <Reference Include="System.Xml" /> + <Reference Include="System.Xml.Linq"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + </ItemGroup> + <ItemGroup> + <Compile Include="Messaging\CollectionAssert.cs" /> + <Compile Include="Messaging\MessageSerializerTests.cs" /> + <Compile Include="Messaging\Reflection\MessageDescriptionTests.cs" /> + <Compile Include="Messaging\Reflection\MessageDictionaryTests.cs" /> + <Compile Include="Messaging\MessagingTestBase.cs" /> + <Compile Include="Messaging\MessagingUtilitiesTests.cs" /> + <Compile Include="Messaging\ChannelTests.cs" /> + <Compile Include="Messaging\HttpRequestInfoTests.cs" /> + <Compile Include="Messaging\ProtocolExceptionTests.cs" /> + <Compile Include="Messaging\Bindings\StandardExpirationBindingElementTests.cs" /> + <Compile Include="Messaging\Reflection\MessagePartTests.cs" /> + <Compile Include="Messaging\Reflection\ValueMappingTests.cs" /> + <Compile Include="Mocks\InMemoryTokenManager.cs" /> + <Compile Include="Mocks\MockTransformationBindingElement.cs" /> + <Compile Include="Mocks\MockReplayProtectionBindingElement.cs" /> + <Compile Include="Mocks\TestBaseMessage.cs" /> + <Compile Include="Mocks\TestDerivedMessage.cs" /> + <Compile Include="Mocks\TestReplayProtectedMessage.cs" /> + <Compile Include="Mocks\TestDirectedMessage.cs" /> + <Compile Include="Mocks\TestBadChannel.cs" /> + <Compile Include="Mocks\TestExpiringMessage.cs" /> + <Compile Include="Mocks\TestSignedDirectedMessage.cs" /> + <Compile Include="Mocks\MockSigningBindingElement.cs" /> + <Compile Include="Mocks\TestWebRequestHandler.cs" /> + <Compile Include="Mocks\TestChannel.cs" /> + <Compile Include="Mocks\TestMessage.cs" /> + <Compile Include="Mocks\TestMessageTypeProvider.cs" /> + <Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElementTests.cs" /> + <Compile Include="OAuth\ChannelElements\OAuthChannelTests.cs" /> + <Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElementTest.cs" /> + <Compile Include="OAuth\ChannelElements\SigningBindingElementBaseTests.cs" /> + <Compile Include="OAuth\ConsumerDescription.cs" /> + <Compile Include="OAuth\ProtocolTests.cs" /> + <Compile Include="OAuth\ServiceProviderDescriptionTests.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="Messaging\ResponseTests.cs" /> + <Compile Include="Scenarios\AppendixScenarios.cs" /> + <Compile Include="Scenarios\CoordinatingOAuthChannel.cs" /> + <Compile Include="Scenarios\Coordinator.cs" /> + <Compile Include="TestBase.cs" /> + <Compile Include="UriUtilTests.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\DotNetOpenAuth\DotNetOpenAuth.csproj"> + <Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project> + <Name>DotNetOpenAuth</Name> + </ProjectReference> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="Logging.config" /> + </ItemGroup> + <ItemGroup> + <Shadow Include="Test References\DotNetOpenAuth.accessor" /> + </ItemGroup> + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> + <Import Project="..\..\tools\DotNetOpenAuth.Versioning.targets" /> </Project>
\ No newline at end of file diff --git a/src/DotNetOAuth.Test/Logging.config b/src/DotNetOpenAuth.Test/Logging.config index be6b69e..f67c031 100644 --- a/src/DotNetOAuth.Test/Logging.config +++ b/src/DotNetOpenAuth.Test/Logging.config @@ -1,33 +1,33 @@ -<?xml version="1.0" encoding="utf-8" ?>
-<log4net>
- <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
- <file value="Testing.log" />
- <appendToFile value="true" />
- <rollingStyle value="Size" />
- <maxSizeRollBackups value="10" />
- <maximumFileSize value="1024KB" />
- <staticLogFileName value="true" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
- </layout>
- </appender>
- <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
- <immediateFlush value="true" />
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%-5level - %message%newline" />
- </layout>
- </appender>
- <!-- Setup the root category, add the appenders and set the default level -->
- <root>
- <level value="Info" />
- <!--<appender-ref ref="RollingFileAppender" />-->
- <appender-ref ref="TraceAppender" />
- </root>
- <!-- Specify the level for some specific categories -->
- <logger name="DotNetOAuth">
- <level value="Debug" />
- </logger>
- <logger name="DotNetOAuth.Test">
- <level value="Debug" />
- </logger>
-</log4net>
+<?xml version="1.0" encoding="utf-8" ?> +<log4net> + <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> + <file value="Testing.log" /> + <appendToFile value="true" /> + <rollingStyle value="Size" /> + <maxSizeRollBackups value="10" /> + <maximumFileSize value="1024KB" /> + <staticLogFileName value="true" /> + <layout type="log4net.Layout.PatternLayout"> + <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> + </layout> + </appender> + <appender name="TraceAppender" type="log4net.Appender.TraceAppender"> + <immediateFlush value="true" /> + <layout type="log4net.Layout.PatternLayout"> + <conversionPattern value="%-5level - %message%newline" /> + </layout> + </appender> + <!-- Setup the root category, add the appenders and set the default level --> + <root> + <level value="Info" /> + <!--<appender-ref ref="RollingFileAppender" />--> + <appender-ref ref="TraceAppender" /> + </root> + <!-- Specify the level for some specific categories --> + <logger name="DotNetOpenAuth"> + <level value="Debug" /> + </logger> + <logger name="DotNetOpenAuth.Test"> + <level value="Debug" /> + </logger> +</log4net> diff --git a/src/DotNetOAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs index 6c05434..69f95f9 100644 --- a/src/DotNetOAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs @@ -1,39 +1,39 @@ -//-----------------------------------------------------------------------
-// <copyright file="StandardExpirationBindingElementTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Bindings {
- using System;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class StandardExpirationBindingElementTests : MessagingTestBase {
- [TestMethod]
- public void SendSetsTimestamp() {
- TestExpiringMessage message = new TestExpiringMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://localtest");
- ((IExpiringProtocolMessage)message).UtcCreationDate = DateTime.Parse("1/1/1990");
-
- Channel channel = CreateChannel(MessageProtections.Expiration);
- channel.Send(message);
- Assert.IsTrue(DateTime.UtcNow - ((IExpiringProtocolMessage)message).UtcCreationDate < TimeSpan.FromSeconds(3), "The timestamp on the message was not set on send.");
- }
-
- [TestMethod]
- public void VerifyGoodTimestampIsAccepted() {
- this.Channel = CreateChannel(MessageProtections.Expiration);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- }
-
- [TestMethod, ExpectedException(typeof(ExpiredMessageException))]
- public void VerifyBadTimestampIsRejected() {
- this.Channel = CreateChannel(MessageProtections.Expiration);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow - StandardExpirationBindingElement.DefaultMaximumMessageAge - TimeSpan.FromSeconds(1), false);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="StandardExpirationBindingElementTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging.Bindings { + using System; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Test.Mocks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class StandardExpirationBindingElementTests : MessagingTestBase { + [TestMethod] + public void SendSetsTimestamp() { + TestExpiringMessage message = new TestExpiringMessage(MessageTransport.Indirect); + message.Recipient = new Uri("http://localtest"); + ((IExpiringProtocolMessage)message).UtcCreationDate = DateTime.Parse("1/1/1990"); + + Channel channel = CreateChannel(MessageProtections.Expiration); + channel.Send(message); + Assert.IsTrue(DateTime.UtcNow - ((IExpiringProtocolMessage)message).UtcCreationDate < TimeSpan.FromSeconds(3), "The timestamp on the message was not set on send."); + } + + [TestMethod] + public void VerifyGoodTimestampIsAccepted() { + this.Channel = CreateChannel(MessageProtections.Expiration); + this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); + } + + [TestMethod, ExpectedException(typeof(ExpiredMessageException))] + public void VerifyBadTimestampIsRejected() { + this.Channel = CreateChannel(MessageProtections.Expiration); + this.ParameterizedReceiveProtectedTest(DateTime.UtcNow - StandardExpirationBindingElement.DefaultMaximumMessageAge - TimeSpan.FromSeconds(1), false); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/ChannelTests.cs b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs index e142c82..4127b5a 100644 --- a/src/DotNetOAuth.Test/Messaging/ChannelTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs @@ -1,290 +1,290 @@ -//-----------------------------------------------------------------------
-// <copyright file="ChannelTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Web;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ChannelTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNull() {
- // This bad channel is deliberately constructed to pass null to
- // its protected base class' constructor.
- new TestBadChannel(true);
- }
-
- [TestMethod]
- public void ReadFromRequestQueryString() {
- this.ParameterizedReceiveTest("GET");
- }
-
- [TestMethod]
- public void ReadFromRequestForm() {
- this.ParameterizedReceiveTest("POST");
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendNull() {
- this.Channel.Send(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendIndirectedUndirectedMessage() {
- IProtocolMessage message = new TestMessage(MessageTransport.Indirect);
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendDirectedNoRecipientMessage() {
- IProtocolMessage message = new TestDirectedMessage(MessageTransport.Indirect);
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendInvalidMessageTransport() {
- IProtocolMessage message = new TestDirectedMessage((MessageTransport)100);
- this.Channel.Send(message);
- }
-
- [TestMethod]
- public void SendIndirectMessage301Get() {
- TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Indirect);
- GetStandardTestMessage(FieldFill.CompleteBeforeBindings, message);
- message.Recipient = new Uri("http://provider/path");
- var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
-
- Response response = this.Channel.Send(message);
- Assert.AreEqual(HttpStatusCode.Redirect, response.Status);
- StringAssert.StartsWith(response.Headers[HttpResponseHeader.Location], "http://provider/path");
- foreach (var pair in expected) {
- string key = HttpUtility.UrlEncode(pair.Key);
- string value = HttpUtility.UrlEncode(pair.Value);
- string substring = string.Format("{0}={1}", key, value);
- StringAssert.Contains(response.Headers[HttpResponseHeader.Location], substring);
- }
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessage301GetNullMessage() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.Create301RedirectResponse(null, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendIndirectMessage301GetEmptyRecipient() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- badChannel.Create301RedirectResponse(message, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessage301GetNullFields() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://someserver");
- badChannel.Create301RedirectResponse(message, null);
- }
-
- [TestMethod]
- public void SendIndirectMessageFormPost() {
- // We craft a very large message to force fallback to form POST.
- // We'll also stick some HTML reserved characters in the string value
- // to test proper character escaping.
- var message = new TestDirectedMessage(MessageTransport.Indirect) {
- Age = 15,
- Name = "c<b" + new string('a', 10 * 1024),
- Location = new Uri("http://host/path"),
- Recipient = new Uri("http://provider/path"),
- };
- Response response = this.Channel.Send(message);
- Assert.AreEqual(HttpStatusCode.OK, response.Status, "A form redirect should be an HTTP successful response.");
- Assert.IsNull(response.Headers[HttpResponseHeader.Location], "There should not be a redirection header in the response.");
- string body = response.Body;
- StringAssert.Contains(body, "<form ");
- StringAssert.Contains(body, "action=\"http://provider/path\"");
- StringAssert.Contains(body, "method=\"post\"");
- StringAssert.Contains(body, "<input type=\"hidden\" name=\"age\" value=\"15\" />");
- StringAssert.Contains(body, "<input type=\"hidden\" name=\"Location\" value=\"http://host/path\" />");
- StringAssert.Contains(body, "<input type=\"hidden\" name=\"Name\" value=\"" + HttpUtility.HtmlEncode(message.Name) + "\" />");
- StringAssert.Contains(body, ".submit()", "There should be some javascript to automate form submission.");
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessageFormPostNullMessage() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.CreateFormPostResponse(null, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void SendIndirectMessageFormPostEmptyRecipient() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- badChannel.CreateFormPostResponse(message, new Dictionary<string, string>());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessageFormPostNullFields() {
- TestBadChannel badChannel = new TestBadChannel(false);
- var message = new TestDirectedMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://someserver");
- badChannel.CreateFormPostResponse(message, null);
- }
-
- /// <summary>
- /// Tests that a direct message is sent when the appropriate message type is provided.
- /// </summary>
- /// <remarks>
- /// Since this is a mock channel that doesn't actually formulate a direct message response,
- /// we just check that the right method was called.
- /// </remarks>
- [TestMethod, ExpectedException(typeof(NotImplementedException), "SendDirectMessageResponse")]
- public void SendDirectMessageResponse() {
- IProtocolMessage message = new TestMessage {
- Age = 15,
- Name = "Andrew",
- Location = new Uri("http://host/path"),
- };
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SendIndirectMessageNull() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.SendIndirectMessage(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ReceiveNull() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.Receive(null, null);
- }
-
- [TestMethod]
- public void ReceiveUnrecognizedMessage() {
- TestBadChannel badChannel = new TestBadChannel(false);
- Assert.IsNull(badChannel.Receive(new Dictionary<string, string>(), null));
- }
-
- [TestMethod]
- public void ReadFromRequestWithContext() {
- var fields = GetStandardTestFields(FieldFill.AllRequired);
- TestMessage expectedMessage = GetStandardTestMessage(FieldFill.AllRequired);
- HttpRequest request = new HttpRequest("somefile", "http://someurl", MessagingUtilities.CreateQueryString(fields));
- HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
- IProtocolMessage message = this.Channel.ReadFromRequest();
- Assert.IsNotNull(message);
- Assert.IsInstanceOfType(message, typeof(TestMessage));
- Assert.AreEqual(expectedMessage.Age, ((TestMessage)message).Age);
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void ReadFromRequestNoContext() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.ReadFromRequest();
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ReadFromRequestNull() {
- TestBadChannel badChannel = new TestBadChannel(false);
- badChannel.ReadFromRequest(null);
- }
-
- [TestMethod]
- public void SendReplayProtectedMessageSetsNonce() {
- TestReplayProtectedMessage message = new TestReplayProtectedMessage(MessageTransport.Indirect);
- message.Recipient = new Uri("http://localtest");
-
- this.Channel = CreateChannel(MessageProtections.ReplayProtection);
- this.Channel.Send(message);
- Assert.IsNotNull(((IReplayProtectedProtocolMessage)message).Nonce);
- }
-
- [TestMethod, ExpectedException(typeof(InvalidSignatureException))]
- public void ReceivedInvalidSignature() {
- this.Channel = CreateChannel(MessageProtections.TamperProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, true);
- }
-
- [TestMethod]
- public void ReceivedReplayProtectedMessageJustOnce() {
- this.Channel = CreateChannel(MessageProtections.ReplayProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- }
-
- [TestMethod, ExpectedException(typeof(ReplayedMessageException))]
- public void ReceivedReplayProtectedMessageTwice() {
- this.Channel = CreateChannel(MessageProtections.ReplayProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false);
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void MessageExpirationWithoutTamperResistance() {
- new TestChannel(
- new TestMessageTypeProvider(),
- new StandardExpirationBindingElement());
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void TooManyBindingElementsProvidingSameProtection() {
- new TestChannel(
- new TestMessageTypeProvider(),
- new MockSigningBindingElement(),
- new MockSigningBindingElement());
- }
-
- [TestMethod]
- public void BindingElementsOrdering() {
- IChannelBindingElement transformA = new MockTransformationBindingElement("a");
- IChannelBindingElement transformB = new MockTransformationBindingElement("b");
- IChannelBindingElement sign = new MockSigningBindingElement();
- IChannelBindingElement replay = new MockReplayProtectionBindingElement();
- IChannelBindingElement expire = new StandardExpirationBindingElement();
-
- Channel channel = new TestChannel(
- new TestMessageTypeProvider(),
- sign,
- replay,
- expire,
- transformB,
- transformA);
-
- Assert.AreEqual(5, channel.BindingElements.Count);
- Assert.AreSame(transformB, channel.BindingElements[0]);
- Assert.AreSame(transformA, channel.BindingElements[1]);
- Assert.AreSame(replay, channel.BindingElements[2]);
- Assert.AreSame(expire, channel.BindingElements[3]);
- Assert.AreSame(sign, channel.BindingElements[4]);
- }
-
- [TestMethod, ExpectedException(typeof(UnprotectedMessageException))]
- public void InsufficientlyProtectedMessageSent() {
- var message = new TestSignedDirectedMessage(MessageTransport.Direct);
- message.Recipient = new Uri("http://localtest");
- this.Channel.Send(message);
- }
-
- [TestMethod, ExpectedException(typeof(UnprotectedMessageException))]
- public void InsufficientlyProtectedMessageReceived() {
- this.Channel = CreateChannel(MessageProtections.None, MessageProtections.TamperProtection);
- this.ParameterizedReceiveProtectedTest(DateTime.Now, false);
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void IncomingMessageMissingRequiredParameters() {
- var fields = GetStandardTestFields(FieldFill.IdentifiableButNotAllRequired);
- this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields));
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ChannelTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Test.Mocks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ChannelTests : MessagingTestBase { + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNull() { + // This bad channel is deliberately constructed to pass null to + // its protected base class' constructor. + new TestBadChannel(true); + } + + [TestMethod] + public void ReadFromRequestQueryString() { + this.ParameterizedReceiveTest("GET"); + } + + [TestMethod] + public void ReadFromRequestForm() { + this.ParameterizedReceiveTest("POST"); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SendNull() { + this.Channel.Send(null); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void SendIndirectedUndirectedMessage() { + IProtocolMessage message = new TestMessage(MessageTransport.Indirect); + this.Channel.Send(message); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void SendDirectedNoRecipientMessage() { + IProtocolMessage message = new TestDirectedMessage(MessageTransport.Indirect); + this.Channel.Send(message); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void SendInvalidMessageTransport() { + IProtocolMessage message = new TestDirectedMessage((MessageTransport)100); + this.Channel.Send(message); + } + + [TestMethod] + public void SendIndirectMessage301Get() { + TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Indirect); + GetStandardTestMessage(FieldFill.CompleteBeforeBindings, message); + message.Recipient = new Uri("http://provider/path"); + var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings); + + Response response = this.Channel.Send(message); + Assert.AreEqual(HttpStatusCode.Redirect, response.Status); + StringAssert.StartsWith(response.Headers[HttpResponseHeader.Location], "http://provider/path"); + foreach (var pair in expected) { + string key = HttpUtility.UrlEncode(pair.Key); + string value = HttpUtility.UrlEncode(pair.Value); + string substring = string.Format("{0}={1}", key, value); + StringAssert.Contains(response.Headers[HttpResponseHeader.Location], substring); + } + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SendIndirectMessage301GetNullMessage() { + TestBadChannel badChannel = new TestBadChannel(false); + badChannel.Create301RedirectResponse(null, new Dictionary<string, string>()); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void SendIndirectMessage301GetEmptyRecipient() { + TestBadChannel badChannel = new TestBadChannel(false); + var message = new TestDirectedMessage(MessageTransport.Indirect); + badChannel.Create301RedirectResponse(message, new Dictionary<string, string>()); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SendIndirectMessage301GetNullFields() { + TestBadChannel badChannel = new TestBadChannel(false); + var message = new TestDirectedMessage(MessageTransport.Indirect); + message.Recipient = new Uri("http://someserver"); + badChannel.Create301RedirectResponse(message, null); + } + + [TestMethod] + public void SendIndirectMessageFormPost() { + // We craft a very large message to force fallback to form POST. + // We'll also stick some HTML reserved characters in the string value + // to test proper character escaping. + var message = new TestDirectedMessage(MessageTransport.Indirect) { + Age = 15, + Name = "c<b" + new string('a', 10 * 1024), + Location = new Uri("http://host/path"), + Recipient = new Uri("http://provider/path"), + }; + Response response = this.Channel.Send(message); + Assert.AreEqual(HttpStatusCode.OK, response.Status, "A form redirect should be an HTTP successful response."); + Assert.IsNull(response.Headers[HttpResponseHeader.Location], "There should not be a redirection header in the response."); + string body = response.Body; + StringAssert.Contains(body, "<form "); + StringAssert.Contains(body, "action=\"http://provider/path\""); + StringAssert.Contains(body, "method=\"post\""); + StringAssert.Contains(body, "<input type=\"hidden\" name=\"age\" value=\"15\" />"); + StringAssert.Contains(body, "<input type=\"hidden\" name=\"Location\" value=\"http://host/path\" />"); + StringAssert.Contains(body, "<input type=\"hidden\" name=\"Name\" value=\"" + HttpUtility.HtmlEncode(message.Name) + "\" />"); + StringAssert.Contains(body, ".submit()", "There should be some javascript to automate form submission."); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SendIndirectMessageFormPostNullMessage() { + TestBadChannel badChannel = new TestBadChannel(false); + badChannel.CreateFormPostResponse(null, new Dictionary<string, string>()); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void SendIndirectMessageFormPostEmptyRecipient() { + TestBadChannel badChannel = new TestBadChannel(false); + var message = new TestDirectedMessage(MessageTransport.Indirect); + badChannel.CreateFormPostResponse(message, new Dictionary<string, string>()); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SendIndirectMessageFormPostNullFields() { + TestBadChannel badChannel = new TestBadChannel(false); + var message = new TestDirectedMessage(MessageTransport.Indirect); + message.Recipient = new Uri("http://someserver"); + badChannel.CreateFormPostResponse(message, null); + } + + /// <summary> + /// Tests that a direct message is sent when the appropriate message type is provided. + /// </summary> + /// <remarks> + /// Since this is a mock channel that doesn't actually formulate a direct message response, + /// we just check that the right method was called. + /// </remarks> + [TestMethod, ExpectedException(typeof(NotImplementedException), "SendDirectMessageResponse")] + public void SendDirectMessageResponse() { + IProtocolMessage message = new TestMessage { + Age = 15, + Name = "Andrew", + Location = new Uri("http://host/path"), + }; + this.Channel.Send(message); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SendIndirectMessageNull() { + TestBadChannel badChannel = new TestBadChannel(false); + badChannel.SendIndirectMessage(null); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void ReceiveNull() { + TestBadChannel badChannel = new TestBadChannel(false); + badChannel.Receive(null, null); + } + + [TestMethod] + public void ReceiveUnrecognizedMessage() { + TestBadChannel badChannel = new TestBadChannel(false); + Assert.IsNull(badChannel.Receive(new Dictionary<string, string>(), null)); + } + + [TestMethod] + public void ReadFromRequestWithContext() { + var fields = GetStandardTestFields(FieldFill.AllRequired); + TestMessage expectedMessage = GetStandardTestMessage(FieldFill.AllRequired); + HttpRequest request = new HttpRequest("somefile", "http://someurl", MessagingUtilities.CreateQueryString(fields)); + HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter())); + IProtocolMessage message = this.Channel.ReadFromRequest(); + Assert.IsNotNull(message); + Assert.IsInstanceOfType(message, typeof(TestMessage)); + Assert.AreEqual(expectedMessage.Age, ((TestMessage)message).Age); + } + + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void ReadFromRequestNoContext() { + TestBadChannel badChannel = new TestBadChannel(false); + badChannel.ReadFromRequest(); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void ReadFromRequestNull() { + TestBadChannel badChannel = new TestBadChannel(false); + badChannel.ReadFromRequest(null); + } + + [TestMethod] + public void SendReplayProtectedMessageSetsNonce() { + TestReplayProtectedMessage message = new TestReplayProtectedMessage(MessageTransport.Indirect); + message.Recipient = new Uri("http://localtest"); + + this.Channel = CreateChannel(MessageProtections.ReplayProtection); + this.Channel.Send(message); + Assert.IsNotNull(((IReplayProtectedProtocolMessage)message).Nonce); + } + + [TestMethod, ExpectedException(typeof(InvalidSignatureException))] + public void ReceivedInvalidSignature() { + this.Channel = CreateChannel(MessageProtections.TamperProtection); + this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, true); + } + + [TestMethod] + public void ReceivedReplayProtectedMessageJustOnce() { + this.Channel = CreateChannel(MessageProtections.ReplayProtection); + this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); + } + + [TestMethod, ExpectedException(typeof(ReplayedMessageException))] + public void ReceivedReplayProtectedMessageTwice() { + this.Channel = CreateChannel(MessageProtections.ReplayProtection); + this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); + this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); + } + + [TestMethod, ExpectedException(typeof(ProtocolException))] + public void MessageExpirationWithoutTamperResistance() { + new TestChannel( + new TestMessageTypeProvider(), + new StandardExpirationBindingElement()); + } + + [TestMethod, ExpectedException(typeof(ProtocolException))] + public void TooManyBindingElementsProvidingSameProtection() { + new TestChannel( + new TestMessageTypeProvider(), + new MockSigningBindingElement(), + new MockSigningBindingElement()); + } + + [TestMethod] + public void BindingElementsOrdering() { + IChannelBindingElement transformA = new MockTransformationBindingElement("a"); + IChannelBindingElement transformB = new MockTransformationBindingElement("b"); + IChannelBindingElement sign = new MockSigningBindingElement(); + IChannelBindingElement replay = new MockReplayProtectionBindingElement(); + IChannelBindingElement expire = new StandardExpirationBindingElement(); + + Channel channel = new TestChannel( + new TestMessageTypeProvider(), + sign, + replay, + expire, + transformB, + transformA); + + Assert.AreEqual(5, channel.BindingElements.Count); + Assert.AreSame(transformB, channel.BindingElements[0]); + Assert.AreSame(transformA, channel.BindingElements[1]); + Assert.AreSame(replay, channel.BindingElements[2]); + Assert.AreSame(expire, channel.BindingElements[3]); + Assert.AreSame(sign, channel.BindingElements[4]); + } + + [TestMethod, ExpectedException(typeof(UnprotectedMessageException))] + public void InsufficientlyProtectedMessageSent() { + var message = new TestSignedDirectedMessage(MessageTransport.Direct); + message.Recipient = new Uri("http://localtest"); + this.Channel.Send(message); + } + + [TestMethod, ExpectedException(typeof(UnprotectedMessageException))] + public void InsufficientlyProtectedMessageReceived() { + this.Channel = CreateChannel(MessageProtections.None, MessageProtections.TamperProtection); + this.ParameterizedReceiveProtectedTest(DateTime.Now, false); + } + + [TestMethod, ExpectedException(typeof(ProtocolException))] + public void IncomingMessageMissingRequiredParameters() { + var fields = GetStandardTestFields(FieldFill.IdentifiableButNotAllRequired); + this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields)); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/CollectionAssert.cs b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs index b9f3da5..d06ef62 100644 --- a/src/DotNetOAuth.Test/Messaging/CollectionAssert.cs +++ b/src/DotNetOpenAuth.Test/Messaging/CollectionAssert.cs @@ -1,19 +1,19 @@ -//-----------------------------------------------------------------------
-// <copyright file="CollectionAssert.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System.Collections;
- using System.Collections.Generic;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- internal class CollectionAssert<T> {
- internal static void AreEquivalent(ICollection<T> expected, ICollection<T> actual) {
- ICollection expectedNonGeneric = new List<T>(expected);
- ICollection actualNonGeneric = new List<T>(actual);
- CollectionAssert.AreEquivalent(expectedNonGeneric, actualNonGeneric);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="CollectionAssert.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System.Collections; + using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal class CollectionAssert<T> { + internal static void AreEquivalent(ICollection<T> expected, ICollection<T> actual) { + ICollection expectedNonGeneric = new List<T>(expected); + ICollection actualNonGeneric = new List<T>(actual); + CollectionAssert.AreEquivalent(expectedNonGeneric, actualNonGeneric); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/HttpRequestInfoTests.cs b/src/DotNetOpenAuth.Test/Messaging/HttpRequestInfoTests.cs index 70fa1d0..5333f97 100644 --- a/src/DotNetOAuth.Test/Messaging/HttpRequestInfoTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/HttpRequestInfoTests.cs @@ -1,36 +1,36 @@ -//-----------------------------------------------------------------------
-// <copyright file="HttpRequestInfoTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System.Web;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class HttpRequestInfoTests : TestBase {
- [TestMethod]
- public void CtorRequest() {
- HttpRequest request = new HttpRequest("file", "http://someserver?a=b", "a=b");
- ////request.Headers["headername"] = "headervalue"; // PlatformNotSupportedException prevents us mocking this up
- HttpRequestInfo info = new HttpRequestInfo(request);
- Assert.AreEqual(request.Headers["headername"], info.Headers["headername"]);
- Assert.AreEqual(request.Url.Query, info.Query);
- Assert.AreEqual(request.QueryString["a"], info.QueryString["a"]);
- Assert.AreEqual(request.Url, info.Url);
- Assert.AreEqual(request.HttpMethod, info.HttpMethod);
- }
-
- /// <summary>
- /// Checks that a property dependent on another null property
- /// doesn't generate a NullReferenceException.
- /// </summary>
- [TestMethod]
- public void QueryBeforeSettingUrl() {
- HttpRequestInfo info = new HttpRequestInfo();
- Assert.IsNull(info.Query);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="HttpRequestInfoTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System.Web; + using DotNetOpenAuth.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class HttpRequestInfoTests : TestBase { + [TestMethod] + public void CtorRequest() { + HttpRequest request = new HttpRequest("file", "http://someserver?a=b", "a=b"); + ////request.Headers["headername"] = "headervalue"; // PlatformNotSupportedException prevents us mocking this up + HttpRequestInfo info = new HttpRequestInfo(request); + Assert.AreEqual(request.Headers["headername"], info.Headers["headername"]); + Assert.AreEqual(request.Url.Query, info.Query); + Assert.AreEqual(request.QueryString["a"], info.QueryString["a"]); + Assert.AreEqual(request.Url, info.Url); + Assert.AreEqual(request.HttpMethod, info.HttpMethod); + } + + /// <summary> + /// Checks that a property dependent on another null property + /// doesn't generate a NullReferenceException. + /// </summary> + [TestMethod] + public void QueryBeforeSettingUrl() { + HttpRequestInfo info = new HttpRequestInfo(); + Assert.IsNull(info.Query); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs index d2d87e1..62b6393 100644 --- a/src/DotNetOAuth.Test/Messaging/MessageSerializerTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs @@ -1,130 +1,130 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageSerializerTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Xml;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- /// <summary>
- /// Tests for the <see cref="MessageSerializer"/> class.
- /// </summary>
- [TestClass()]
- public class MessageSerializerTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void SerializeNull() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- serializer.Serialize(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void GetInvalidMessageType() {
- MessageSerializer.Get(typeof(string));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void GetNullType() {
- MessageSerializer.Get(null);
- }
-
- [TestMethod()]
- public void SerializeTest() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- var message = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
- var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
- IDictionary<string, string> actual = serializer.Serialize(message);
- Assert.AreEqual(4, actual.Count);
-
- // Test case sensitivity of generated dictionary
- Assert.IsFalse(actual.ContainsKey("Age"));
- Assert.IsTrue(actual.ContainsKey("age"));
-
- // Test contents of dictionary
- Assert.AreEqual(expected["age"], actual["age"]);
- Assert.AreEqual(expected["Name"], actual["Name"]);
- Assert.AreEqual(expected["Location"], actual["Location"]);
- Assert.AreEqual(expected["Timestamp"], actual["Timestamp"]);
- Assert.IsFalse(actual.ContainsKey("EmptyMember"));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void DeserializeNull() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- serializer.Deserialize(null, null);
- }
-
- [TestMethod]
- public void DeserializeSimple() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
- fields["Name"] = "Andrew";
- fields["age"] = "15";
- fields["Timestamp"] = "1990-01-01T00:00:00";
- var actual = (Mocks.TestMessage)serializer.Deserialize(fields, null);
- Assert.AreEqual(15, actual.Age);
- Assert.AreEqual("Andrew", actual.Name);
- Assert.AreEqual(DateTime.Parse("1/1/1990"), actual.Timestamp);
- Assert.IsNull(actual.EmptyMember);
- }
-
- /// <summary>
- /// This tests deserialization of a message that is comprised of [MessagePart]'s
- /// that are defined in multiple places in the inheritance tree.
- /// </summary>
- /// <remarks>
- /// The element sorting rules are first inheritance order, then alphabetical order.
- /// This test validates correct behavior on both.
- /// </remarks>
- [TestMethod]
- public void DeserializeVerifyElementOrdering() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestDerivedMessage));
- Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
- // We deliberately do this OUT of order,
- // since DataContractSerializer demands elements to be in
- // 1) inheritance then 2) alphabetical order.
- // Proper xml element order would be: Name, age, Second..., TheFirst...
- fields["TheFirstDerivedElement"] = "first";
- fields["age"] = "15";
- fields["Name"] = "Andrew";
- fields["SecondDerivedElement"] = "second";
- fields["explicit"] = "explicitValue";
- fields["private"] = "privateValue";
- var actual = (Mocks.TestDerivedMessage)serializer.Deserialize(fields, null);
- Assert.AreEqual(15, actual.Age);
- Assert.AreEqual("Andrew", actual.Name);
- Assert.AreEqual("first", actual.TheFirstDerivedElement);
- Assert.AreEqual("second", actual.SecondDerivedElement);
- Assert.AreEqual("explicitValue", ((Mocks.IBaseMessageExplicitMembers)actual).ExplicitProperty);
- Assert.AreEqual("privateValue", actual.PrivatePropertyAccessor);
- }
-
- [TestMethod]
- public void DeserializeWithExtraFields() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal);
- fields["age"] = "15";
- fields["Name"] = "Andrew";
- fields["Timestamp"] = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);
- // Add some field that is not recognized by the class. This simulates a querystring with
- // more parameters than are actually interesting to the protocol message.
- fields["someExtraField"] = "asdf";
- var actual = (Mocks.TestMessage)serializer.Deserialize(fields, null);
- Assert.AreEqual(15, actual.Age);
- Assert.AreEqual("Andrew", actual.Name);
- Assert.IsNull(actual.EmptyMember);
- }
-
- [TestMethod, ExpectedException(typeof(ProtocolException))]
- public void DeserializeInvalidMessage() {
- var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- var fields = GetStandardTestFields(FieldFill.AllRequired);
- fields["age"] = "-1"; // Set an disallowed value.
- serializer.Deserialize(fields, null);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageSerializerTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System; + using System.Collections.Generic; + using System.Xml; + using DotNetOpenAuth.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + /// <summary> + /// Tests for the <see cref="MessageSerializer"/> class. + /// </summary> + [TestClass()] + public class MessageSerializerTests : MessagingTestBase { + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void SerializeNull() { + var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); + serializer.Serialize(null); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void GetInvalidMessageType() { + MessageSerializer.Get(typeof(string)); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void GetNullType() { + MessageSerializer.Get(null); + } + + [TestMethod()] + public void SerializeTest() { + var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); + var message = GetStandardTestMessage(FieldFill.CompleteBeforeBindings); + var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings); + IDictionary<string, string> actual = serializer.Serialize(message); + Assert.AreEqual(4, actual.Count); + + // Test case sensitivity of generated dictionary + Assert.IsFalse(actual.ContainsKey("Age")); + Assert.IsTrue(actual.ContainsKey("age")); + + // Test contents of dictionary + Assert.AreEqual(expected["age"], actual["age"]); + Assert.AreEqual(expected["Name"], actual["Name"]); + Assert.AreEqual(expected["Location"], actual["Location"]); + Assert.AreEqual(expected["Timestamp"], actual["Timestamp"]); + Assert.IsFalse(actual.ContainsKey("EmptyMember")); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void DeserializeNull() { + var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); + serializer.Deserialize(null, null); + } + + [TestMethod] + public void DeserializeSimple() { + var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); + Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal); + fields["Name"] = "Andrew"; + fields["age"] = "15"; + fields["Timestamp"] = "1990-01-01T00:00:00"; + var actual = (Mocks.TestMessage)serializer.Deserialize(fields, null); + Assert.AreEqual(15, actual.Age); + Assert.AreEqual("Andrew", actual.Name); + Assert.AreEqual(DateTime.Parse("1/1/1990"), actual.Timestamp); + Assert.IsNull(actual.EmptyMember); + } + + /// <summary> + /// This tests deserialization of a message that is comprised of [MessagePart]'s + /// that are defined in multiple places in the inheritance tree. + /// </summary> + /// <remarks> + /// The element sorting rules are first inheritance order, then alphabetical order. + /// This test validates correct behavior on both. + /// </remarks> + [TestMethod] + public void DeserializeVerifyElementOrdering() { + var serializer = MessageSerializer.Get(typeof(Mocks.TestDerivedMessage)); + Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal); + // We deliberately do this OUT of order, + // since DataContractSerializer demands elements to be in + // 1) inheritance then 2) alphabetical order. + // Proper xml element order would be: Name, age, Second..., TheFirst... + fields["TheFirstDerivedElement"] = "first"; + fields["age"] = "15"; + fields["Name"] = "Andrew"; + fields["SecondDerivedElement"] = "second"; + fields["explicit"] = "explicitValue"; + fields["private"] = "privateValue"; + var actual = (Mocks.TestDerivedMessage)serializer.Deserialize(fields, null); + Assert.AreEqual(15, actual.Age); + Assert.AreEqual("Andrew", actual.Name); + Assert.AreEqual("first", actual.TheFirstDerivedElement); + Assert.AreEqual("second", actual.SecondDerivedElement); + Assert.AreEqual("explicitValue", ((Mocks.IBaseMessageExplicitMembers)actual).ExplicitProperty); + Assert.AreEqual("privateValue", actual.PrivatePropertyAccessor); + } + + [TestMethod] + public void DeserializeWithExtraFields() { + var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); + Dictionary<string, string> fields = new Dictionary<string, string>(StringComparer.Ordinal); + fields["age"] = "15"; + fields["Name"] = "Andrew"; + fields["Timestamp"] = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); + // Add some field that is not recognized by the class. This simulates a querystring with + // more parameters than are actually interesting to the protocol message. + fields["someExtraField"] = "asdf"; + var actual = (Mocks.TestMessage)serializer.Deserialize(fields, null); + Assert.AreEqual(15, actual.Age); + Assert.AreEqual("Andrew", actual.Name); + Assert.IsNull(actual.EmptyMember); + } + + [TestMethod, ExpectedException(typeof(ProtocolException))] + public void DeserializeInvalidMessage() { + var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage)); + var fields = GetStandardTestFields(FieldFill.AllRequired); + fields["age"] = "-1"; // Set an disallowed value. + serializer.Deserialize(fields, null); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/MessagingTestBase.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs index 403cd25..4413c67 100644 --- a/src/DotNetOAuth.Test/Messaging/MessagingTestBase.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs @@ -1,188 +1,188 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessagingTestBase.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test {
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Xml;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- /// <summary>
- /// The base class that all messaging test classes inherit from.
- /// </summary>
- public class MessagingTestBase : TestBase {
- internal enum FieldFill {
- /// <summary>
- /// An empty dictionary is returned.
- /// </summary>
- None,
-
- /// <summary>
- /// Only enough fields for the <see cref="TestMessageTypeProvider"/>
- /// to identify the message are included.
- /// </summary>
- IdentifiableButNotAllRequired,
-
- /// <summary>
- /// All fields marked as required are included.
- /// </summary>
- AllRequired,
-
- /// <summary>
- /// All user-fillable fields in the message, leaving out those whose
- /// values are to be set by channel binding elements.
- /// </summary>
- CompleteBeforeBindings,
- }
-
- internal Channel Channel { get; set; }
-
- [TestInitialize]
- public override void SetUp() {
- base.SetUp();
-
- this.Channel = new TestChannel();
- }
-
- internal static HttpRequestInfo CreateHttpRequestInfo(string method, IDictionary<string, string> fields) {
- string query = MessagingUtilities.CreateQueryString(fields);
- UriBuilder requestUri = new UriBuilder("http://localhost/path");
- WebHeaderCollection headers = new WebHeaderCollection();
- MemoryStream ms = new MemoryStream();
- if (method == "POST") {
- headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
- StreamWriter sw = new StreamWriter(ms);
- sw.Write(query);
- sw.Flush();
- ms.Position = 0;
- } else if (method == "GET") {
- requestUri.Query = query;
- } else {
- throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET");
- }
- HttpRequestInfo request = new HttpRequestInfo {
- HttpMethod = method,
- Url = requestUri.Uri,
- Headers = headers,
- InputStream = ms,
- };
-
- return request;
- }
-
- internal static Channel CreateChannel(MessageProtections capabilityAndRecognition) {
- return CreateChannel(capabilityAndRecognition, capabilityAndRecognition);
- }
-
- internal static Channel CreateChannel(MessageProtections capability, MessageProtections recognition) {
- var bindingElements = new List<IChannelBindingElement>();
- if (capability >= MessageProtections.TamperProtection) {
- bindingElements.Add(new MockSigningBindingElement());
- }
- if (capability >= MessageProtections.Expiration) {
- bindingElements.Add(new StandardExpirationBindingElement());
- }
- if (capability >= MessageProtections.ReplayProtection) {
- bindingElements.Add(new MockReplayProtectionBindingElement());
- }
-
- bool signing = false, expiration = false, replay = false;
- if (recognition >= MessageProtections.TamperProtection) {
- signing = true;
- }
- if (recognition >= MessageProtections.Expiration) {
- expiration = true;
- }
- if (recognition >= MessageProtections.ReplayProtection) {
- replay = true;
- }
-
- var typeProvider = new TestMessageTypeProvider(signing, expiration, replay);
- return new TestChannel(typeProvider, bindingElements.ToArray());
- }
-
- internal static IDictionary<string, string> GetStandardTestFields(FieldFill fill) {
- TestMessage expectedMessage = GetStandardTestMessage(fill);
-
- var fields = new Dictionary<string, string>();
- if (fill >= FieldFill.IdentifiableButNotAllRequired) {
- fields.Add("age", expectedMessage.Age.ToString());
- }
- if (fill >= FieldFill.AllRequired) {
- fields.Add("Timestamp", XmlConvert.ToString(expectedMessage.Timestamp, XmlDateTimeSerializationMode.Utc));
- }
- if (fill >= FieldFill.CompleteBeforeBindings) {
- fields.Add("Name", expectedMessage.Name);
- fields.Add("Location", expectedMessage.Location.AbsoluteUri);
- }
-
- return fields;
- }
-
- internal static TestMessage GetStandardTestMessage(FieldFill fill) {
- TestMessage message = new TestMessage();
- GetStandardTestMessage(fill, message);
- return message;
- }
-
- internal static void GetStandardTestMessage(FieldFill fill, TestMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- if (fill >= FieldFill.IdentifiableButNotAllRequired) {
- message.Age = 15;
- }
- if (fill >= FieldFill.AllRequired) {
- message.Timestamp = DateTime.SpecifyKind(DateTime.Parse("9/19/2008 8 AM"), DateTimeKind.Utc);
- }
- if (fill >= FieldFill.CompleteBeforeBindings) {
- message.Name = "Andrew";
- message.Location = new Uri("http://localtest/path");
- }
- }
-
- internal void ParameterizedReceiveTest(string method) {
- var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
- TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
-
- IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo(method, fields));
- Assert.IsNotNull(requestMessage);
- Assert.IsInstanceOfType(requestMessage, typeof(TestMessage));
- TestMessage actualMessage = (TestMessage)requestMessage;
- Assert.AreEqual(expectedMessage.Age, actualMessage.Age);
- Assert.AreEqual(expectedMessage.Name, actualMessage.Name);
- Assert.AreEqual(expectedMessage.Location, actualMessage.Location);
- }
-
- internal void ParameterizedReceiveProtectedTest(DateTime? utcCreatedDate, bool invalidSignature) {
- TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
- var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings);
- fields.Add("Signature", invalidSignature ? "badsig" : MockSigningBindingElement.MessageSignature);
- fields.Add("Nonce", "someNonce");
- if (utcCreatedDate.HasValue) {
- utcCreatedDate = DateTime.Parse(utcCreatedDate.Value.ToUniversalTime().ToString()); // round off the milliseconds so comparisons work later
- fields.Add("created_on", XmlConvert.ToString(utcCreatedDate.Value, XmlDateTimeSerializationMode.Utc));
- }
- IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields));
- Assert.IsNotNull(requestMessage);
- Assert.IsInstanceOfType(requestMessage, typeof(TestSignedDirectedMessage));
- TestSignedDirectedMessage actualMessage = (TestSignedDirectedMessage)requestMessage;
- Assert.AreEqual(expectedMessage.Age, actualMessage.Age);
- Assert.AreEqual(expectedMessage.Name, actualMessage.Name);
- Assert.AreEqual(expectedMessage.Location, actualMessage.Location);
- if (utcCreatedDate.HasValue) {
- IExpiringProtocolMessage expiringMessage = (IExpiringProtocolMessage)requestMessage;
- Assert.AreEqual(utcCreatedDate.Value, expiringMessage.UtcCreationDate);
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessagingTestBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Xml; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Test.Mocks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + /// <summary> + /// The base class that all messaging test classes inherit from. + /// </summary> + public class MessagingTestBase : TestBase { + internal enum FieldFill { + /// <summary> + /// An empty dictionary is returned. + /// </summary> + None, + + /// <summary> + /// Only enough fields for the <see cref="TestMessageTypeProvider"/> + /// to identify the message are included. + /// </summary> + IdentifiableButNotAllRequired, + + /// <summary> + /// All fields marked as required are included. + /// </summary> + AllRequired, + + /// <summary> + /// All user-fillable fields in the message, leaving out those whose + /// values are to be set by channel binding elements. + /// </summary> + CompleteBeforeBindings, + } + + internal Channel Channel { get; set; } + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + + this.Channel = new TestChannel(); + } + + internal static HttpRequestInfo CreateHttpRequestInfo(string method, IDictionary<string, string> fields) { + string query = MessagingUtilities.CreateQueryString(fields); + UriBuilder requestUri = new UriBuilder("http://localhost/path"); + WebHeaderCollection headers = new WebHeaderCollection(); + MemoryStream ms = new MemoryStream(); + if (method == "POST") { + headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); + StreamWriter sw = new StreamWriter(ms); + sw.Write(query); + sw.Flush(); + ms.Position = 0; + } else if (method == "GET") { + requestUri.Query = query; + } else { + throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET"); + } + HttpRequestInfo request = new HttpRequestInfo { + HttpMethod = method, + Url = requestUri.Uri, + Headers = headers, + InputStream = ms, + }; + + return request; + } + + internal static Channel CreateChannel(MessageProtections capabilityAndRecognition) { + return CreateChannel(capabilityAndRecognition, capabilityAndRecognition); + } + + internal static Channel CreateChannel(MessageProtections capability, MessageProtections recognition) { + var bindingElements = new List<IChannelBindingElement>(); + if (capability >= MessageProtections.TamperProtection) { + bindingElements.Add(new MockSigningBindingElement()); + } + if (capability >= MessageProtections.Expiration) { + bindingElements.Add(new StandardExpirationBindingElement()); + } + if (capability >= MessageProtections.ReplayProtection) { + bindingElements.Add(new MockReplayProtectionBindingElement()); + } + + bool signing = false, expiration = false, replay = false; + if (recognition >= MessageProtections.TamperProtection) { + signing = true; + } + if (recognition >= MessageProtections.Expiration) { + expiration = true; + } + if (recognition >= MessageProtections.ReplayProtection) { + replay = true; + } + + var typeProvider = new TestMessageTypeProvider(signing, expiration, replay); + return new TestChannel(typeProvider, bindingElements.ToArray()); + } + + internal static IDictionary<string, string> GetStandardTestFields(FieldFill fill) { + TestMessage expectedMessage = GetStandardTestMessage(fill); + + var fields = new Dictionary<string, string>(); + if (fill >= FieldFill.IdentifiableButNotAllRequired) { + fields.Add("age", expectedMessage.Age.ToString()); + } + if (fill >= FieldFill.AllRequired) { + fields.Add("Timestamp", XmlConvert.ToString(expectedMessage.Timestamp, XmlDateTimeSerializationMode.Utc)); + } + if (fill >= FieldFill.CompleteBeforeBindings) { + fields.Add("Name", expectedMessage.Name); + fields.Add("Location", expectedMessage.Location.AbsoluteUri); + } + + return fields; + } + + internal static TestMessage GetStandardTestMessage(FieldFill fill) { + TestMessage message = new TestMessage(); + GetStandardTestMessage(fill, message); + return message; + } + + internal static void GetStandardTestMessage(FieldFill fill, TestMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + if (fill >= FieldFill.IdentifiableButNotAllRequired) { + message.Age = 15; + } + if (fill >= FieldFill.AllRequired) { + message.Timestamp = DateTime.SpecifyKind(DateTime.Parse("9/19/2008 8 AM"), DateTimeKind.Utc); + } + if (fill >= FieldFill.CompleteBeforeBindings) { + message.Name = "Andrew"; + message.Location = new Uri("http://localtest/path"); + } + } + + internal void ParameterizedReceiveTest(string method) { + var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings); + TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings); + + IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo(method, fields)); + Assert.IsNotNull(requestMessage); + Assert.IsInstanceOfType(requestMessage, typeof(TestMessage)); + TestMessage actualMessage = (TestMessage)requestMessage; + Assert.AreEqual(expectedMessage.Age, actualMessage.Age); + Assert.AreEqual(expectedMessage.Name, actualMessage.Name); + Assert.AreEqual(expectedMessage.Location, actualMessage.Location); + } + + internal void ParameterizedReceiveProtectedTest(DateTime? utcCreatedDate, bool invalidSignature) { + TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings); + var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings); + fields.Add("Signature", invalidSignature ? "badsig" : MockSigningBindingElement.MessageSignature); + fields.Add("Nonce", "someNonce"); + if (utcCreatedDate.HasValue) { + utcCreatedDate = DateTime.Parse(utcCreatedDate.Value.ToUniversalTime().ToString()); // round off the milliseconds so comparisons work later + fields.Add("created_on", XmlConvert.ToString(utcCreatedDate.Value, XmlDateTimeSerializationMode.Utc)); + } + IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields)); + Assert.IsNotNull(requestMessage); + Assert.IsInstanceOfType(requestMessage, typeof(TestSignedDirectedMessage)); + TestSignedDirectedMessage actualMessage = (TestSignedDirectedMessage)requestMessage; + Assert.AreEqual(expectedMessage.Age, actualMessage.Age); + Assert.AreEqual(expectedMessage.Name, actualMessage.Name); + Assert.AreEqual(expectedMessage.Location, actualMessage.Location); + if (utcCreatedDate.HasValue) { + IExpiringProtocolMessage expiringMessage = (IExpiringProtocolMessage)requestMessage; + Assert.AreEqual(utcCreatedDate.Value, expiringMessage.UtcCreationDate); + } + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs index f5c5248..fc60ef6 100644 --- a/src/DotNetOAuth.Test/Messaging/MessagingUtilitiesTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs @@ -1,99 +1,99 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessagingUtilitiesTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging
-{
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.IO;
- using System.Net;
- using System.Web;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessagingUtilitiesTests : TestBase {
- [TestMethod]
- public void CreateQueryString() {
- var args = new Dictionary<string, string>();
- args.Add("a", "b");
- args.Add("c/d", "e/f");
- Assert.AreEqual("a=b&c%2fd=e%2ff", MessagingUtilities.CreateQueryString(args));
- }
-
- [TestMethod]
- public void CreateQueryStringEmptyCollection() {
- Assert.AreEqual(0, MessagingUtilities.CreateQueryString(new Dictionary<string, string>()).Length);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CreateQueryStringNullDictionary() {
- MessagingUtilities.CreateQueryString(null);
- }
-
- [TestMethod]
- public void AppendQueryArgs() {
- UriBuilder uri = new UriBuilder("http://baseline.org/page");
- var args = new Dictionary<string, string>();
- args.Add("a", "b");
- args.Add("c/d", "e/f");
- MessagingUtilities.AppendQueryArgs(uri, args);
- Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff", uri.Uri.AbsoluteUri);
- args.Clear();
- args.Add("g", "h");
- MessagingUtilities.AppendQueryArgs(uri, args);
- Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff&g=h", uri.Uri.AbsoluteUri);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void AppendQueryArgsNullUriBuilder() {
- MessagingUtilities.AppendQueryArgs(null, new Dictionary<string, string>());
- }
-
- [TestMethod]
- public void AppendQueryArgsNullDictionary() {
- MessagingUtilities.AppendQueryArgs(new UriBuilder(), null);
- }
-
- [TestMethod]
- public void ToDictionary() {
- NameValueCollection nvc = new NameValueCollection();
- nvc["a"] = "b";
- nvc["c"] = "d";
- Dictionary<string, string> actual = MessagingUtilities.ToDictionary(nvc);
- Assert.AreEqual(nvc.Count, actual.Count);
- Assert.AreEqual(nvc["a"], actual["a"]);
- Assert.AreEqual(nvc["c"], actual["c"]);
- }
-
- [TestMethod]
- public void ToDictionaryNull() {
- Assert.IsNull(MessagingUtilities.ToDictionary(null));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ApplyHeadersToResponseNullResponse() {
- MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ApplyHeadersToResponseNullHeaders() {
- MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponse(new StringWriter()));
- }
-
- [TestMethod]
- public void ApplyHeadersToResponse() {
- var headers = new WebHeaderCollection();
- headers[HttpResponseHeader.ContentType] = "application/binary";
-
- var response = new HttpResponse(new StringWriter());
- MessagingUtilities.ApplyHeadersToResponse(headers, response);
-
- Assert.AreEqual(headers[HttpResponseHeader.ContentType], response.ContentType);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessagingUtilitiesTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging +{ + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.IO; + using System.Net; + using System.Web; + using DotNetOpenAuth.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MessagingUtilitiesTests : TestBase { + [TestMethod] + public void CreateQueryString() { + var args = new Dictionary<string, string>(); + args.Add("a", "b"); + args.Add("c/d", "e/f"); + Assert.AreEqual("a=b&c%2fd=e%2ff", MessagingUtilities.CreateQueryString(args)); + } + + [TestMethod] + public void CreateQueryStringEmptyCollection() { + Assert.AreEqual(0, MessagingUtilities.CreateQueryString(new Dictionary<string, string>()).Length); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CreateQueryStringNullDictionary() { + MessagingUtilities.CreateQueryString(null); + } + + [TestMethod] + public void AppendQueryArgs() { + UriBuilder uri = new UriBuilder("http://baseline.org/page"); + var args = new Dictionary<string, string>(); + args.Add("a", "b"); + args.Add("c/d", "e/f"); + MessagingUtilities.AppendQueryArgs(uri, args); + Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff", uri.Uri.AbsoluteUri); + args.Clear(); + args.Add("g", "h"); + MessagingUtilities.AppendQueryArgs(uri, args); + Assert.AreEqual("http://baseline.org/page?a=b&c%2fd=e%2ff&g=h", uri.Uri.AbsoluteUri); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void AppendQueryArgsNullUriBuilder() { + MessagingUtilities.AppendQueryArgs(null, new Dictionary<string, string>()); + } + + [TestMethod] + public void AppendQueryArgsNullDictionary() { + MessagingUtilities.AppendQueryArgs(new UriBuilder(), null); + } + + [TestMethod] + public void ToDictionary() { + NameValueCollection nvc = new NameValueCollection(); + nvc["a"] = "b"; + nvc["c"] = "d"; + Dictionary<string, string> actual = MessagingUtilities.ToDictionary(nvc); + Assert.AreEqual(nvc.Count, actual.Count); + Assert.AreEqual(nvc["a"], actual["a"]); + Assert.AreEqual(nvc["c"], actual["c"]); + } + + [TestMethod] + public void ToDictionaryNull() { + Assert.IsNull(MessagingUtilities.ToDictionary(null)); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void ApplyHeadersToResponseNullResponse() { + MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), null); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void ApplyHeadersToResponseNullHeaders() { + MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponse(new StringWriter())); + } + + [TestMethod] + public void ApplyHeadersToResponse() { + var headers = new WebHeaderCollection(); + headers[HttpResponseHeader.ContentType] = "application/binary"; + + var response = new HttpResponse(new StringWriter()); + MessagingUtilities.ApplyHeadersToResponse(headers, response); + + Assert.AreEqual(headers[HttpResponseHeader.ContentType], response.ContentType); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/ProtocolExceptionTests.cs b/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs index 0e01e33..a2e3eaa 100644 --- a/src/DotNetOAuth.Test/Messaging/ProtocolExceptionTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ProtocolExceptionTests.cs @@ -1,97 +1,97 @@ -//-----------------------------------------------------------------------
-// <copyright file="ProtocolExceptionTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ProtocolExceptionTests : TestBase {
- [TestMethod]
- public void CtorDefault() {
- ProtocolException ex = new ProtocolException();
- }
-
- [TestMethod]
- public void CtorWithTextMessage() {
- ProtocolException ex = new ProtocolException("message");
- Assert.AreEqual("message", ex.Message);
- }
-
- [TestMethod]
- public void CtorWithTextMessageAndInnerException() {
- Exception innerException = new Exception();
- ProtocolException ex = new ProtocolException("message", innerException);
- Assert.AreEqual("message", ex.Message);
- Assert.AreSame(innerException, ex.InnerException);
- }
-
- [TestMethod]
- public void CtorWithProtocolMessage() {
- IProtocolMessage request = new Mocks.TestMessage();
- Uri receiver = new Uri("http://receiver");
- ProtocolException ex = new ProtocolException("some error occurred", request, receiver);
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- Assert.AreEqual("some error occurred", ex.Message);
- Assert.AreSame(receiver, msg.Recipient);
- Assert.AreEqual(request.ProtocolVersion, msg.ProtocolVersion);
- Assert.AreEqual(request.Transport, msg.Transport);
- msg.EnsureValidMessage();
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorWithNullProtocolMessage() {
- new ProtocolException("message", null, new Uri("http://receiver"));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorWithNullReceiver() {
- new ProtocolException("message", new Mocks.TestDirectedMessage(MessageTransport.Indirect), null);
- }
-
- /// <summary>
- /// Tests that exceptions being sent as direct responses do not need an explicit receiver.
- /// </summary>
- [TestMethod]
- public void CtorUndirectedMessageWithNullReceiver() {
- IProtocolMessage request = new Mocks.TestDirectedMessage(MessageTransport.Direct);
- ProtocolException ex = new ProtocolException("message", request, null);
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- Assert.IsNull(msg.Recipient);
- Assert.AreEqual(request.ProtocolVersion, msg.ProtocolVersion);
- Assert.AreEqual(request.Transport, msg.Transport);
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void ProtocolVersionWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- var temp = msg.ProtocolVersion;
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void TransportWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- var temp = msg.Transport;
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void RecipientWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- var temp = msg.Recipient;
- }
-
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void EnsureValidMessageWithoutMessage() {
- ProtocolException ex = new ProtocolException();
- IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex;
- msg.EnsureValidMessage();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ProtocolExceptionTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System; + using DotNetOpenAuth.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ProtocolExceptionTests : TestBase { + [TestMethod] + public void CtorDefault() { + ProtocolException ex = new ProtocolException(); + } + + [TestMethod] + public void CtorWithTextMessage() { + ProtocolException ex = new ProtocolException("message"); + Assert.AreEqual("message", ex.Message); + } + + [TestMethod] + public void CtorWithTextMessageAndInnerException() { + Exception innerException = new Exception(); + ProtocolException ex = new ProtocolException("message", innerException); + Assert.AreEqual("message", ex.Message); + Assert.AreSame(innerException, ex.InnerException); + } + + [TestMethod] + public void CtorWithProtocolMessage() { + IProtocolMessage request = new Mocks.TestMessage(); + Uri receiver = new Uri("http://receiver"); + ProtocolException ex = new ProtocolException("some error occurred", request, receiver); + IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex; + Assert.AreEqual("some error occurred", ex.Message); + Assert.AreSame(receiver, msg.Recipient); + Assert.AreEqual(request.ProtocolVersion, msg.ProtocolVersion); + Assert.AreEqual(request.Transport, msg.Transport); + msg.EnsureValidMessage(); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorWithNullProtocolMessage() { + new ProtocolException("message", null, new Uri("http://receiver")); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorWithNullReceiver() { + new ProtocolException("message", new Mocks.TestDirectedMessage(MessageTransport.Indirect), null); + } + + /// <summary> + /// Tests that exceptions being sent as direct responses do not need an explicit receiver. + /// </summary> + [TestMethod] + public void CtorUndirectedMessageWithNullReceiver() { + IProtocolMessage request = new Mocks.TestDirectedMessage(MessageTransport.Direct); + ProtocolException ex = new ProtocolException("message", request, null); + IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex; + Assert.IsNull(msg.Recipient); + Assert.AreEqual(request.ProtocolVersion, msg.ProtocolVersion); + Assert.AreEqual(request.Transport, msg.Transport); + } + + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void ProtocolVersionWithoutMessage() { + ProtocolException ex = new ProtocolException(); + IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex; + var temp = msg.ProtocolVersion; + } + + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void TransportWithoutMessage() { + ProtocolException ex = new ProtocolException(); + IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex; + var temp = msg.Transport; + } + + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void RecipientWithoutMessage() { + ProtocolException ex = new ProtocolException(); + IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex; + var temp = msg.Recipient; + } + + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void EnsureValidMessageWithoutMessage() { + ProtocolException ex = new ProtocolException(); + IDirectedProtocolMessage msg = (IDirectedProtocolMessage)ex; + msg.EnsureValidMessage(); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs index 90c64dc..da5275b 100644 --- a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs @@ -1,24 +1,24 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageDescriptionTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using DotNetOAuth.Messaging.Reflection;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessageDescriptionTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void GetNull() {
- MessageDescription.Get(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void GetNonMessageType() {
- MessageDescription.Get(typeof(string));
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageDescriptionTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging.Reflection { + using System; + using DotNetOpenAuth.Messaging.Reflection; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MessageDescriptionTests : MessagingTestBase { + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void GetNull() { + MessageDescription.Get(null); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void GetNonMessageType() { + MessageDescription.Get(typeof(string)); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs index 143e6b8..039743e 100644 --- a/src/DotNetOAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDictionaryTests.cs @@ -1,347 +1,347 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageDictionaryTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Xml;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessageDictionaryTests : MessagingTestBase {
- private Mocks.TestMessage message;
-
- [TestInitialize]
- public override void SetUp() {
- base.SetUp();
-
- this.message = new Mocks.TestMessage();
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNull() {
- new MessageDictionary(null);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Values
- /// </summary>
- [TestMethod]
- public void Values() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Collection<string> expected = new Collection<string> {
- this.message.Age.ToString(),
- XmlConvert.ToString(DateTime.SpecifyKind(this.message.Timestamp, DateTimeKind.Utc), XmlDateTimeSerializationMode.Utc),
- };
- CollectionAssert<string>.AreEquivalent(expected, target.Values);
-
- this.message.Age = 15;
- this.message.Location = new Uri("http://localtest");
- this.message.Name = "Andrew";
- target["extra"] = "a";
- expected = new Collection<string> {
- this.message.Age.ToString(),
- this.message.Location.AbsoluteUri,
- this.message.Name,
- XmlConvert.ToString(DateTime.SpecifyKind(this.message.Timestamp, DateTimeKind.Utc), XmlDateTimeSerializationMode.Utc),
- "a",
- };
- CollectionAssert<string>.AreEquivalent(expected, target.Values);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Keys
- /// </summary>
- [TestMethod]
- public void Keys() {
- // We expect that non-nullable value type fields will automatically have keys
- // in the dictionary for them.
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Collection<string> expected = new Collection<string> {
- "age",
- "Timestamp",
- };
- CollectionAssert<string>.AreEquivalent(expected, target.Keys);
-
- this.message.Name = "Andrew";
- expected.Add("Name");
- target["extraField"] = string.Empty;
- expected.Add("extraField");
- CollectionAssert<string>.AreEquivalent(expected, target.Keys);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Item
- /// </summary>
- [TestMethod]
- public void Item() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
-
- // Test setting of declared message properties.
- this.message.Age = 15;
- Assert.AreEqual("15", target["age"]);
- target["age"] = "13";
- Assert.AreEqual(13, this.message.Age);
-
- // Test setting extra fields
- target["extra"] = "fun";
- Assert.AreEqual("fun", target["extra"]);
- Assert.AreEqual("fun", ((IProtocolMessage)this.message).ExtraData["extra"]);
-
- // Test clearing extra fields
- target["extra"] = null;
- Assert.IsFalse(target.ContainsKey("extra"));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.IsReadOnly
- /// </summary>
- [TestMethod]
- public void IsReadOnly() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- Assert.IsFalse(target.IsReadOnly);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Count
- /// </summary>
- [TestMethod]
- public void Count() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target;
- Assert.AreEqual(targetDictionary.Keys.Count, target.Count);
- targetDictionary["extraField"] = "hi";
- Assert.AreEqual(targetDictionary.Keys.Count, target.Count);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.String<<.GetEnumerator
- /// </summary>
- [TestMethod]
- public void GetEnumerator() {
- IEnumerable<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target;
- var keys = targetDictionary.Keys.GetEnumerator();
- var values = targetDictionary.Values.GetEnumerator();
- IEnumerator<KeyValuePair<string, string>> actual = target.GetEnumerator();
-
- bool keysLast = true, valuesLast = true, actualLast = true;
- while (true) {
- keysLast = keys.MoveNext();
- valuesLast = values.MoveNext();
- actualLast = actual.MoveNext();
- if (!keysLast || !valuesLast || !actualLast) {
- break;
- }
-
- Assert.AreEqual(keys.Current, actual.Current.Key);
- Assert.AreEqual(values.Current, actual.Current.Value);
- }
- Assert.IsTrue(keysLast == valuesLast && keysLast == actualLast);
- }
-
- [TestMethod]
- public void GetEnumeratorUntyped() {
- IEnumerable target = new MessageDictionary(this.message);
- IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target;
- var keys = targetDictionary.Keys.GetEnumerator();
- var values = targetDictionary.Values.GetEnumerator();
- IEnumerator actual = target.GetEnumerator();
-
- bool keysLast = true, valuesLast = true, actualLast = true;
- while (true) {
- keysLast = keys.MoveNext();
- valuesLast = values.MoveNext();
- actualLast = actual.MoveNext();
- if (!keysLast || !valuesLast || !actualLast) {
- break;
- }
-
- KeyValuePair<string, string> current = (KeyValuePair<string, string>)actual.Current;
- Assert.AreEqual(keys.Current, current.Key);
- Assert.AreEqual(values.Current, current.Value);
- }
- Assert.IsTrue(keysLast == valuesLast && keysLast == actualLast);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.TryGetValue
- /// </summary>
- [TestMethod]
- public void TryGetValue() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- this.message.Name = "andrew";
- string name;
- Assert.IsTrue(target.TryGetValue("Name", out name));
- Assert.AreEqual(this.message.Name, name);
-
- Assert.IsFalse(target.TryGetValue("name", out name));
- Assert.IsNull(name);
-
- target["extra"] = "value";
- string extra;
- Assert.IsTrue(target.TryGetValue("extra", out extra));
- Assert.AreEqual("value", extra);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Remove
- /// </summary>
- [TestMethod]
- public void RemoveTest1() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- this.message.Name = "andrew";
- Assert.IsTrue(target.Remove("Name"));
- Assert.IsNull(this.message.Name);
- Assert.IsFalse(target.Remove("Name"));
-
- Assert.IsFalse(target.Remove("extra"));
- target["extra"] = "value";
- Assert.IsTrue(target.Remove("extra"));
- Assert.IsFalse(target.ContainsKey("extra"));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.ContainsKey
- /// </summary>
- [TestMethod]
- public void ContainsKey() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Assert.IsTrue(target.ContainsKey("age"), "Value type declared element should have a key.");
- Assert.IsFalse(target.ContainsKey("Name"), "Null declared element should NOT have a key.");
-
- Assert.IsFalse(target.ContainsKey("extra"));
- target["extra"] = "value";
- Assert.IsTrue(target.ContainsKey("extra"));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Add
- /// </summary>
- [TestMethod]
- public void AddByKeyAndValue() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("extra", "value");
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value")));
- target.Add("Name", "Andrew");
- Assert.AreEqual("Andrew", this.message.Name);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void AddNullValue() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("extra", null);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Add
- /// </summary>
- [TestMethod]
- public void AddByKeyValuePair() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add(new KeyValuePair<string, string>("extra", "value"));
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value")));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void AddExtraFieldThatAlreadyExists() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("extra", "value");
- target.Add("extra", "value");
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void AddDeclaredValueThatAlreadyExists() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- target.Add("Name", "andrew");
- target.Add("Name", "andrew");
- }
-
- [TestMethod]
- public void DefaultReferenceTypeDeclaredPropertyHasNoKey() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- Assert.IsFalse(target.ContainsKey("Name"), "A null value should result in no key.");
- Assert.IsFalse(target.Keys.Contains("Name"), "A null value should result in no key.");
- }
-
- [TestMethod]
- public void RemoveStructDeclaredProperty() {
- IDictionary<string, string> target = new MessageDictionary(this.message);
- this.message.Age = 5;
- Assert.IsTrue(target.ContainsKey("age"));
- target.Remove("age");
- Assert.IsTrue(target.ContainsKey("age"));
- Assert.AreEqual(0, this.message.Age);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Remove
- /// </summary>
- [TestMethod]
- public void RemoveByKeyValuePair() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- this.message.Name = "Andrew";
- Assert.IsFalse(target.Remove(new KeyValuePair<string, string>("Name", "andrew")));
- Assert.AreEqual("Andrew", this.message.Name);
- Assert.IsTrue(target.Remove(new KeyValuePair<string, string>("Name", "Andrew")));
- Assert.IsNull(this.message.Name);
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.CopyTo
- /// </summary>
- [TestMethod]
- public void CopyTo() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target);
- KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[target.Count + 1];
- int arrayIndex = 1;
- target.CopyTo(array, arrayIndex);
- Assert.AreEqual(new KeyValuePair<string, string>(), array[0]);
- for (int i = 1; i < array.Length; i++) {
- Assert.IsNotNull(array[i].Key);
- Assert.AreEqual(targetAsDictionary[array[i].Key], array[i].Value);
- }
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Contains
- /// </summary>
- [TestMethod]
- public void ContainsKeyValuePair() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target);
- Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("age", "1")));
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("age", "0")));
-
- targetAsDictionary["extra"] = "value";
- Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("extra", "Value")));
- Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value")));
- Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("wayoff", "value")));
- }
-
- /// <summary>
- /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Clear
- /// </summary>
- [TestMethod]
- public void Clear() {
- ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message);
- IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target);
- this.message.Name = "Andrew";
- this.message.Age = 15;
- targetAsDictionary["extra"] = "value";
- target.Clear();
- Assert.AreEqual(2, target.Count, "Clearing should remove all keys except for declared non-nullable structs.");
- Assert.IsFalse(targetAsDictionary.ContainsKey("extra"));
- Assert.IsNull(this.message.Name);
- Assert.AreEqual(0, this.message.Age);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageDictionaryTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging.Reflection { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Xml; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MessageDictionaryTests : MessagingTestBase { + private Mocks.TestMessage message; + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + + this.message = new Mocks.TestMessage(); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNull() { + new MessageDictionary(null); + } + + /// <summary> + /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Values + /// </summary> + [TestMethod] + public void Values() { + IDictionary<string, string> target = new MessageDictionary(this.message); + Collection<string> expected = new Collection<string> { + this.message.Age.ToString(), + XmlConvert.ToString(DateTime.SpecifyKind(this.message.Timestamp, DateTimeKind.Utc), XmlDateTimeSerializationMode.Utc), + }; + CollectionAssert<string>.AreEquivalent(expected, target.Values); + + this.message.Age = 15; + this.message.Location = new Uri("http://localtest"); + this.message.Name = "Andrew"; + target["extra"] = "a"; + expected = new Collection<string> { + this.message.Age.ToString(), + this.message.Location.AbsoluteUri, + this.message.Name, + XmlConvert.ToString(DateTime.SpecifyKind(this.message.Timestamp, DateTimeKind.Utc), XmlDateTimeSerializationMode.Utc), + "a", + }; + CollectionAssert<string>.AreEquivalent(expected, target.Values); + } + + /// <summary> + /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Keys + /// </summary> + [TestMethod] + public void Keys() { + // We expect that non-nullable value type fields will automatically have keys + // in the dictionary for them. + IDictionary<string, string> target = new MessageDictionary(this.message); + Collection<string> expected = new Collection<string> { + "age", + "Timestamp", + }; + CollectionAssert<string>.AreEquivalent(expected, target.Keys); + + this.message.Name = "Andrew"; + expected.Add("Name"); + target["extraField"] = string.Empty; + expected.Add("extraField"); + CollectionAssert<string>.AreEquivalent(expected, target.Keys); + } + + /// <summary> + /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Item + /// </summary> + [TestMethod] + public void Item() { + IDictionary<string, string> target = new MessageDictionary(this.message); + + // Test setting of declared message properties. + this.message.Age = 15; + Assert.AreEqual("15", target["age"]); + target["age"] = "13"; + Assert.AreEqual(13, this.message.Age); + + // Test setting extra fields + target["extra"] = "fun"; + Assert.AreEqual("fun", target["extra"]); + Assert.AreEqual("fun", ((IProtocolMessage)this.message).ExtraData["extra"]); + + // Test clearing extra fields + target["extra"] = null; + Assert.IsFalse(target.ContainsKey("extra")); + } + + /// <summary> + /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.IsReadOnly + /// </summary> + [TestMethod] + public void IsReadOnly() { + ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message); + Assert.IsFalse(target.IsReadOnly); + } + + /// <summary> + /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Count + /// </summary> + [TestMethod] + public void Count() { + ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message); + IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target; + Assert.AreEqual(targetDictionary.Keys.Count, target.Count); + targetDictionary["extraField"] = "hi"; + Assert.AreEqual(targetDictionary.Keys.Count, target.Count); + } + + /// <summary> + /// A test for System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String,System.String<<.GetEnumerator + /// </summary> + [TestMethod] + public void GetEnumerator() { + IEnumerable<KeyValuePair<string, string>> target = new MessageDictionary(this.message); + IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target; + var keys = targetDictionary.Keys.GetEnumerator(); + var values = targetDictionary.Values.GetEnumerator(); + IEnumerator<KeyValuePair<string, string>> actual = target.GetEnumerator(); + + bool keysLast = true, valuesLast = true, actualLast = true; + while (true) { + keysLast = keys.MoveNext(); + valuesLast = values.MoveNext(); + actualLast = actual.MoveNext(); + if (!keysLast || !valuesLast || !actualLast) { + break; + } + + Assert.AreEqual(keys.Current, actual.Current.Key); + Assert.AreEqual(values.Current, actual.Current.Value); + } + Assert.IsTrue(keysLast == valuesLast && keysLast == actualLast); + } + + [TestMethod] + public void GetEnumeratorUntyped() { + IEnumerable target = new MessageDictionary(this.message); + IDictionary<string, string> targetDictionary = (IDictionary<string, string>)target; + var keys = targetDictionary.Keys.GetEnumerator(); + var values = targetDictionary.Values.GetEnumerator(); + IEnumerator actual = target.GetEnumerator(); + + bool keysLast = true, valuesLast = true, actualLast = true; + while (true) { + keysLast = keys.MoveNext(); + valuesLast = values.MoveNext(); + actualLast = actual.MoveNext(); + if (!keysLast || !valuesLast || !actualLast) { + break; + } + + KeyValuePair<string, string> current = (KeyValuePair<string, string>)actual.Current; + Assert.AreEqual(keys.Current, current.Key); + Assert.AreEqual(values.Current, current.Value); + } + Assert.IsTrue(keysLast == valuesLast && keysLast == actualLast); + } + + /// <summary> + /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.TryGetValue + /// </summary> + [TestMethod] + public void TryGetValue() { + IDictionary<string, string> target = new MessageDictionary(this.message); + this.message.Name = "andrew"; + string name; + Assert.IsTrue(target.TryGetValue("Name", out name)); + Assert.AreEqual(this.message.Name, name); + + Assert.IsFalse(target.TryGetValue("name", out name)); + Assert.IsNull(name); + + target["extra"] = "value"; + string extra; + Assert.IsTrue(target.TryGetValue("extra", out extra)); + Assert.AreEqual("value", extra); + } + + /// <summary> + /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Remove + /// </summary> + [TestMethod] + public void RemoveTest1() { + IDictionary<string, string> target = new MessageDictionary(this.message); + this.message.Name = "andrew"; + Assert.IsTrue(target.Remove("Name")); + Assert.IsNull(this.message.Name); + Assert.IsFalse(target.Remove("Name")); + + Assert.IsFalse(target.Remove("extra")); + target["extra"] = "value"; + Assert.IsTrue(target.Remove("extra")); + Assert.IsFalse(target.ContainsKey("extra")); + } + + /// <summary> + /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.ContainsKey + /// </summary> + [TestMethod] + public void ContainsKey() { + IDictionary<string, string> target = new MessageDictionary(this.message); + Assert.IsTrue(target.ContainsKey("age"), "Value type declared element should have a key."); + Assert.IsFalse(target.ContainsKey("Name"), "Null declared element should NOT have a key."); + + Assert.IsFalse(target.ContainsKey("extra")); + target["extra"] = "value"; + Assert.IsTrue(target.ContainsKey("extra")); + } + + /// <summary> + /// A test for System.Collections.Generic.IDictionary<System.String,System.String>.Add + /// </summary> + [TestMethod] + public void AddByKeyAndValue() { + IDictionary<string, string> target = new MessageDictionary(this.message); + target.Add("extra", "value"); + Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value"))); + target.Add("Name", "Andrew"); + Assert.AreEqual("Andrew", this.message.Name); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void AddNullValue() { + IDictionary<string, string> target = new MessageDictionary(this.message); + target.Add("extra", null); + } + + /// <summary> + /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Add + /// </summary> + [TestMethod] + public void AddByKeyValuePair() { + IDictionary<string, string> target = new MessageDictionary(this.message); + target.Add(new KeyValuePair<string, string>("extra", "value")); + Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value"))); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void AddExtraFieldThatAlreadyExists() { + IDictionary<string, string> target = new MessageDictionary(this.message); + target.Add("extra", "value"); + target.Add("extra", "value"); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void AddDeclaredValueThatAlreadyExists() { + IDictionary<string, string> target = new MessageDictionary(this.message); + target.Add("Name", "andrew"); + target.Add("Name", "andrew"); + } + + [TestMethod] + public void DefaultReferenceTypeDeclaredPropertyHasNoKey() { + IDictionary<string, string> target = new MessageDictionary(this.message); + Assert.IsFalse(target.ContainsKey("Name"), "A null value should result in no key."); + Assert.IsFalse(target.Keys.Contains("Name"), "A null value should result in no key."); + } + + [TestMethod] + public void RemoveStructDeclaredProperty() { + IDictionary<string, string> target = new MessageDictionary(this.message); + this.message.Age = 5; + Assert.IsTrue(target.ContainsKey("age")); + target.Remove("age"); + Assert.IsTrue(target.ContainsKey("age")); + Assert.AreEqual(0, this.message.Age); + } + + /// <summary> + /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Remove + /// </summary> + [TestMethod] + public void RemoveByKeyValuePair() { + ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message); + this.message.Name = "Andrew"; + Assert.IsFalse(target.Remove(new KeyValuePair<string, string>("Name", "andrew"))); + Assert.AreEqual("Andrew", this.message.Name); + Assert.IsTrue(target.Remove(new KeyValuePair<string, string>("Name", "Andrew"))); + Assert.IsNull(this.message.Name); + } + + /// <summary> + /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.CopyTo + /// </summary> + [TestMethod] + public void CopyTo() { + ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message); + IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target); + KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[target.Count + 1]; + int arrayIndex = 1; + target.CopyTo(array, arrayIndex); + Assert.AreEqual(new KeyValuePair<string, string>(), array[0]); + for (int i = 1; i < array.Length; i++) { + Assert.IsNotNull(array[i].Key); + Assert.AreEqual(targetAsDictionary[array[i].Key], array[i].Value); + } + } + + /// <summary> + /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Contains + /// </summary> + [TestMethod] + public void ContainsKeyValuePair() { + ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message); + IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target); + Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("age", "1"))); + Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("age", "0"))); + + targetAsDictionary["extra"] = "value"; + Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("extra", "Value"))); + Assert.IsTrue(target.Contains(new KeyValuePair<string, string>("extra", "value"))); + Assert.IsFalse(target.Contains(new KeyValuePair<string, string>("wayoff", "value"))); + } + + /// <summary> + /// A test for System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.String<<.Clear + /// </summary> + [TestMethod] + public void Clear() { + ICollection<KeyValuePair<string, string>> target = new MessageDictionary(this.message); + IDictionary<string, string> targetAsDictionary = ((IDictionary<string, string>)target); + this.message.Name = "Andrew"; + this.message.Age = 15; + targetAsDictionary["extra"] = "value"; + target.Clear(); + Assert.AreEqual(2, target.Count, "Clearing should remove all keys except for declared non-nullable structs."); + Assert.IsFalse(targetAsDictionary.ContainsKey("extra")); + Assert.IsNull(this.message.Name); + Assert.AreEqual(0, this.message.Age); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/MessagePartTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessagePartTests.cs index 90ccca4..c3c69c2 100644 --- a/src/DotNetOAuth.Test/Messaging/Reflection/MessagePartTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessagePartTests.cs @@ -1,101 +1,101 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessagePartTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using System.Linq;
- using System.Reflection;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class MessagePartTests : MessagingTestBase {
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void OptionalNonNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableOptionalStruct));
- }
-
- [TestMethod]
- public void RequiredNonNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableRequiredStruct));
- }
-
- [TestMethod]
- public void OptionalNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNullableOptionalStruct));
- }
-
- [TestMethod]
- public void RequiredNullableStruct() {
- this.ParameterizedMessageTypeTest(typeof(MessageWithNullableRequiredStruct));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullMember() {
- new MessagePart(null, new MessagePartAttribute());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullAttribute() {
- PropertyInfo field = typeof(MessageWithNullableOptionalStruct).GetProperty("OptionalInt", BindingFlags.NonPublic | BindingFlags.Instance);
- new MessagePart(field, null);
- }
-
- [TestMethod]
- public void SetValue() {
- var message = new MessageWithNonNullableRequiredStruct();
- MessagePart part = this.ParameterizedMessageTypeTest(message.GetType());
- part.SetValue(message, "5");
- Assert.AreEqual(5, message.OptionalInt);
- }
-
- [TestMethod]
- public void GetValue() {
- var message = new MessageWithNonNullableRequiredStruct();
- message.OptionalInt = 8;
- MessagePart part = this.ParameterizedMessageTypeTest(message.GetType());
- Assert.AreEqual("8", part.GetValue(message));
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void NonFieldOrPropertyMember() {
- MemberInfo method = typeof(MessageWithNullableOptionalStruct).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance);
- new MessagePart(method, new MessagePartAttribute());
- }
-
- private MessagePart ParameterizedMessageTypeTest(Type messageType) {
- PropertyInfo field = messageType.GetProperty("OptionalInt", BindingFlags.NonPublic | BindingFlags.Instance);
- MessagePartAttribute attribute = field.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>().Single();
- return new MessagePart(field, attribute);
- }
-
- private class MessageWithNonNullableOptionalStruct : TestMessage {
- // Optional structs like int must be nullable for Optional to make sense.
- [MessagePart(IsRequired = false)]
- internal int OptionalInt { get; set; }
- }
-
- private class MessageWithNonNullableRequiredStruct : TestMessage {
- // This should work because a required field will always have a value so it
- // need not be nullable.
- [MessagePart(IsRequired = true)]
- internal int OptionalInt { get; set; }
- }
-
- private class MessageWithNullableOptionalStruct : TestMessage {
- // Optional structs like int must be nullable for Optional to make sense.
- [MessagePart(IsRequired = false)]
- internal int? OptionalInt { get; set; }
- }
-
- private class MessageWithNullableRequiredStruct : TestMessage {
- [MessagePart(IsRequired = true)]
- private int? OptionalInt { get; set; }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessagePartTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging.Reflection { + using System; + using System.Linq; + using System.Reflection; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.Test.Mocks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class MessagePartTests : MessagingTestBase { + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void OptionalNonNullableStruct() { + this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableOptionalStruct)); + } + + [TestMethod] + public void RequiredNonNullableStruct() { + this.ParameterizedMessageTypeTest(typeof(MessageWithNonNullableRequiredStruct)); + } + + [TestMethod] + public void OptionalNullableStruct() { + this.ParameterizedMessageTypeTest(typeof(MessageWithNullableOptionalStruct)); + } + + [TestMethod] + public void RequiredNullableStruct() { + this.ParameterizedMessageTypeTest(typeof(MessageWithNullableRequiredStruct)); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullMember() { + new MessagePart(null, new MessagePartAttribute()); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullAttribute() { + PropertyInfo field = typeof(MessageWithNullableOptionalStruct).GetProperty("OptionalInt", BindingFlags.NonPublic | BindingFlags.Instance); + new MessagePart(field, null); + } + + [TestMethod] + public void SetValue() { + var message = new MessageWithNonNullableRequiredStruct(); + MessagePart part = this.ParameterizedMessageTypeTest(message.GetType()); + part.SetValue(message, "5"); + Assert.AreEqual(5, message.OptionalInt); + } + + [TestMethod] + public void GetValue() { + var message = new MessageWithNonNullableRequiredStruct(); + message.OptionalInt = 8; + MessagePart part = this.ParameterizedMessageTypeTest(message.GetType()); + Assert.AreEqual("8", part.GetValue(message)); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void NonFieldOrPropertyMember() { + MemberInfo method = typeof(MessageWithNullableOptionalStruct).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance); + new MessagePart(method, new MessagePartAttribute()); + } + + private MessagePart ParameterizedMessageTypeTest(Type messageType) { + PropertyInfo field = messageType.GetProperty("OptionalInt", BindingFlags.NonPublic | BindingFlags.Instance); + MessagePartAttribute attribute = field.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>().Single(); + return new MessagePart(field, attribute); + } + + private class MessageWithNonNullableOptionalStruct : TestMessage { + // Optional structs like int must be nullable for Optional to make sense. + [MessagePart(IsRequired = false)] + internal int OptionalInt { get; set; } + } + + private class MessageWithNonNullableRequiredStruct : TestMessage { + // This should work because a required field will always have a value so it + // need not be nullable. + [MessagePart(IsRequired = true)] + internal int OptionalInt { get; set; } + } + + private class MessageWithNullableOptionalStruct : TestMessage { + // Optional structs like int must be nullable for Optional to make sense. + [MessagePart(IsRequired = false)] + internal int? OptionalInt { get; set; } + } + + private class MessageWithNullableRequiredStruct : TestMessage { + [MessagePart(IsRequired = true)] + private int? OptionalInt { get; set; } + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/Reflection/ValueMappingTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/ValueMappingTests.cs index 5def394..c4a79b5 100644 --- a/src/DotNetOAuth.Test/Messaging/Reflection/ValueMappingTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/ValueMappingTests.cs @@ -1,24 +1,24 @@ -//-----------------------------------------------------------------------
-// <copyright file="ValueMappingTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging.Reflection {
- using System;
- using DotNetOAuth.Messaging.Reflection;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ValueMappingTests {
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullToString() {
- new ValueMapping(null, str => new object());
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullToObject() {
- new ValueMapping(obj => obj.ToString(), null);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ValueMappingTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging.Reflection { + using System; + using DotNetOpenAuth.Messaging.Reflection; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ValueMappingTests { + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullToString() { + new ValueMapping(null, str => new object()); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullToObject() { + new ValueMapping(obj => obj.ToString(), null); + } + } +} diff --git a/src/DotNetOAuth.Test/Messaging/ResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs index 5020d7e..972bb58 100644 --- a/src/DotNetOAuth.Test/Messaging/ResponseTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs @@ -1,39 +1,39 @@ -//-----------------------------------------------------------------------
-// <copyright file="ResponseTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Messaging {
- using System;
- using System.IO;
- using System.Web;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ResponseTests : TestBase {
- [TestMethod, ExpectedException(typeof(InvalidOperationException))]
- public void SendWithoutAspNetContext() {
- new Response().Send();
- }
-
- [TestMethod]
- public void Send() {
- StringWriter writer = new StringWriter();
- HttpRequest httpRequest = new HttpRequest("file", "http://server", string.Empty);
- HttpResponse httpResponse = new HttpResponse(writer);
- HttpContext context = new HttpContext(httpRequest, httpResponse);
- HttpContext.Current = context;
-
- Response response = new Response();
- response.Status = System.Net.HttpStatusCode.OK;
- response.Headers["someHeaderName"] = "someHeaderValue";
- response.Body = "some body";
- response.Send();
- string results = writer.ToString();
- // For some reason the only output in test is the body... the headers require a web host
- Assert.AreEqual(response.Body, results);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ResponseTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Messaging { + using System; + using System.IO; + using System.Web; + using DotNetOpenAuth.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ResponseTests : TestBase { + [TestMethod, ExpectedException(typeof(InvalidOperationException))] + public void SendWithoutAspNetContext() { + new Response().Send(); + } + + [TestMethod] + public void Send() { + StringWriter writer = new StringWriter(); + HttpRequest httpRequest = new HttpRequest("file", "http://server", string.Empty); + HttpResponse httpResponse = new HttpResponse(writer); + HttpContext context = new HttpContext(httpRequest, httpResponse); + HttpContext.Current = context; + + Response response = new Response(); + response.Status = System.Net.HttpStatusCode.OK; + response.Headers["someHeaderName"] = "someHeaderValue"; + response.Body = "some body"; + response.Send(); + string results = writer.ToString(); + // For some reason the only output in test is the body... the headers require a web host + Assert.AreEqual(response.Body, results); + } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/InMemoryTokenManager.cs b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs index a39fd81..571bba7 100644 --- a/src/DotNetOAuth.Test/Mocks/InMemoryTokenManager.cs +++ b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs @@ -1,107 +1,106 @@ -//-----------------------------------------------------------------------
-// <copyright file="InMemoryTokenManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
- using DotNetOAuth.Test.OAuth;
-
- internal class InMemoryTokenManager : ITokenManager {
- private Dictionary<string, string> consumersAndSecrets = new Dictionary<string, string>();
- private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>();
-
- /// <summary>
- /// Request tokens that have been issued, and whether they have been authorized yet.
- /// </summary>
- private Dictionary<string, bool> requestTokens = new Dictionary<string, bool>();
-
- /// <summary>
- /// Access tokens that have been issued and have not yet expired.
- /// </summary>
- private List<string> accessTokens = new List<string>();
-
- #region ITokenManager Members
-
- public string GetConsumerSecret(string consumerKey) {
- return this.consumersAndSecrets[consumerKey];
- }
-
- public string GetTokenSecret(string token) {
- return this.tokensAndSecrets[token];
- }
-
- public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) {
- this.tokensAndSecrets[response.Token] = response.TokenSecret;
- this.requestTokens.Add(response.Token, false);
- }
-
- /// <summary>
- /// Checks whether a given request token has already been authorized
- /// by some user for use by the Consumer that requested it.
- /// </summary>
- /// <param name="requestToken">The Consumer's request token.</param>
- /// <returns>
- /// True if the request token has already been fully authorized by the user
- /// who owns the relevant protected resources. False if the token has not yet
- /// been authorized, has expired or does not exist.
- /// </returns>
- public bool IsRequestTokenAuthorized(string requestToken) {
- return this.requestTokens[requestToken];
- }
-
- public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) {
- // The following line is commented out because consumers don't mark their own tokens
- // as authorized... only the SPs do. And since we multi-purpose this test class for
- // both SPs and Consumers, we won't do this extra check.
- ////Debug.Assert(this.requestTokens[requestToken], "Unauthorized token should not be exchanged for access token.");
- this.requestTokens.Remove(requestToken);
- this.accessTokens.Add(accessToken);
- this.tokensAndSecrets.Remove(requestToken);
- this.tokensAndSecrets[accessToken] = accessTokenSecret;
- }
-
- /// <summary>
- /// Classifies a token as a request token or an access token.
- /// </summary>
- /// <param name="token">The token to classify.</param>
- /// <returns>Request or Access token, or invalid if the token is not recognized.</returns>
- public TokenType GetTokenType(string token) {
- if (this.requestTokens.ContainsKey(token)) {
- return TokenType.RequestToken;
- } else if (this.accessTokens.Contains(token)) {
- return TokenType.AccessToken;
- } else {
- return TokenType.InvalidToken;
- }
- }
-
- #endregion
-
- /// <summary>
- /// Tells a Service Provider's token manager about a consumer and its secret
- /// so that the SP can verify the Consumer's signed messages.
- /// </summary>
- /// <param name="consumerDescription">The consumer description.</param>
- internal void AddConsumer(ConsumerDescription consumerDescription) {
- this.consumersAndSecrets.Add(consumerDescription.ConsumerKey, consumerDescription.ConsumerSecret);
- }
-
- /// <summary>
- /// Marks an existing token as authorized.
- /// </summary>
- /// <param name="requestToken">The request token.</param>
- internal void AuthorizeRequestToken(string requestToken) {
- if (requestToken == null) {
- throw new ArgumentNullException("requestToken");
- }
-
- this.requestTokens[requestToken] = true;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="InMemoryTokenManager.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + + internal class InMemoryTokenManager : ITokenManager { + private Dictionary<string, string> consumersAndSecrets = new Dictionary<string, string>(); + private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); + + /// <summary> + /// Request tokens that have been issued, and whether they have been authorized yet. + /// </summary> + private Dictionary<string, bool> requestTokens = new Dictionary<string, bool>(); + + /// <summary> + /// Access tokens that have been issued and have not yet expired. + /// </summary> + private List<string> accessTokens = new List<string>(); + + #region ITokenManager Members + + public string GetConsumerSecret(string consumerKey) { + return this.consumersAndSecrets[consumerKey]; + } + + public string GetTokenSecret(string token) { + return this.tokensAndSecrets[token]; + } + + public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { + this.tokensAndSecrets[response.Token] = response.TokenSecret; + this.requestTokens.Add(response.Token, false); + } + + /// <summary> + /// Checks whether a given request token has already been authorized + /// by some user for use by the Consumer that requested it. + /// </summary> + /// <param name="requestToken">The Consumer's request token.</param> + /// <returns> + /// True if the request token has already been fully authorized by the user + /// who owns the relevant protected resources. False if the token has not yet + /// been authorized, has expired or does not exist. + /// </returns> + public bool IsRequestTokenAuthorized(string requestToken) { + return this.requestTokens[requestToken]; + } + + public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { + // The following line is commented out because consumers don't mark their own tokens + // as authorized... only the SPs do. And since we multi-purpose this test class for + // both SPs and Consumers, we won't do this extra check. + ////Debug.Assert(this.requestTokens[requestToken], "Unauthorized token should not be exchanged for access token."); + this.requestTokens.Remove(requestToken); + this.accessTokens.Add(accessToken); + this.tokensAndSecrets.Remove(requestToken); + this.tokensAndSecrets[accessToken] = accessTokenSecret; + } + + /// <summary> + /// Classifies a token as a request token or an access token. + /// </summary> + /// <param name="token">The token to classify.</param> + /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> + public TokenType GetTokenType(string token) { + if (this.requestTokens.ContainsKey(token)) { + return TokenType.RequestToken; + } else if (this.accessTokens.Contains(token)) { + return TokenType.AccessToken; + } else { + return TokenType.InvalidToken; + } + } + + #endregion + + /// <summary> + /// Tells a Service Provider's token manager about a consumer and its secret + /// so that the SP can verify the Consumer's signed messages. + /// </summary> + /// <param name="consumerDescription">The consumer description.</param> + internal void AddConsumer(ConsumerDescription consumerDescription) { + this.consumersAndSecrets.Add(consumerDescription.ConsumerKey, consumerDescription.ConsumerSecret); + } + + /// <summary> + /// Marks an existing token as authorized. + /// </summary> + /// <param name="requestToken">The request token.</param> + internal void AuthorizeRequestToken(string requestToken) { + if (requestToken == null) { + throw new ArgumentNullException("requestToken"); + } + + this.requestTokens[requestToken] = true; + } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/MockReplayProtectionBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs index ffd6044..5e65a59 100644 --- a/src/DotNetOAuth.Test/Mocks/MockReplayProtectionBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs @@ -1,48 +1,48 @@ -//-----------------------------------------------------------------------
-// <copyright file="MockReplayProtectionBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- internal class MockReplayProtectionBindingElement : IChannelBindingElement {
- private bool messageReceived;
-
- #region IChannelBindingElement Members
-
- MessageProtections IChannelBindingElement.Protection {
- get { return MessageProtections.ReplayProtection; }
- }
-
- bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) {
- var replayMessage = message as IReplayProtectedProtocolMessage;
- if (replayMessage != null) {
- replayMessage.Nonce = "someNonce";
- return true;
- }
-
- return false;
- }
-
- bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) {
- var replayMessage = message as IReplayProtectedProtocolMessage;
- if (replayMessage != null) {
- Assert.AreEqual("someNonce", replayMessage.Nonce, "The nonce didn't serialize correctly, or something");
- // this mock implementation passes the first time and fails subsequent times.
- if (this.messageReceived) {
- throw new ReplayedMessageException(message);
- }
- this.messageReceived = true;
- return true;
- }
-
- return false;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MockReplayProtectionBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal class MockReplayProtectionBindingElement : IChannelBindingElement { + private bool messageReceived; + + #region IChannelBindingElement Members + + MessageProtections IChannelBindingElement.Protection { + get { return MessageProtections.ReplayProtection; } + } + + bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) { + var replayMessage = message as IReplayProtectedProtocolMessage; + if (replayMessage != null) { + replayMessage.Nonce = "someNonce"; + return true; + } + + return false; + } + + bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) { + var replayMessage = message as IReplayProtectedProtocolMessage; + if (replayMessage != null) { + Assert.AreEqual("someNonce", replayMessage.Nonce, "The nonce didn't serialize correctly, or something"); + // this mock implementation passes the first time and fails subsequent times. + if (this.messageReceived) { + throw new ReplayedMessageException(message); + } + this.messageReceived = true; + return true; + } + + return false; + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/Mocks/MockSigningBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockSigningBindingElement.cs index 97298ad..eab9a39 100644 --- a/src/DotNetOAuth.Test/Mocks/MockSigningBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockSigningBindingElement.cs @@ -1,48 +1,48 @@ -//-----------------------------------------------------------------------
-// <copyright file="MockSigningBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
-
- internal class MockSigningBindingElement : IChannelBindingElement {
- internal const string MessageSignature = "mocksignature";
-
- #region IChannelBindingElement Members
-
- MessageProtections IChannelBindingElement.Protection {
- get { return MessageProtections.TamperProtection; }
- }
-
- bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) {
- ITamperResistantProtocolMessage signedMessage = message as ITamperResistantProtocolMessage;
- if (signedMessage != null) {
- signedMessage.Signature = MessageSignature;
- return true;
- }
-
- return false;
- }
-
- bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) {
- ITamperResistantProtocolMessage signedMessage = message as ITamperResistantProtocolMessage;
- if (signedMessage != null) {
- if (signedMessage.Signature != MessageSignature) {
- throw new InvalidSignatureException(message);
- }
- return true;
- }
-
- return false;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MockSigningBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + + internal class MockSigningBindingElement : IChannelBindingElement { + internal const string MessageSignature = "mocksignature"; + + #region IChannelBindingElement Members + + MessageProtections IChannelBindingElement.Protection { + get { return MessageProtections.TamperProtection; } + } + + bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) { + ITamperResistantProtocolMessage signedMessage = message as ITamperResistantProtocolMessage; + if (signedMessage != null) { + signedMessage.Signature = MessageSignature; + return true; + } + + return false; + } + + bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) { + ITamperResistantProtocolMessage signedMessage = message as ITamperResistantProtocolMessage; + if (signedMessage != null) { + if (signedMessage.Signature != MessageSignature) { + throw new InvalidSignatureException(message); + } + return true; + } + + return false; + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/Mocks/MockTransformationBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs index 8ee6036..7c5a240 100644 --- a/src/DotNetOAuth.Test/Mocks/MockTransformationBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs @@ -1,55 +1,55 @@ -//-----------------------------------------------------------------------
-// <copyright file="MockTransformationBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- internal class MockTransformationBindingElement : IChannelBindingElement {
- private string transform;
-
- internal MockTransformationBindingElement(string transform) {
- if (transform == null) {
- throw new ArgumentNullException("transform");
- }
-
- this.transform = transform;
- }
-
- #region IChannelBindingElement Members
-
- MessageProtections IChannelBindingElement.Protection {
- get { return MessageProtections.None; }
- }
-
- bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) {
- var testMessage = message as TestMessage;
- if (testMessage != null) {
- testMessage.Name = this.transform + testMessage.Name;
- return true;
- }
-
- return false;
- }
-
- bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) {
- var testMessage = message as TestMessage;
- if (testMessage != null) {
- StringAssert.StartsWith(testMessage.Name, this.transform);
- testMessage.Name = testMessage.Name.Substring(this.transform.Length);
- return true;
- }
-
- return false;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MockTransformationBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + internal class MockTransformationBindingElement : IChannelBindingElement { + private string transform; + + internal MockTransformationBindingElement(string transform) { + if (transform == null) { + throw new ArgumentNullException("transform"); + } + + this.transform = transform; + } + + #region IChannelBindingElement Members + + MessageProtections IChannelBindingElement.Protection { + get { return MessageProtections.None; } + } + + bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) { + var testMessage = message as TestMessage; + if (testMessage != null) { + testMessage.Name = this.transform + testMessage.Name; + return true; + } + + return false; + } + + bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) { + var testMessage = message as TestMessage; + if (testMessage != null) { + StringAssert.StartsWith(testMessage.Name, this.transform); + testMessage.Name = testMessage.Name.Substring(this.transform.Length); + return true; + } + + return false; + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestBadChannel.cs b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs index 781d65b..8fbfaf9 100644 --- a/src/DotNetOAuth.Test/Mocks/TestBadChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs @@ -1,54 +1,54 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestBadChannel.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A Channel derived type that passes null to the protected constructor.
- /// </summary>
- internal class TestBadChannel : Channel {
- internal TestBadChannel(bool badConstructorParam)
- : base(badConstructorParam ? null : new TestMessageTypeProvider()) {
- }
-
- internal new void Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- base.Create301RedirectResponse(message, fields);
- }
-
- internal new void CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- base.CreateFormPostResponse(message, fields);
- }
-
- internal new void SendIndirectMessage(IDirectedProtocolMessage message) {
- base.SendIndirectMessage(message);
- }
-
- internal new IProtocolMessage Receive(Dictionary<string, string> fields, MessageReceivingEndpoint recipient) {
- return base.Receive(fields, recipient);
- }
-
- internal new IProtocolMessage ReadFromRequest(HttpRequestInfo request) {
- return base.ReadFromRequest(request);
- }
-
- protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) {
- throw new NotImplementedException();
- }
-
- protected override IProtocolMessage ReadFromResponseInternal(System.IO.Stream responseStream) {
- throw new NotImplementedException();
- }
-
- protected override Response SendDirectMessageResponse(IProtocolMessage response) {
- throw new NotImplementedException();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestBadChannel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A Channel derived type that passes null to the protected constructor. + /// </summary> + internal class TestBadChannel : Channel { + internal TestBadChannel(bool badConstructorParam) + : base(badConstructorParam ? null : new TestMessageTypeProvider()) { + } + + internal new void Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) { + base.Create301RedirectResponse(message, fields); + } + + internal new void CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) { + base.CreateFormPostResponse(message, fields); + } + + internal new void SendIndirectMessage(IDirectedProtocolMessage message) { + base.SendIndirectMessage(message); + } + + internal new IProtocolMessage Receive(Dictionary<string, string> fields, MessageReceivingEndpoint recipient) { + return base.Receive(fields, recipient); + } + + internal new IProtocolMessage ReadFromRequest(HttpRequestInfo request) { + return base.ReadFromRequest(request); + } + + protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) { + throw new NotImplementedException(); + } + + protected override IProtocolMessage ReadFromResponseInternal(System.IO.Stream responseStream) { + throw new NotImplementedException(); + } + + protected override Response SendDirectMessageResponse(IProtocolMessage response) { + throw new NotImplementedException(); + } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestBaseMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestBaseMessage.cs index c874d23..ef0693c 100644 --- a/src/DotNetOAuth.Test/Mocks/TestBaseMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestBaseMessage.cs @@ -1,56 +1,56 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestBaseMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Runtime.Serialization;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
-
- internal interface IBaseMessageExplicitMembers {
- string ExplicitProperty { get; set; }
- }
-
- internal class TestBaseMessage : IProtocolMessage, IBaseMessageExplicitMembers {
- private Dictionary<string, string> extraData = new Dictionary<string, string>();
-
- [MessagePart("age", IsRequired = true)]
- public int Age { get; set; }
-
- [MessagePart]
- public string Name { get; set; }
-
- [MessagePart("explicit")]
- string IBaseMessageExplicitMembers.ExplicitProperty { get; set; }
-
- Version IProtocolMessage.ProtocolVersion {
- get { return new Version(1, 0); }
- }
-
- MessageProtections IProtocolMessage.RequiredProtection {
- get { return MessageProtections.None; }
- }
-
- MessageTransport IProtocolMessage.Transport {
- get { return MessageTransport.Indirect; }
- }
-
- IDictionary<string, string> IProtocolMessage.ExtraData {
- get { return this.extraData; }
- }
-
- internal string PrivatePropertyAccessor {
- get { return this.PrivateProperty; }
- set { this.PrivateProperty = value; }
- }
-
- [MessagePart("private")]
- private string PrivateProperty { get; set; }
-
- void IProtocolMessage.EnsureValidMessage() { }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestBaseMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Runtime.Serialization; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + + internal interface IBaseMessageExplicitMembers { + string ExplicitProperty { get; set; } + } + + internal class TestBaseMessage : IProtocolMessage, IBaseMessageExplicitMembers { + private Dictionary<string, string> extraData = new Dictionary<string, string>(); + + [MessagePart("age", IsRequired = true)] + public int Age { get; set; } + + [MessagePart] + public string Name { get; set; } + + [MessagePart("explicit")] + string IBaseMessageExplicitMembers.ExplicitProperty { get; set; } + + Version IProtocolMessage.ProtocolVersion { + get { return new Version(1, 0); } + } + + MessageProtections IProtocolMessage.RequiredProtection { + get { return MessageProtections.None; } + } + + MessageTransport IProtocolMessage.Transport { + get { return MessageTransport.Indirect; } + } + + IDictionary<string, string> IProtocolMessage.ExtraData { + get { return this.extraData; } + } + + internal string PrivatePropertyAccessor { + get { return this.PrivateProperty; } + set { this.PrivateProperty = value; } + } + + [MessagePart("private")] + private string PrivateProperty { get; set; } + + void IProtocolMessage.EnsureValidMessage() { } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestChannel.cs b/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs index 1f75e3f..ebb5858 100644 --- a/src/DotNetOAuth.Test/Mocks/TestChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs @@ -1,35 +1,35 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestChannel.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- internal class TestChannel : Channel {
- internal TestChannel()
- : this(new TestMessageTypeProvider()) {
- }
-
- internal TestChannel(IMessageTypeProvider messageTypeProvider, params IChannelBindingElement[] bindingElements)
- : base(messageTypeProvider, bindingElements) {
- }
-
- protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) {
- throw new NotImplementedException("Request");
- }
-
- protected override IProtocolMessage ReadFromResponseInternal(System.IO.Stream responseStream) {
- throw new NotImplementedException("ReadFromResponse");
- }
-
- protected override Response SendDirectMessageResponse(IProtocolMessage response) {
- throw new NotImplementedException("SendDirectMessageResponse");
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestChannel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + + internal class TestChannel : Channel { + internal TestChannel() + : this(new TestMessageTypeProvider()) { + } + + internal TestChannel(IMessageTypeProvider messageTypeProvider, params IChannelBindingElement[] bindingElements) + : base(messageTypeProvider, bindingElements) { + } + + protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) { + throw new NotImplementedException("Request"); + } + + protected override IProtocolMessage ReadFromResponseInternal(System.IO.Stream responseStream) { + throw new NotImplementedException("ReadFromResponse"); + } + + protected override Response SendDirectMessageResponse(IProtocolMessage response) { + throw new NotImplementedException("SendDirectMessageResponse"); + } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestDerivedMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestDerivedMessage.cs index 9d69495..de34329 100644 --- a/src/DotNetOAuth.Test/Mocks/TestDerivedMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestDerivedMessage.cs @@ -1,33 +1,33 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestDerivedMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System.Runtime.Serialization;
- using DotNetOAuth.Messaging;
-
- internal class TestDerivedMessage : TestBaseMessage {
- /// <summary>
- /// Gets or sets the first value.
- /// </summary>
- /// <remarks>
- /// This element should appear AFTER <see cref="SecondDerivedElement"/>
- /// due to alphabetical ordering rules, but after all the elements in the
- /// base class due to inheritance rules.
- /// </remarks>
- [MessagePart]
- public string TheFirstDerivedElement { get; set; }
-
- /// <summary>
- /// Gets or sets the second value.
- /// </summary>
- /// <remarks>
- /// This element should appear BEFORE <see cref="TheFirstDerivedElement"/>,
- /// but after all the elements in the base class.
- /// </remarks>
- [MessagePart]
- public string SecondDerivedElement { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestDerivedMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System.Runtime.Serialization; + using DotNetOpenAuth.Messaging; + + internal class TestDerivedMessage : TestBaseMessage { + /// <summary> + /// Gets or sets the first value. + /// </summary> + /// <remarks> + /// This element should appear AFTER <see cref="SecondDerivedElement"/> + /// due to alphabetical ordering rules, but after all the elements in the + /// base class due to inheritance rules. + /// </remarks> + [MessagePart] + public string TheFirstDerivedElement { get; set; } + + /// <summary> + /// Gets or sets the second value. + /// </summary> + /// <remarks> + /// This element should appear BEFORE <see cref="TheFirstDerivedElement"/>, + /// but after all the elements in the base class. + /// </remarks> + [MessagePart] + public string SecondDerivedElement { get; set; } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestDirectedMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs index 39aa6f3..67d0eb0 100644 --- a/src/DotNetOAuth.Test/Mocks/TestDirectedMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestDirectedMessage.cs @@ -1,43 +1,43 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestDirectedMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.ChannelElements;
-
- internal class TestDirectedMessage : TestMessage, IOAuthDirectedMessage {
- internal TestDirectedMessage() {
- }
-
- internal TestDirectedMessage(MessageTransport transport) : base(transport) {
- }
-
- #region IDirectedProtocolMessage Members
-
- public Uri Recipient { get; set; }
-
- #endregion
-
- #region IProtocolMessage Properties
-
- MessageProtections IProtocolMessage.RequiredProtection {
- get { return this.RequiredProtection; }
- }
-
- #endregion
-
- #region IOAuthDirectedMessage Members
-
- public HttpDeliveryMethods HttpMethods { get; internal set; }
-
- #endregion
-
- protected virtual MessageProtections RequiredProtection {
- get { return MessageProtections.None; }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestDirectedMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth.ChannelElements; + + internal class TestDirectedMessage : TestMessage, IOAuthDirectedMessage { + internal TestDirectedMessage() { + } + + internal TestDirectedMessage(MessageTransport transport) : base(transport) { + } + + #region IDirectedProtocolMessage Members + + public Uri Recipient { get; set; } + + #endregion + + #region IProtocolMessage Properties + + MessageProtections IProtocolMessage.RequiredProtection { + get { return this.RequiredProtection; } + } + + #endregion + + #region IOAuthDirectedMessage Members + + public HttpDeliveryMethods HttpMethods { get; internal set; } + + #endregion + + protected virtual MessageProtections RequiredProtection { + get { return MessageProtections.None; } + } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestExpiringMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestExpiringMessage.cs index b14d4f2..0aae6ae 100644 --- a/src/DotNetOAuth.Test/Mocks/TestExpiringMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestExpiringMessage.cs @@ -1,35 +1,35 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestExpiringMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Diagnostics;
- using System.Runtime.Serialization;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Messaging.Reflection;
-
- internal class TestExpiringMessage : TestSignedDirectedMessage, IExpiringProtocolMessage {
- [DebuggerBrowsable(DebuggerBrowsableState.Never)]
- private DateTime utcCreationDate;
-
- internal TestExpiringMessage() { }
-
- internal TestExpiringMessage(MessageTransport transport)
- : base(transport) {
- }
-
- #region IExpiringProtocolMessage Members
-
- [MessagePart("created_on", IsRequired = true)]
- DateTime IExpiringProtocolMessage.UtcCreationDate {
- get { return this.utcCreationDate; }
- set { this.utcCreationDate = value.ToUniversalTime(); }
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestExpiringMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Diagnostics; + using System.Runtime.Serialization; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Messaging.Reflection; + + internal class TestExpiringMessage : TestSignedDirectedMessage, IExpiringProtocolMessage { + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private DateTime utcCreationDate; + + internal TestExpiringMessage() { } + + internal TestExpiringMessage(MessageTransport transport) + : base(transport) { + } + + #region IExpiringProtocolMessage Members + + [MessagePart("created_on", IsRequired = true)] + DateTime IExpiringProtocolMessage.UtcCreationDate { + get { return this.utcCreationDate; } + set { this.utcCreationDate = value.ToUniversalTime(); } + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestMessage.cs index 0cb331c..301e70d 100644 --- a/src/DotNetOAuth.Test/Mocks/TestMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestMessage.cs @@ -1,63 +1,63 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Runtime.Serialization;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
-
- internal class TestMessage : IProtocolMessage {
- private MessageTransport transport;
- private Dictionary<string, string> extraData = new Dictionary<string, string>();
-
- internal TestMessage()
- : this(MessageTransport.Direct) {
- }
-
- internal TestMessage(MessageTransport transport) {
- this.transport = transport;
- }
-
- [MessagePart("age", IsRequired = true)]
- public int Age { get; set; }
- [MessagePart("Name")]
- public string Name { get; set; }
- [MessagePart]
- public string EmptyMember { get; set; }
- [MessagePart(null)] // null name tests that Location is still the name.
- public Uri Location { get; set; }
- [MessagePart(IsRequired = true)]
- public DateTime Timestamp { get; set; }
-
- #region IProtocolMessage Members
-
- Version IProtocolMessage.ProtocolVersion {
- get { return new Version(1, 0); }
- }
-
- MessageProtections IProtocolMessage.RequiredProtection {
- get { return MessageProtections.None; }
- }
-
- MessageTransport IProtocolMessage.Transport {
- get { return this.transport; }
- }
-
- IDictionary<string, string> IProtocolMessage.ExtraData {
- get { return this.extraData; }
- }
-
- void IProtocolMessage.EnsureValidMessage() {
- if (this.EmptyMember != null || this.Age < 0) {
- throw new ProtocolException();
- }
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Runtime.Serialization; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + + internal class TestMessage : IProtocolMessage { + private MessageTransport transport; + private Dictionary<string, string> extraData = new Dictionary<string, string>(); + + internal TestMessage() + : this(MessageTransport.Direct) { + } + + internal TestMessage(MessageTransport transport) { + this.transport = transport; + } + + [MessagePart("age", IsRequired = true)] + public int Age { get; set; } + [MessagePart("Name")] + public string Name { get; set; } + [MessagePart] + public string EmptyMember { get; set; } + [MessagePart(null)] // null name tests that Location is still the name. + public Uri Location { get; set; } + [MessagePart(IsRequired = true)] + public DateTime Timestamp { get; set; } + + #region IProtocolMessage Members + + Version IProtocolMessage.ProtocolVersion { + get { return new Version(1, 0); } + } + + MessageProtections IProtocolMessage.RequiredProtection { + get { return MessageProtections.None; } + } + + MessageTransport IProtocolMessage.Transport { + get { return this.transport; } + } + + IDictionary<string, string> IProtocolMessage.ExtraData { + get { return this.extraData; } + } + + void IProtocolMessage.EnsureValidMessage() { + if (this.EmptyMember != null || this.Age < 0) { + throw new ProtocolException(); + } + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestMessageTypeProvider.cs b/src/DotNetOpenAuth.Test/Mocks/TestMessageTypeProvider.cs index 85e2b05..c6bb0c7 100644 --- a/src/DotNetOAuth.Test/Mocks/TestMessageTypeProvider.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestMessageTypeProvider.cs @@ -1,56 +1,56 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestMessageTypeProvider.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- internal class TestMessageTypeProvider : IMessageTypeProvider {
- private bool signedMessages;
- private bool expiringMessages;
- private bool replayMessages;
-
- internal TestMessageTypeProvider()
- : this(false, false, false) {
- }
-
- internal TestMessageTypeProvider(bool signed, bool expiring, bool replay) {
- if ((!signed && expiring) || (!expiring && replay)) {
- throw new ArgumentException("Invalid combination of protection.");
- }
- this.signedMessages = signed;
- this.expiringMessages = expiring;
- this.replayMessages = replay;
- }
-
- #region IMessageTypeProvider Members
-
- public Type GetRequestMessageType(IDictionary<string, string> fields) {
- if (fields.ContainsKey("age")) {
- if (this.signedMessages) {
- if (this.expiringMessages) {
- if (this.replayMessages) {
- return typeof(TestReplayProtectedMessage);
- }
- return typeof(TestExpiringMessage);
- }
- return typeof(TestSignedDirectedMessage);
- }
- return typeof(TestMessage);
- }
- return null;
- }
-
- public Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields) {
- return this.GetRequestMessageType(fields);
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestMessageTypeProvider.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + + internal class TestMessageTypeProvider : IMessageTypeProvider { + private bool signedMessages; + private bool expiringMessages; + private bool replayMessages; + + internal TestMessageTypeProvider() + : this(false, false, false) { + } + + internal TestMessageTypeProvider(bool signed, bool expiring, bool replay) { + if ((!signed && expiring) || (!expiring && replay)) { + throw new ArgumentException("Invalid combination of protection."); + } + this.signedMessages = signed; + this.expiringMessages = expiring; + this.replayMessages = replay; + } + + #region IMessageTypeProvider Members + + public Type GetRequestMessageType(IDictionary<string, string> fields) { + if (fields.ContainsKey("age")) { + if (this.signedMessages) { + if (this.expiringMessages) { + if (this.replayMessages) { + return typeof(TestReplayProtectedMessage); + } + return typeof(TestExpiringMessage); + } + return typeof(TestSignedDirectedMessage); + } + return typeof(TestMessage); + } + return null; + } + + public Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields) { + return this.GetRequestMessageType(fields); + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestReplayProtectedMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestReplayProtectedMessage.cs index 6467ebc..396db44 100644 --- a/src/DotNetOAuth.Test/Mocks/TestReplayProtectedMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestReplayProtectedMessage.cs @@ -1,30 +1,30 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestReplayProtectedMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System.Runtime.Serialization;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Messaging.Reflection;
-
- internal class TestReplayProtectedMessage : TestExpiringMessage, IReplayProtectedProtocolMessage {
- internal TestReplayProtectedMessage() { }
-
- internal TestReplayProtectedMessage(MessageTransport transport)
- : base(transport) {
- }
-
- #region IReplayProtectedProtocolMessage Members
-
- [MessagePart("Nonce")]
- string IReplayProtectedProtocolMessage.Nonce {
- get;
- set;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestReplayProtectedMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System.Runtime.Serialization; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Messaging.Reflection; + + internal class TestReplayProtectedMessage : TestExpiringMessage, IReplayProtectedProtocolMessage { + internal TestReplayProtectedMessage() { } + + internal TestReplayProtectedMessage(MessageTransport transport) + : base(transport) { + } + + #region IReplayProtectedProtocolMessage Members + + [MessagePart("Nonce")] + string IReplayProtectedProtocolMessage.Nonce { + get; + set; + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestSignedDirectedMessage.cs b/src/DotNetOpenAuth.Test/Mocks/TestSignedDirectedMessage.cs index 0cb880d..d665db8 100644 --- a/src/DotNetOAuth.Test/Mocks/TestSignedDirectedMessage.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestSignedDirectedMessage.cs @@ -1,33 +1,33 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestSignedDirectedMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Messaging.Reflection;
-
- internal class TestSignedDirectedMessage : TestDirectedMessage, ITamperResistantProtocolMessage {
- internal TestSignedDirectedMessage() { }
-
- internal TestSignedDirectedMessage(MessageTransport transport)
- : base(transport) {
- }
-
- #region ISignedProtocolMessage Members
-
- [MessagePart]
- public string Signature {
- get;
- set;
- }
-
- #endregion
-
- protected override MessageProtections RequiredProtection {
- get { return MessageProtections.TamperProtection; }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestSignedDirectedMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Messaging.Reflection; + + internal class TestSignedDirectedMessage : TestDirectedMessage, ITamperResistantProtocolMessage { + internal TestSignedDirectedMessage() { } + + internal TestSignedDirectedMessage(MessageTransport transport) + : base(transport) { + } + + #region ISignedProtocolMessage Members + + [MessagePart] + public string Signature { + get; + set; + } + + #endregion + + protected override MessageProtections RequiredProtection { + get { return MessageProtections.TamperProtection; } + } + } +} diff --git a/src/DotNetOAuth.Test/Mocks/TestWebRequestHandler.cs b/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs index f0e1b62..d7092b4 100644 --- a/src/DotNetOAuth.Test/Mocks/TestWebRequestHandler.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs @@ -1,46 +1,46 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestWebRequestHandler.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Mocks {
- using System;
- using System.IO;
- using System.Net;
- using System.Text;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.ChannelElements;
-
- internal class TestWebRequestHandler : IWebRequestHandler {
- private StringBuilder postEntity;
-
- internal Func<HttpWebRequest, Response> Callback { get; set; }
-
- internal Stream RequestEntityStream {
- get {
- if (this.postEntity == null) {
- return null;
- }
- return new MemoryStream(Encoding.UTF8.GetBytes(this.postEntity.ToString()));
- }
- }
-
- #region IWebRequestHandler Members
-
- public TextWriter GetRequestStream(HttpWebRequest request) {
- this.postEntity = new StringBuilder();
- return new StringWriter(this.postEntity);
- }
-
- public Response GetResponse(HttpWebRequest request) {
- if (this.Callback == null) {
- throw new InvalidOperationException("Set the Callback property first.");
- }
-
- return this.Callback(request);
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestWebRequestHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Mocks { + using System; + using System.IO; + using System.Net; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth.ChannelElements; + + internal class TestWebRequestHandler : IWebRequestHandler { + private StringBuilder postEntity; + + internal Func<HttpWebRequest, Response> Callback { get; set; } + + internal Stream RequestEntityStream { + get { + if (this.postEntity == null) { + return null; + } + return new MemoryStream(Encoding.UTF8.GetBytes(this.postEntity.ToString())); + } + } + + #region IWebRequestHandler Members + + public TextWriter GetRequestStream(HttpWebRequest request) { + this.postEntity = new StringBuilder(); + return new StringWriter(this.postEntity); + } + + public Response GetResponse(HttpWebRequest request) { + if (this.Callback == null) { + throw new InvalidOperationException("Set the Callback property first."); + } + + return this.Callback(request); + } + + #endregion + } +} diff --git a/src/DotNetOAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs index d98e6be..ac2c0b1 100644 --- a/src/DotNetOAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs @@ -1,22 +1,22 @@ -//-----------------------------------------------------------------------
-// <copyright file="HmacSha1SigningBindingElementTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.OAuth.ChannelElements {
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class HmacSha1SigningBindingElementTests : MessagingTestBase {
- [TestMethod]
- public void SignatureTest() {
- UnauthorizedTokenRequest message = SigningBindingElementBaseTests.CreateTestRequestTokenMessage();
-
- HmacSha1SigningBindingElement_Accessor hmac = new HmacSha1SigningBindingElement_Accessor();
- Assert.AreEqual("kR0LhH8UqylaLfR/esXVVlP4sQI=", hmac.GetSignature(message));
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="HmacSha1SigningBindingElementTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.ChannelElements { + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class HmacSha1SigningBindingElementTests : MessagingTestBase { + [TestMethod] + public void SignatureTest() { + UnauthorizedTokenRequest message = SigningBindingElementBaseTests.CreateTestRequestTokenMessage(); + + HmacSha1SigningBindingElement_Accessor hmac = new HmacSha1SigningBindingElement_Accessor(); + Assert.AreEqual("kR0LhH8UqylaLfR/esXVVlP4sQI=", hmac.GetSignature(message)); + } + } +} diff --git a/src/DotNetOAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs index 6a58bfa..c5d3b14 100644 --- a/src/DotNetOAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs @@ -1,293 +1,293 @@ -//-----------------------------------------------------------------------
-// <copyright file="OAuthChannelTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Web;
- using System.Xml;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.Test.Mocks;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class OAuthChannelTests : TestBase {
- private OAuthChannel channel;
- private TestWebRequestHandler webRequestHandler;
- private SigningBindingElementBase signingElement;
- private INonceStore nonceStore;
-
- [TestInitialize]
- public override void SetUp() {
- base.SetUp();
-
- this.webRequestHandler = new TestWebRequestHandler();
- this.signingElement = new RsaSha1SigningBindingElement();
- this.nonceStore = new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge);
- this.channel = new OAuthChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), new TestMessageTypeProvider(), this.webRequestHandler);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullHandler() {
- new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, new InMemoryTokenManager(), new TestMessageTypeProvider(), null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void CtorNullSigner() {
- new OAuthChannel(null, this.nonceStore, new InMemoryTokenManager(), new TestMessageTypeProvider(), this.webRequestHandler);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullStore() {
- new OAuthChannel(new RsaSha1SigningBindingElement(), null, new InMemoryTokenManager(), new TestMessageTypeProvider(), this.webRequestHandler);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void CtorNullTokenManager() {
- new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, null, new TestMessageTypeProvider(), this.webRequestHandler);
- }
-
- [TestMethod]
- public void CtorSimpleConsumer() {
- new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, new InMemoryTokenManager(), true);
- }
-
- [TestMethod]
- public void CtorSimpleServiceProvider() {
- new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, new InMemoryTokenManager(), false);
- }
-
- [TestMethod]
- public void ReadFromRequestAuthorization() {
- this.ParameterizedReceiveTest(HttpDeliveryMethods.AuthorizationHeaderRequest);
- }
-
- [TestMethod]
- public void ReadFromRequestForm() {
- this.ParameterizedReceiveTest(HttpDeliveryMethods.PostRequest);
- }
-
- [TestMethod]
- public void ReadFromRequestQueryString() {
- this.ParameterizedReceiveTest(HttpDeliveryMethods.GetRequest);
- }
-
- [TestMethod]
- public void SendDirectMessageResponse() {
- IProtocolMessage message = new TestMessage {
- Age = 15,
- Name = "Andrew",
- Location = new Uri("http://hostb/pathB"),
- };
-
- Response response = this.channel.Send(message);
- Assert.AreSame(message, response.OriginalMessage);
- Assert.AreEqual(HttpStatusCode.OK, response.Status);
- Assert.AreEqual(0, response.Headers.Count);
-
- NameValueCollection body = HttpUtility.ParseQueryString(response.Body);
- Assert.AreEqual("15", body["age"]);
- Assert.AreEqual("Andrew", body["Name"]);
- Assert.AreEqual("http://hostb/pathB", body["Location"]);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void ReadFromResponseNull() {
- Channel_Accessor accessor = Channel_Accessor.AttachShadow(this.channel);
- accessor.ReadFromResponse(null);
- }
-
- [TestMethod]
- public void ReadFromResponse() {
- var fields = new Dictionary<string, string> {
- { "age", "15" },
- { "Name", "Andrew" },
- { "Location", "http://hostb/pathB" },
- { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
- };
-
- MemoryStream ms = new MemoryStream();
- StreamWriter writer = new StreamWriter(ms);
- writer.Write(MessagingUtilities.CreateQueryString(fields));
- writer.Flush();
- ms.Seek(0, SeekOrigin.Begin);
- Channel_Accessor channelAccessor = Channel_Accessor.AttachShadow(this.channel);
- IProtocolMessage message = channelAccessor.ReadFromResponse(ms);
- Assert.IsNotNull(message);
- Assert.IsInstanceOfType(message, typeof(TestMessage));
- TestMessage testMessage = (TestMessage)message;
- Assert.AreEqual(15, testMessage.Age);
- Assert.AreEqual("Andrew", testMessage.Name);
- Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
- Assert.IsNull(testMessage.EmptyMember);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentNullException))]
- public void RequestNull() {
- this.channel.Request(null);
- }
-
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void RequestNullRecipient() {
- IDirectedProtocolMessage message = new TestDirectedMessage(MessageTransport.Direct);
- this.channel.Request(message);
- }
-
- [TestMethod, ExpectedException(typeof(NotSupportedException))]
- public void RequestBadPreferredScheme() {
- TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Direct);
- message.Recipient = new Uri("http://localtest");
- message.HttpMethods = HttpDeliveryMethods.None;
- this.channel.Request(message);
- }
-
- [TestMethod]
- public void RequestUsingAuthorizationHeader() {
- this.ParameterizedRequestTest(HttpDeliveryMethods.AuthorizationHeaderRequest);
- }
-
- [TestMethod]
- public void RequestUsingGet() {
- this.ParameterizedRequestTest(HttpDeliveryMethods.GetRequest);
- }
-
- [TestMethod]
- public void RequestUsingPost() {
- this.ParameterizedRequestTest(HttpDeliveryMethods.PostRequest);
- }
-
- private static string CreateAuthorizationHeader(IDictionary<string, string> fields) {
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- StringBuilder authorization = new StringBuilder();
- authorization.Append("OAuth ");
- foreach (var pair in fields) {
- string key = Uri.EscapeDataString(pair.Key);
- string value = Uri.EscapeDataString(pair.Value);
- authorization.Append(key);
- authorization.Append("=\"");
- authorization.Append(value);
- authorization.Append("\",");
- }
- authorization.Length--; // remove trailing comma
-
- return authorization.ToString();
- }
-
- private static HttpRequestInfo CreateHttpRequestInfo(HttpDeliveryMethods scheme, IDictionary<string, string> fields) {
- string query = MessagingUtilities.CreateQueryString(fields);
- UriBuilder requestUri = new UriBuilder("http://localhost/path");
- WebHeaderCollection headers = new WebHeaderCollection();
- MemoryStream ms = new MemoryStream();
- string method;
- switch (scheme) {
- case HttpDeliveryMethods.PostRequest:
- method = "POST";
- headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
- StreamWriter sw = new StreamWriter(ms);
- sw.Write(query);
- sw.Flush();
- ms.Position = 0;
- break;
- case HttpDeliveryMethods.GetRequest:
- method = "GET";
- requestUri.Query = query;
- break;
- case HttpDeliveryMethods.AuthorizationHeaderRequest:
- method = "GET";
- headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(fields));
- break;
- default:
- throw new ArgumentOutOfRangeException("scheme", scheme, "Unexpected value");
- }
- HttpRequestInfo request = new HttpRequestInfo {
- HttpMethod = method,
- Url = requestUri.Uri,
- Headers = headers,
- InputStream = ms,
- };
-
- return request;
- }
-
- private static HttpRequestInfo ConvertToRequestInfo(HttpWebRequest request, Stream postEntity) {
- HttpRequestInfo info = new HttpRequestInfo {
- HttpMethod = request.Method,
- Url = request.RequestUri,
- Headers = request.Headers,
- InputStream = postEntity,
- };
- return info;
- }
-
- private void ParameterizedRequestTest(HttpDeliveryMethods scheme) {
- TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) {
- Age = 15,
- Name = "Andrew",
- Location = new Uri("http://hostb/pathB"),
- Recipient = new Uri("http://localtest"),
- Timestamp = DateTime.UtcNow,
- HttpMethods = scheme,
- };
-
- Response rawResponse = null;
- this.webRequestHandler.Callback = (req) => {
- Assert.IsNotNull(req);
- HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream);
- Assert.AreEqual(scheme == HttpDeliveryMethods.PostRequest ? "POST" : "GET", reqInfo.HttpMethod);
- var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage;
- Assert.IsNotNull(incomingMessage);
- Assert.AreEqual(request.Age, incomingMessage.Age);
- Assert.AreEqual(request.Name, incomingMessage.Name);
- Assert.AreEqual(request.Location, incomingMessage.Location);
- Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp);
-
- var responseFields = new Dictionary<string, string> {
- { "age", request.Age.ToString() },
- { "Name", request.Name },
- { "Location", request.Location.AbsoluteUri },
- { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) },
- };
- rawResponse = new Response {
- Body = MessagingUtilities.CreateQueryString(responseFields),
- };
- return rawResponse;
- };
-
- IProtocolMessage response = this.channel.Request(request);
- Assert.IsNotNull(response);
- Assert.IsInstanceOfType(response, typeof(TestMessage));
- TestMessage responseMessage = (TestMessage)response;
- Assert.AreEqual(request.Age, responseMessage.Age);
- Assert.AreEqual(request.Name, responseMessage.Name);
- Assert.AreEqual(request.Location, responseMessage.Location);
- }
-
- private void ParameterizedReceiveTest(HttpDeliveryMethods scheme) {
- var fields = new Dictionary<string, string> {
- { "age", "15" },
- { "Name", "Andrew" },
- { "Location", "http://hostb/pathB" },
- { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) },
- };
- IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields));
- Assert.IsNotNull(requestMessage);
- Assert.IsInstanceOfType(requestMessage, typeof(TestMessage));
- TestMessage testMessage = (TestMessage)requestMessage;
- Assert.AreEqual(15, testMessage.Age);
- Assert.AreEqual("Andrew", testMessage.Name);
- Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="OAuthChannelTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.ChannelElements { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.IO; + using System.Net; + using System.Text; + using System.Web; + using System.Xml; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.Test.Mocks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class OAuthChannelTests : TestBase { + private OAuthChannel channel; + private TestWebRequestHandler webRequestHandler; + private SigningBindingElementBase signingElement; + private INonceStore nonceStore; + + [TestInitialize] + public override void SetUp() { + base.SetUp(); + + this.webRequestHandler = new TestWebRequestHandler(); + this.signingElement = new RsaSha1SigningBindingElement(); + this.nonceStore = new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge); + this.channel = new OAuthChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), new TestMessageTypeProvider(), this.webRequestHandler); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullHandler() { + new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, new InMemoryTokenManager(), new TestMessageTypeProvider(), null); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void CtorNullSigner() { + new OAuthChannel(null, this.nonceStore, new InMemoryTokenManager(), new TestMessageTypeProvider(), this.webRequestHandler); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullStore() { + new OAuthChannel(new RsaSha1SigningBindingElement(), null, new InMemoryTokenManager(), new TestMessageTypeProvider(), this.webRequestHandler); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullTokenManager() { + new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, null, new TestMessageTypeProvider(), this.webRequestHandler); + } + + [TestMethod] + public void CtorSimpleConsumer() { + new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, new InMemoryTokenManager(), true); + } + + [TestMethod] + public void CtorSimpleServiceProvider() { + new OAuthChannel(new RsaSha1SigningBindingElement(), this.nonceStore, new InMemoryTokenManager(), false); + } + + [TestMethod] + public void ReadFromRequestAuthorization() { + this.ParameterizedReceiveTest(HttpDeliveryMethods.AuthorizationHeaderRequest); + } + + [TestMethod] + public void ReadFromRequestForm() { + this.ParameterizedReceiveTest(HttpDeliveryMethods.PostRequest); + } + + [TestMethod] + public void ReadFromRequestQueryString() { + this.ParameterizedReceiveTest(HttpDeliveryMethods.GetRequest); + } + + [TestMethod] + public void SendDirectMessageResponse() { + IProtocolMessage message = new TestMessage { + Age = 15, + Name = "Andrew", + Location = new Uri("http://hostb/pathB"), + }; + + Response response = this.channel.Send(message); + Assert.AreSame(message, response.OriginalMessage); + Assert.AreEqual(HttpStatusCode.OK, response.Status); + Assert.AreEqual(0, response.Headers.Count); + + NameValueCollection body = HttpUtility.ParseQueryString(response.Body); + Assert.AreEqual("15", body["age"]); + Assert.AreEqual("Andrew", body["Name"]); + Assert.AreEqual("http://hostb/pathB", body["Location"]); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void ReadFromResponseNull() { + Channel_Accessor accessor = Channel_Accessor.AttachShadow(this.channel); + accessor.ReadFromResponse(null); + } + + [TestMethod] + public void ReadFromResponse() { + var fields = new Dictionary<string, string> { + { "age", "15" }, + { "Name", "Andrew" }, + { "Location", "http://hostb/pathB" }, + { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) }, + }; + + MemoryStream ms = new MemoryStream(); + StreamWriter writer = new StreamWriter(ms); + writer.Write(MessagingUtilities.CreateQueryString(fields)); + writer.Flush(); + ms.Seek(0, SeekOrigin.Begin); + Channel_Accessor channelAccessor = Channel_Accessor.AttachShadow(this.channel); + IProtocolMessage message = channelAccessor.ReadFromResponse(ms); + Assert.IsNotNull(message); + Assert.IsInstanceOfType(message, typeof(TestMessage)); + TestMessage testMessage = (TestMessage)message; + Assert.AreEqual(15, testMessage.Age); + Assert.AreEqual("Andrew", testMessage.Name); + Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri); + Assert.IsNull(testMessage.EmptyMember); + } + + [TestMethod, ExpectedException(typeof(ArgumentNullException))] + public void RequestNull() { + this.channel.Request(null); + } + + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void RequestNullRecipient() { + IDirectedProtocolMessage message = new TestDirectedMessage(MessageTransport.Direct); + this.channel.Request(message); + } + + [TestMethod, ExpectedException(typeof(NotSupportedException))] + public void RequestBadPreferredScheme() { + TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Direct); + message.Recipient = new Uri("http://localtest"); + message.HttpMethods = HttpDeliveryMethods.None; + this.channel.Request(message); + } + + [TestMethod] + public void RequestUsingAuthorizationHeader() { + this.ParameterizedRequestTest(HttpDeliveryMethods.AuthorizationHeaderRequest); + } + + [TestMethod] + public void RequestUsingGet() { + this.ParameterizedRequestTest(HttpDeliveryMethods.GetRequest); + } + + [TestMethod] + public void RequestUsingPost() { + this.ParameterizedRequestTest(HttpDeliveryMethods.PostRequest); + } + + private static string CreateAuthorizationHeader(IDictionary<string, string> fields) { + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + StringBuilder authorization = new StringBuilder(); + authorization.Append("OAuth "); + foreach (var pair in fields) { + string key = Uri.EscapeDataString(pair.Key); + string value = Uri.EscapeDataString(pair.Value); + authorization.Append(key); + authorization.Append("=\""); + authorization.Append(value); + authorization.Append("\","); + } + authorization.Length--; // remove trailing comma + + return authorization.ToString(); + } + + private static HttpRequestInfo CreateHttpRequestInfo(HttpDeliveryMethods scheme, IDictionary<string, string> fields) { + string query = MessagingUtilities.CreateQueryString(fields); + UriBuilder requestUri = new UriBuilder("http://localhost/path"); + WebHeaderCollection headers = new WebHeaderCollection(); + MemoryStream ms = new MemoryStream(); + string method; + switch (scheme) { + case HttpDeliveryMethods.PostRequest: + method = "POST"; + headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); + StreamWriter sw = new StreamWriter(ms); + sw.Write(query); + sw.Flush(); + ms.Position = 0; + break; + case HttpDeliveryMethods.GetRequest: + method = "GET"; + requestUri.Query = query; + break; + case HttpDeliveryMethods.AuthorizationHeaderRequest: + method = "GET"; + headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(fields)); + break; + default: + throw new ArgumentOutOfRangeException("scheme", scheme, "Unexpected value"); + } + HttpRequestInfo request = new HttpRequestInfo { + HttpMethod = method, + Url = requestUri.Uri, + Headers = headers, + InputStream = ms, + }; + + return request; + } + + private static HttpRequestInfo ConvertToRequestInfo(HttpWebRequest request, Stream postEntity) { + HttpRequestInfo info = new HttpRequestInfo { + HttpMethod = request.Method, + Url = request.RequestUri, + Headers = request.Headers, + InputStream = postEntity, + }; + return info; + } + + private void ParameterizedRequestTest(HttpDeliveryMethods scheme) { + TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) { + Age = 15, + Name = "Andrew", + Location = new Uri("http://hostb/pathB"), + Recipient = new Uri("http://localtest"), + Timestamp = DateTime.UtcNow, + HttpMethods = scheme, + }; + + Response rawResponse = null; + this.webRequestHandler.Callback = (req) => { + Assert.IsNotNull(req); + HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream); + Assert.AreEqual(scheme == HttpDeliveryMethods.PostRequest ? "POST" : "GET", reqInfo.HttpMethod); + var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage; + Assert.IsNotNull(incomingMessage); + Assert.AreEqual(request.Age, incomingMessage.Age); + Assert.AreEqual(request.Name, incomingMessage.Name); + Assert.AreEqual(request.Location, incomingMessage.Location); + Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp); + + var responseFields = new Dictionary<string, string> { + { "age", request.Age.ToString() }, + { "Name", request.Name }, + { "Location", request.Location.AbsoluteUri }, + { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, + }; + rawResponse = new Response { + Body = MessagingUtilities.CreateQueryString(responseFields), + }; + return rawResponse; + }; + + IProtocolMessage response = this.channel.Request(request); + Assert.IsNotNull(response); + Assert.IsInstanceOfType(response, typeof(TestMessage)); + TestMessage responseMessage = (TestMessage)response; + Assert.AreEqual(request.Age, responseMessage.Age); + Assert.AreEqual(request.Name, responseMessage.Name); + Assert.AreEqual(request.Location, responseMessage.Location); + } + + private void ParameterizedReceiveTest(HttpDeliveryMethods scheme) { + var fields = new Dictionary<string, string> { + { "age", "15" }, + { "Name", "Andrew" }, + { "Location", "http://hostb/pathB" }, + { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) }, + }; + IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields)); + Assert.IsNotNull(requestMessage); + Assert.IsInstanceOfType(requestMessage, typeof(TestMessage)); + TestMessage testMessage = (TestMessage)requestMessage; + Assert.AreEqual(15, testMessage.Age); + Assert.AreEqual("Andrew", testMessage.Name); + Assert.AreEqual("http://hostb/pathB", testMessage.Location.AbsoluteUri); + } + } +} diff --git a/src/DotNetOAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs index 151f00d..22b6243 100644 --- a/src/DotNetOAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs @@ -1,78 +1,78 @@ -//-----------------------------------------------------------------------
-// <copyright file="PlaintextSigningBindingElementTest.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.OAuth.ChannelElements
-{
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class PlaintextSigningBindingElementTest {
- [TestMethod]
- public void HttpsSignatureGeneration() {
- SigningBindingElementBase target = new PlaintextSigningBindingElement();
- MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest);
- ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint);
- message.ConsumerSecret = "cs";
- message.TokenSecret = "ts";
- Assert.IsTrue(target.PrepareMessageForSending(message));
- Assert.AreEqual("PLAINTEXT", message.SignatureMethod);
- Assert.AreEqual("cs&ts", message.Signature);
- }
-
- [TestMethod]
- public void HttpsSignatureVerification() {
- MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest);
- ITamperProtectionChannelBindingElement target = new PlaintextSigningBindingElement();
- ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint);
- message.ConsumerSecret = "cs";
- message.TokenSecret = "ts";
- message.SignatureMethod = "PLAINTEXT";
- message.Signature = "cs&ts";
- Assert.IsTrue(target.PrepareMessageForReceiving(message));
- }
-
- [TestMethod]
- public void HttpsSignatureVerificationNotApplicable() {
- SigningBindingElementBase target = new PlaintextSigningBindingElement();
- MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest);
- ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint);
- message.ConsumerSecret = "cs";
- message.TokenSecret = "ts";
- message.SignatureMethod = "ANOTHERALGORITHM";
- message.Signature = "somethingelse";
- Assert.IsFalse(target.PrepareMessageForReceiving(message), "PLAINTEXT binding element should opt-out where it doesn't understand.");
- }
-
- [TestMethod]
- public void HttpSignatureGeneration() {
- SigningBindingElementBase target = new PlaintextSigningBindingElement();
- MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest);
- ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint);
- message.ConsumerSecret = "cs";
- message.TokenSecret = "ts";
-
- // Since this is (non-encrypted) HTTP, so the plain text signer should not be used
- Assert.IsFalse(target.PrepareMessageForSending(message));
- Assert.IsNull(message.SignatureMethod);
- Assert.IsNull(message.Signature);
- }
-
- [TestMethod]
- public void HttpSignatureVerification() {
- SigningBindingElementBase target = new PlaintextSigningBindingElement();
- MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest);
- ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint);
- message.ConsumerSecret = "cs";
- message.TokenSecret = "ts";
- message.SignatureMethod = "PLAINTEXT";
- message.Signature = "cs%26ts";
- Assert.IsFalse(target.PrepareMessageForReceiving(message), "PLAINTEXT signature binding element should refuse to participate in non-encrypted messages.");
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="PlaintextSigningBindingElementTest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.ChannelElements +{ + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class PlaintextSigningBindingElementTest { + [TestMethod] + public void HttpsSignatureGeneration() { + SigningBindingElementBase target = new PlaintextSigningBindingElement(); + MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); + ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint); + message.ConsumerSecret = "cs"; + message.TokenSecret = "ts"; + Assert.IsTrue(target.PrepareMessageForSending(message)); + Assert.AreEqual("PLAINTEXT", message.SignatureMethod); + Assert.AreEqual("cs&ts", message.Signature); + } + + [TestMethod] + public void HttpsSignatureVerification() { + MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); + ITamperProtectionChannelBindingElement target = new PlaintextSigningBindingElement(); + ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint); + message.ConsumerSecret = "cs"; + message.TokenSecret = "ts"; + message.SignatureMethod = "PLAINTEXT"; + message.Signature = "cs&ts"; + Assert.IsTrue(target.PrepareMessageForReceiving(message)); + } + + [TestMethod] + public void HttpsSignatureVerificationNotApplicable() { + SigningBindingElementBase target = new PlaintextSigningBindingElement(); + MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); + ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint); + message.ConsumerSecret = "cs"; + message.TokenSecret = "ts"; + message.SignatureMethod = "ANOTHERALGORITHM"; + message.Signature = "somethingelse"; + Assert.IsFalse(target.PrepareMessageForReceiving(message), "PLAINTEXT binding element should opt-out where it doesn't understand."); + } + + [TestMethod] + public void HttpSignatureGeneration() { + SigningBindingElementBase target = new PlaintextSigningBindingElement(); + MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); + ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint); + message.ConsumerSecret = "cs"; + message.TokenSecret = "ts"; + + // Since this is (non-encrypted) HTTP, so the plain text signer should not be used + Assert.IsFalse(target.PrepareMessageForSending(message)); + Assert.IsNull(message.SignatureMethod); + Assert.IsNull(message.Signature); + } + + [TestMethod] + public void HttpSignatureVerification() { + SigningBindingElementBase target = new PlaintextSigningBindingElement(); + MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); + ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint); + message.ConsumerSecret = "cs"; + message.TokenSecret = "ts"; + message.SignatureMethod = "PLAINTEXT"; + message.Signature = "cs%26ts"; + Assert.IsFalse(target.PrepareMessageForReceiving(message), "PLAINTEXT signature binding element should refuse to participate in non-encrypted messages."); + } + } +} diff --git a/src/DotNetOAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs index e764322..8f09ef6 100644 --- a/src/DotNetOAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs @@ -1,40 +1,40 @@ -//-----------------------------------------------------------------------
-// <copyright file="SigningBindingElementBaseTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.OAuth.ChannelElements {
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class SigningBindingElementBaseTests : MessagingTestBase {
- [TestMethod]
- public void BaseSignatureStringTest() {
- UnauthorizedTokenRequest message = CreateTestRequestTokenMessage();
-
- Assert.AreEqual(
- "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F",
- SigningBindingElementBase_Accessor.ConstructSignatureBaseString(message));
- }
-
- internal static UnauthorizedTokenRequest CreateTestRequestTokenMessage() {
- MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
- UnauthorizedTokenRequest message = new UnauthorizedTokenRequest(endpoint);
- message.ConsumerKey = "nerdbank.org";
- ((ITamperResistantOAuthMessage)message).ConsumerSecret = "nerdbanksecret";
- var signedMessage = (ITamperResistantOAuthMessage)message;
- signedMessage.HttpMethod = "GET";
- signedMessage.SignatureMethod = "HMAC-SHA1";
- MessageDictionary dictionary = new MessageDictionary(message);
- dictionary["oauth_timestamp"] = "1222665749";
- dictionary["oauth_nonce"] = "fe4045a3f0efdd1e019fa8f8ae3f5c38";
- dictionary["scope"] = "http://www.google.com/m8/feeds/";
- return message;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="SigningBindingElementBaseTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.ChannelElements { + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class SigningBindingElementBaseTests : MessagingTestBase { + [TestMethod] + public void BaseSignatureStringTest() { + UnauthorizedTokenRequest message = CreateTestRequestTokenMessage(); + + Assert.AreEqual( + "GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_consumer_key%3Dnerdbank.org%26oauth_nonce%3Dfe4045a3f0efdd1e019fa8f8ae3f5c38%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1222665749%26oauth_version%3D1.0%26scope%3Dhttp%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds%252F", + SigningBindingElementBase_Accessor.ConstructSignatureBaseString(message)); + } + + internal static UnauthorizedTokenRequest CreateTestRequestTokenMessage() { + MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); + UnauthorizedTokenRequest message = new UnauthorizedTokenRequest(endpoint); + message.ConsumerKey = "nerdbank.org"; + ((ITamperResistantOAuthMessage)message).ConsumerSecret = "nerdbanksecret"; + var signedMessage = (ITamperResistantOAuthMessage)message; + signedMessage.HttpMethod = "GET"; + signedMessage.SignatureMethod = "HMAC-SHA1"; + MessageDictionary dictionary = new MessageDictionary(message); + dictionary["oauth_timestamp"] = "1222665749"; + dictionary["oauth_nonce"] = "fe4045a3f0efdd1e019fa8f8ae3f5c38"; + dictionary["scope"] = "http://www.google.com/m8/feeds/"; + return message; + } + } +} diff --git a/src/DotNetOAuth.Test/OAuth/ConsumerDescription.cs b/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs index 7043a2f..625f416 100644 --- a/src/DotNetOAuth.Test/OAuth/ConsumerDescription.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs @@ -1,38 +1,38 @@ -//-----------------------------------------------------------------------
-// <copyright file="ConsumerDescription.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.OAuth {
- /// <summary>
- /// Information necessary to initialize a <see cref="Consumer"/>,
- /// and to tell a <see cref="ServiceProvider"/> about it.
- /// </summary>
- /// <remarks>
- /// Immutable.
- /// </remarks>
- internal class ConsumerDescription {
- /// <summary>
- /// Initializes a new instance of the <see cref="ConsumerDescription"/> class.
- /// </summary>
- /// <param name="key">The consumer key.</param>
- /// <param name="secret">The consumer secret.</param>
- internal ConsumerDescription(string key, string secret) {
- this.ConsumerKey = key;
- this.ConsumerSecret = secret;
- }
-
- /// <summary>
- /// Gets the consumer key.
- /// </summary>
- /// <value>The consumer key.</value>
- internal string ConsumerKey { get; private set; }
-
- /// <summary>
- /// Gets the consumer secret.
- /// </summary>
- /// <value>The consumer secret.</value>
- internal string ConsumerSecret { get; private set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ConsumerDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + /// <summary> + /// Information necessary to initialize a <see cref="Consumer"/>, + /// and to tell a <see cref="ServiceProvider"/> about it. + /// </summary> + /// <remarks> + /// Immutable. + /// </remarks> + internal class ConsumerDescription { + /// <summary> + /// Initializes a new instance of the <see cref="ConsumerDescription"/> class. + /// </summary> + /// <param name="key">The consumer key.</param> + /// <param name="secret">The consumer secret.</param> + internal ConsumerDescription(string key, string secret) { + this.ConsumerKey = key; + this.ConsumerSecret = secret; + } + + /// <summary> + /// Gets the consumer key. + /// </summary> + /// <value>The consumer key.</value> + internal string ConsumerKey { get; private set; } + + /// <summary> + /// Gets the consumer secret. + /// </summary> + /// <value>The consumer secret.</value> + internal string ConsumerSecret { get; private set; } + } +} diff --git a/src/DotNetOAuth.Test/OAuth/ProtocolTests.cs b/src/DotNetOpenAuth.Test/OAuth/ProtocolTests.cs index d72fcba..6a2551a 100644 --- a/src/DotNetOAuth.Test/OAuth/ProtocolTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ProtocolTests.cs @@ -1,34 +1,34 @@ -//-----------------------------------------------------------------------
-// <copyright file="ProtocolTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.OAuth {
- using DotNetOAuth.OAuth;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class ProtocolTests {
- [TestMethod]
- public void Default() {
- Assert.AreSame(Protocol.V10, Protocol.Default);
- }
-
- [TestMethod]
- public void DataContractNamespace() {
- Assert.AreEqual("http://oauth.net/core/1.0/", Protocol.V10.DataContractNamespace);
- Assert.AreEqual("http://oauth.net/core/1.0/", Protocol.DataContractNamespaceV10);
- }
-
- [TestMethod]
- public void AuthorizationHeaderScheme() {
- Assert.AreEqual("OAuth", Protocol.V10.AuthorizationHeaderScheme);
- }
-
- [TestMethod]
- public void ParameterPrefix() {
- Assert.AreEqual("oauth_", Protocol.V10.ParameterPrefix);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ProtocolTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using DotNetOpenAuth.OAuth; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class ProtocolTests { + [TestMethod] + public void Default() { + Assert.AreSame(Protocol.V10, Protocol.Default); + } + + [TestMethod] + public void DataContractNamespace() { + Assert.AreEqual("http://oauth.net/core/1.0/", Protocol.V10.DataContractNamespace); + Assert.AreEqual("http://oauth.net/core/1.0/", Protocol.DataContractNamespaceV10); + } + + [TestMethod] + public void AuthorizationHeaderScheme() { + Assert.AreEqual("OAuth", Protocol.V10.AuthorizationHeaderScheme); + } + + [TestMethod] + public void ParameterPrefix() { + Assert.AreEqual("oauth_", Protocol.V10.ParameterPrefix); + } + } +} diff --git a/src/DotNetOAuth.Test/OAuth/ServiceProviderDescriptionTests.cs b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs index e3cba68..760a9e9 100644 --- a/src/DotNetOAuth.Test/OAuth/ServiceProviderDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs @@ -1,76 +1,76 @@ -//-----------------------------------------------------------------------
-// <copyright file="ServiceProviderDescriptionTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.OAuth {
- using System;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- /// <summary>
- /// Tests for the <see cref="ServiceProviderEndpoints"/> class.
- /// </summary>
- [TestClass]
- public class ServiceProviderDescriptionTests : TestBase {
- /// <summary>
- /// A test for UserAuthorizationUri
- /// </summary>
- [TestMethod]
- public void UserAuthorizationUriTest() {
- ServiceProviderDescription target = new ServiceProviderDescription();
- MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest);
- MessageReceivingEndpoint actual;
- target.UserAuthorizationEndpoint = expected;
- actual = target.UserAuthorizationEndpoint;
- Assert.AreEqual(expected, actual);
-
- target.UserAuthorizationEndpoint = null;
- Assert.IsNull(target.UserAuthorizationEndpoint);
- }
-
- /// <summary>
- /// A test for RequestTokenUri
- /// </summary>
- [TestMethod]
- public void RequestTokenUriTest() {
- var target = new ServiceProviderDescription();
- MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/requesttoken", HttpDeliveryMethods.GetRequest);
- MessageReceivingEndpoint actual;
- target.RequestTokenEndpoint = expected;
- actual = target.RequestTokenEndpoint;
- Assert.AreEqual(expected, actual);
-
- target.RequestTokenEndpoint = null;
- Assert.IsNull(target.RequestTokenEndpoint);
- }
-
- /// <summary>
- /// Verifies that oauth parameters are not allowed in <see cref="ServiceProvider.RequestTokenUri"/>,
- /// per section OAuth 1.0 section 4.1.
- /// </summary>
- [TestMethod, ExpectedException(typeof(ArgumentException))]
- public void RequestTokenUriWithOAuthParametersTest() {
- var target = new ServiceProviderDescription();
- target.RequestTokenEndpoint = new MessageReceivingEndpoint("http://localhost/requesttoken?oauth_token=something", HttpDeliveryMethods.GetRequest);
- }
-
- /// <summary>
- /// A test for AccessTokenUri
- /// </summary>
- [TestMethod]
- public void AccessTokenUriTest() {
- var target = new ServiceProviderDescription();
- MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/accesstoken", HttpDeliveryMethods.GetRequest);
- MessageReceivingEndpoint actual;
- target.AccessTokenEndpoint = expected;
- actual = target.AccessTokenEndpoint;
- Assert.AreEqual(expected, actual);
-
- target.AccessTokenEndpoint = null;
- Assert.IsNull(target.AccessTokenEndpoint);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ServiceProviderDescriptionTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + /// <summary> + /// Tests for the <see cref="ServiceProviderEndpoints"/> class. + /// </summary> + [TestClass] + public class ServiceProviderDescriptionTests : TestBase { + /// <summary> + /// A test for UserAuthorizationUri + /// </summary> + [TestMethod] + public void UserAuthorizationUriTest() { + ServiceProviderDescription target = new ServiceProviderDescription(); + MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest); + MessageReceivingEndpoint actual; + target.UserAuthorizationEndpoint = expected; + actual = target.UserAuthorizationEndpoint; + Assert.AreEqual(expected, actual); + + target.UserAuthorizationEndpoint = null; + Assert.IsNull(target.UserAuthorizationEndpoint); + } + + /// <summary> + /// A test for RequestTokenUri + /// </summary> + [TestMethod] + public void RequestTokenUriTest() { + var target = new ServiceProviderDescription(); + MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/requesttoken", HttpDeliveryMethods.GetRequest); + MessageReceivingEndpoint actual; + target.RequestTokenEndpoint = expected; + actual = target.RequestTokenEndpoint; + Assert.AreEqual(expected, actual); + + target.RequestTokenEndpoint = null; + Assert.IsNull(target.RequestTokenEndpoint); + } + + /// <summary> + /// Verifies that oauth parameters are not allowed in <see cref="ServiceProvider.RequestTokenUri"/>, + /// per section OAuth 1.0 section 4.1. + /// </summary> + [TestMethod, ExpectedException(typeof(ArgumentException))] + public void RequestTokenUriWithOAuthParametersTest() { + var target = new ServiceProviderDescription(); + target.RequestTokenEndpoint = new MessageReceivingEndpoint("http://localhost/requesttoken?oauth_token=something", HttpDeliveryMethods.GetRequest); + } + + /// <summary> + /// A test for AccessTokenUri + /// </summary> + [TestMethod] + public void AccessTokenUriTest() { + var target = new ServiceProviderDescription(); + MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/accesstoken", HttpDeliveryMethods.GetRequest); + MessageReceivingEndpoint actual; + target.AccessTokenEndpoint = expected; + actual = target.AccessTokenEndpoint; + Assert.AreEqual(expected, actual); + + target.AccessTokenEndpoint = null; + Assert.IsNull(target.AccessTokenEndpoint); + } + } +} diff --git a/src/DotNetOAuth.Test/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs index 2495cc7..88c17e6 100644 --- a/src/DotNetOAuth.Test/Properties/AssemblyInfo.cs +++ b/src/DotNetOpenAuth.Test/Properties/AssemblyInfo.cs @@ -1,29 +1,29 @@ -//-----------------------------------------------------------------------
-// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("DotNetOAuth.Test")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("DotNetOAuth.Test")]
-[assembly: AssemblyCopyright("Copyright © 2008")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM componenets. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("aef0bb13-b79c-4854-a69a-de58b8feb5d1")]
+//----------------------------------------------------------------------- +// <copyright file="AssemblyInfo.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DotNetOpenAuth.Test")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DotNetOpenAuth.Test")] +[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM componenets. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("aef0bb13-b79c-4854-a69a-de58b8feb5d1")] diff --git a/src/DotNetOAuth.Test/Scenarios/AppendixScenarios.cs b/src/DotNetOpenAuth.Test/Scenarios/AppendixScenarios.cs index a9c8b33..5fb7538 100644 --- a/src/DotNetOAuth.Test/Scenarios/AppendixScenarios.cs +++ b/src/DotNetOpenAuth.Test/Scenarios/AppendixScenarios.cs @@ -1,68 +1,67 @@ -//-----------------------------------------------------------------------
-// <copyright file="AppendixScenarios.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Test {
- using System;
- using System.IO;
- using System.Net;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.Test;
- using DotNetOAuth.Test.Mocks;
- using DotNetOAuth.Test.OAuth;
- using DotNetOAuth.Test.Scenarios;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class AppendixScenarios : TestBase {
- [TestMethod]
- public void SpecAppendixAExample() {
- ServiceProviderDescription serviceDescription = new ServiceProviderDescription() {
- RequestTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/request_token", HttpDeliveryMethods.PostRequest),
- UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://photos.example.net/authorize", HttpDeliveryMethods.GetRequest),
- AccessTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/access_token", HttpDeliveryMethods.PostRequest),
- TamperProtectionElements = new ITamperProtectionChannelBindingElement[] {
- new PlaintextSigningBindingElement(),
- new HmacSha1SigningBindingElement(),
- },
- };
- MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
- ConsumerDescription consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44");
-
- Coordinator coordinator = new Coordinator(
- consumerDescription,
- serviceDescription,
- consumer => {
- consumer.Channel.Send(consumer.PrepareRequestUserAuthorization(new Uri("http://printer.example.com/request_token_ready"), null, null)); // .Send() dropped because this is just a simulation
- string accessToken = consumer.ProcessUserAuthorization().AccessToken;
- var photoRequest = consumer.CreateAuthorizingMessage(accessPhotoEndpoint, accessToken);
- Response protectedPhoto = ((CoordinatingOAuthChannel)consumer.Channel).RequestProtectedResource(photoRequest);
- Assert.IsNotNull(protectedPhoto);
- Assert.AreEqual(HttpStatusCode.OK, protectedPhoto.Status);
- Assert.AreEqual("image/jpeg", protectedPhoto.Headers[HttpResponseHeader.ContentType]);
- Assert.AreNotEqual(0, protectedPhoto.ResponseStream.Length);
- },
- sp => {
- var requestTokenMessage = sp.ReadTokenRequest();
- sp.Channel.Send(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage)); // .Send() dropped because this is just a simulation
- var authRequest = sp.ReadAuthorizationRequest();
- ((InMemoryTokenManager)sp.TokenManager).AuthorizeRequestToken(authRequest.RequestToken);
- sp.Channel.Send(sp.PrepareAuthorizationResponse(authRequest)); // .Send() dropped because this is just a simulation
- var accessRequest = sp.ReadAccessTokenRequest();
- sp.Channel.Send(sp.PrepareAccessTokenMessage(accessRequest)); // .Send() dropped because this is just a simulation
- string accessToken = sp.ReadProtectedResourceAuthorization().AccessToken;
- ((CoordinatingOAuthChannel)sp.Channel).SendDirectRawResponse(new Response {
- ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }),
- Headers = new WebHeaderCollection {
- { HttpResponseHeader.ContentType, "image/jpeg" },
- },
- });
- });
-
- coordinator.Run();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="AppendixScenarios.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System; + using System.IO; + using System.Net; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.Test.Mocks; + using DotNetOpenAuth.Test.Scenarios; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class AppendixScenarios : TestBase { + [TestMethod] + public void SpecAppendixAExample() { + ServiceProviderDescription serviceDescription = new ServiceProviderDescription() { + RequestTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/request_token", HttpDeliveryMethods.PostRequest), + UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://photos.example.net/authorize", HttpDeliveryMethods.GetRequest), + AccessTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/access_token", HttpDeliveryMethods.PostRequest), + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { + new PlaintextSigningBindingElement(), + new HmacSha1SigningBindingElement(), + }, + }; + MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); + ConsumerDescription consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44"); + + Coordinator coordinator = new Coordinator( + consumerDescription, + serviceDescription, + consumer => { + consumer.Channel.Send(consumer.PrepareRequestUserAuthorization(new Uri("http://printer.example.com/request_token_ready"), null, null)); // .Send() dropped because this is just a simulation + string accessToken = consumer.ProcessUserAuthorization().AccessToken; + var photoRequest = consumer.CreateAuthorizingMessage(accessPhotoEndpoint, accessToken); + Response protectedPhoto = ((CoordinatingOAuthChannel)consumer.Channel).RequestProtectedResource(photoRequest); + Assert.IsNotNull(protectedPhoto); + Assert.AreEqual(HttpStatusCode.OK, protectedPhoto.Status); + Assert.AreEqual("image/jpeg", protectedPhoto.Headers[HttpResponseHeader.ContentType]); + Assert.AreNotEqual(0, protectedPhoto.ResponseStream.Length); + }, + sp => { + var requestTokenMessage = sp.ReadTokenRequest(); + sp.Channel.Send(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage)); // .Send() dropped because this is just a simulation + var authRequest = sp.ReadAuthorizationRequest(); + ((InMemoryTokenManager)sp.TokenManager).AuthorizeRequestToken(authRequest.RequestToken); + sp.Channel.Send(sp.PrepareAuthorizationResponse(authRequest)); // .Send() dropped because this is just a simulation + var accessRequest = sp.ReadAccessTokenRequest(); + sp.Channel.Send(sp.PrepareAccessTokenMessage(accessRequest)); // .Send() dropped because this is just a simulation + string accessToken = sp.ReadProtectedResourceAuthorization().AccessToken; + ((CoordinatingOAuthChannel)sp.Channel).SendDirectRawResponse(new Response { + ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }), + Headers = new WebHeaderCollection { + { HttpResponseHeader.ContentType, "image/jpeg" }, + }, + }); + }); + + coordinator.Run(); + } + } +} diff --git a/src/DotNetOAuth.Test/Scenarios/CoordinatingOAuthChannel.cs b/src/DotNetOpenAuth.Test/Scenarios/CoordinatingOAuthChannel.cs index ff23639..9fae4a9 100644 --- a/src/DotNetOAuth.Test/Scenarios/CoordinatingOAuthChannel.cs +++ b/src/DotNetOpenAuth.Test/Scenarios/CoordinatingOAuthChannel.cs @@ -1,144 +1,144 @@ -//-----------------------------------------------------------------------
-// <copyright file="CoordinatingOAuthChannel.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Scenarios {
- using System;
- using System.Threading;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
- using DotNetOAuth.Test.Mocks;
-
- /// <summary>
- /// A special channel used in test simulations to pass messages directly between two parties.
- /// </summary>
- internal class CoordinatingOAuthChannel : OAuthChannel {
- private EventWaitHandle incomingMessageSignal = new AutoResetEvent(false);
- private IProtocolMessage incomingMessage;
- private Response incomingRawResponse;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="CoordinatingOAuthChannel"/> class for Consumers.
- /// </summary>
- /// <param name="signingBindingElement">
- /// The signing element for the Consumer to use. Null for the Service Provider.
- /// </param>
- /// <param name="isConsumer">True if this channel is constructed for a Consumer.</param>
- /// <param name="tokenManager">The token manager to use.</param>
- internal CoordinatingOAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, bool isConsumer, ITokenManager tokenManager)
- : base(
- signingBindingElement,
- new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge),
- tokenManager,
- isConsumer ? (IMessageTypeProvider)new OAuthConsumerMessageTypeProvider() : new OAuthServiceProviderMessageTypeProvider(tokenManager),
- new TestWebRequestHandler()) {
- }
-
- /// <summary>
- /// Gets or sets the coordinating channel used by the other party.
- /// </summary>
- internal CoordinatingOAuthChannel RemoteChannel { get; set; }
-
- internal Response RequestProtectedResource(AccessProtectedResourceRequest request) {
- ((ITamperResistantOAuthMessage)request).HttpMethod = this.GetHttpMethod(((ITamperResistantOAuthMessage)request).HttpMethods);
- this.PrepareMessageForSending(request);
- HttpRequestInfo requestInfo = this.SpoofHttpMethod(request);
- TestBase.TestLogger.InfoFormat("Sending protected resource request: {0}", requestInfo.Message);
- // Drop the outgoing message in the other channel's in-slot and let them know it's there.
- this.RemoteChannel.incomingMessage = requestInfo.Message;
- this.RemoteChannel.incomingMessageSignal.Set();
- return this.AwaitIncomingRawResponse();
- }
-
- internal void SendDirectRawResponse(Response response) {
- this.RemoteChannel.incomingRawResponse = response;
- this.RemoteChannel.incomingMessageSignal.Set();
- }
-
- protected internal override HttpRequestInfo GetRequestFromContext() {
- return new HttpRequestInfo(this.AwaitIncomingMessage());
- }
-
- protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) {
- HttpRequestInfo requestInfo = this.SpoofHttpMethod(request);
- // Drop the outgoing message in the other channel's in-slot and let them know it's there.
- this.RemoteChannel.incomingMessage = requestInfo.Message;
- this.RemoteChannel.incomingMessageSignal.Set();
- // Now wait for a response...
- return this.AwaitIncomingMessage();
- }
-
- protected override Response SendDirectMessageResponse(IProtocolMessage response) {
- this.RemoteChannel.incomingMessage = CloneSerializedParts(response, null);
- this.RemoteChannel.incomingMessageSignal.Set();
- return null;
- }
-
- protected override Response SendIndirectMessage(IDirectedProtocolMessage message) {
- // In this mock transport, direct and indirect messages are the same.
- return this.SendDirectMessageResponse(message);
- }
-
- protected override IProtocolMessage ReadFromRequestInternal(HttpRequestInfo request) {
- return request.Message;
- }
-
- /// <summary>
- /// Spoof HTTP request information for signing/verification purposes.
- /// </summary>
- /// <param name="message">The message to add a pretend HTTP method to.</param>
- /// <returns>A spoofed HttpRequestInfo that wraps the new message.</returns>
- private HttpRequestInfo SpoofHttpMethod(IDirectedProtocolMessage message) {
- HttpRequestInfo requestInfo = new HttpRequestInfo(message);
-
- var signedMessage = message as ITamperResistantOAuthMessage;
- if (signedMessage != null) {
- string httpMethod = this.GetHttpMethod(signedMessage.HttpMethods);
- requestInfo.HttpMethod = httpMethod;
- requestInfo.Url = message.Recipient;
- signedMessage.HttpMethod = httpMethod;
- }
-
- requestInfo.Message = this.CloneSerializedParts(message, requestInfo);
-
- return requestInfo;
- }
-
- private IProtocolMessage AwaitIncomingMessage() {
- this.incomingMessageSignal.WaitOne();
- IProtocolMessage response = this.incomingMessage;
- this.incomingMessage = null;
- return response;
- }
-
- private Response AwaitIncomingRawResponse() {
- this.incomingMessageSignal.WaitOne();
- Response response = this.incomingRawResponse;
- this.incomingRawResponse = null;
- return response;
- }
-
- private T CloneSerializedParts<T>(T message, HttpRequestInfo requestInfo) where T : class, IProtocolMessage {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- MessageReceivingEndpoint recipient = null;
- IOAuthDirectedMessage directedMessage = message as IOAuthDirectedMessage;
- if (directedMessage != null && directedMessage.Recipient != null) {
- recipient = new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods);
- }
-
- MessageSerializer serializer = MessageSerializer.Get(message.GetType());
- return (T)serializer.Deserialize(serializer.Serialize(message), recipient);
- }
-
- private string GetHttpMethod(HttpDeliveryMethods methods) {
- return (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET";
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="CoordinatingOAuthChannel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Scenarios { + using System; + using System.Threading; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + using DotNetOpenAuth.Test.Mocks; + + /// <summary> + /// A special channel used in test simulations to pass messages directly between two parties. + /// </summary> + internal class CoordinatingOAuthChannel : OAuthChannel { + private EventWaitHandle incomingMessageSignal = new AutoResetEvent(false); + private IProtocolMessage incomingMessage; + private Response incomingRawResponse; + + /// <summary> + /// Initializes a new instance of the <see cref="CoordinatingOAuthChannel"/> class for Consumers. + /// </summary> + /// <param name="signingBindingElement"> + /// The signing element for the Consumer to use. Null for the Service Provider. + /// </param> + /// <param name="isConsumer">True if this channel is constructed for a Consumer.</param> + /// <param name="tokenManager">The token manager to use.</param> + internal CoordinatingOAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, bool isConsumer, ITokenManager tokenManager) + : base( + signingBindingElement, + new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge), + tokenManager, + isConsumer ? (IMessageTypeProvider)new OAuthConsumerMessageTypeProvider() : new OAuthServiceProviderMessageTypeProvider(tokenManager), + new TestWebRequestHandler()) { + } + + /// <summary> + /// Gets or sets the coordinating channel used by the other party. + /// </summary> + internal CoordinatingOAuthChannel RemoteChannel { get; set; } + + internal Response RequestProtectedResource(AccessProtectedResourceRequest request) { + ((ITamperResistantOAuthMessage)request).HttpMethod = this.GetHttpMethod(((ITamperResistantOAuthMessage)request).HttpMethods); + this.PrepareMessageForSending(request); + HttpRequestInfo requestInfo = this.SpoofHttpMethod(request); + TestBase.TestLogger.InfoFormat("Sending protected resource request: {0}", requestInfo.Message); + // Drop the outgoing message in the other channel's in-slot and let them know it's there. + this.RemoteChannel.incomingMessage = requestInfo.Message; + this.RemoteChannel.incomingMessageSignal.Set(); + return this.AwaitIncomingRawResponse(); + } + + internal void SendDirectRawResponse(Response response) { + this.RemoteChannel.incomingRawResponse = response; + this.RemoteChannel.incomingMessageSignal.Set(); + } + + protected internal override HttpRequestInfo GetRequestFromContext() { + return new HttpRequestInfo(this.AwaitIncomingMessage()); + } + + protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) { + HttpRequestInfo requestInfo = this.SpoofHttpMethod(request); + // Drop the outgoing message in the other channel's in-slot and let them know it's there. + this.RemoteChannel.incomingMessage = requestInfo.Message; + this.RemoteChannel.incomingMessageSignal.Set(); + // Now wait for a response... + return this.AwaitIncomingMessage(); + } + + protected override Response SendDirectMessageResponse(IProtocolMessage response) { + this.RemoteChannel.incomingMessage = CloneSerializedParts(response, null); + this.RemoteChannel.incomingMessageSignal.Set(); + return null; + } + + protected override Response SendIndirectMessage(IDirectedProtocolMessage message) { + // In this mock transport, direct and indirect messages are the same. + return this.SendDirectMessageResponse(message); + } + + protected override IProtocolMessage ReadFromRequestInternal(HttpRequestInfo request) { + return request.Message; + } + + /// <summary> + /// Spoof HTTP request information for signing/verification purposes. + /// </summary> + /// <param name="message">The message to add a pretend HTTP method to.</param> + /// <returns>A spoofed HttpRequestInfo that wraps the new message.</returns> + private HttpRequestInfo SpoofHttpMethod(IDirectedProtocolMessage message) { + HttpRequestInfo requestInfo = new HttpRequestInfo(message); + + var signedMessage = message as ITamperResistantOAuthMessage; + if (signedMessage != null) { + string httpMethod = this.GetHttpMethod(signedMessage.HttpMethods); + requestInfo.HttpMethod = httpMethod; + requestInfo.Url = message.Recipient; + signedMessage.HttpMethod = httpMethod; + } + + requestInfo.Message = this.CloneSerializedParts(message, requestInfo); + + return requestInfo; + } + + private IProtocolMessage AwaitIncomingMessage() { + this.incomingMessageSignal.WaitOne(); + IProtocolMessage response = this.incomingMessage; + this.incomingMessage = null; + return response; + } + + private Response AwaitIncomingRawResponse() { + this.incomingMessageSignal.WaitOne(); + Response response = this.incomingRawResponse; + this.incomingRawResponse = null; + return response; + } + + private T CloneSerializedParts<T>(T message, HttpRequestInfo requestInfo) where T : class, IProtocolMessage { + if (message == null) { + throw new ArgumentNullException("message"); + } + + MessageReceivingEndpoint recipient = null; + IOAuthDirectedMessage directedMessage = message as IOAuthDirectedMessage; + if (directedMessage != null && directedMessage.Recipient != null) { + recipient = new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods); + } + + MessageSerializer serializer = MessageSerializer.Get(message.GetType()); + return (T)serializer.Deserialize(serializer.Serialize(message), recipient); + } + + private string GetHttpMethod(HttpDeliveryMethods methods) { + return (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET"; + } + } +} diff --git a/src/DotNetOAuth.Test/Scenarios/Coordinator.cs b/src/DotNetOpenAuth.Test/Scenarios/Coordinator.cs index 02f0721..0479092 100644 --- a/src/DotNetOAuth.Test/Scenarios/Coordinator.cs +++ b/src/DotNetOpenAuth.Test/Scenarios/Coordinator.cs @@ -1,121 +1,120 @@ -//-----------------------------------------------------------------------
-// <copyright file="Coordinator.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test.Scenarios {
- using System;
- using System.Threading;
- using DotNetOAuth.OAuth;
- using DotNetOAuth.Test.Mocks;
- using DotNetOAuth.Test.OAuth;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- /// <summary>
- /// Runs a Consumer and Service Provider simultaneously so they can interact in a full simulation.
- /// </summary>
- internal class Coordinator {
- private ConsumerDescription consumerDescription;
- private ServiceProviderDescription serviceDescription;
- private Action<WebConsumer> consumerAction;
- private Action<ServiceProvider> serviceProviderAction;
-
- /// <summary>Initializes a new instance of the <see cref="Coordinator"/> class.</summary>
- /// <param name="consumerDescription">The description of the consumer.</param>
- /// <param name="serviceDescription">The service description that will be used to construct the Consumer and ServiceProvider objects.</param>
- /// <param name="consumerAction">The code path of the Consumer.</param>
- /// <param name="serviceProviderAction">The code path of the Service Provider.</param>
- internal Coordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action<WebConsumer> consumerAction, Action<ServiceProvider> serviceProviderAction) {
- if (consumerDescription == null) {
- throw new ArgumentNullException("consumerDescription");
- }
- if (serviceDescription == null) {
- throw new ArgumentNullException("serviceDescription");
- }
- if (consumerAction == null) {
- throw new ArgumentNullException("consumerAction");
- }
- if (serviceProviderAction == null) {
- throw new ArgumentNullException("serviceProviderAction");
- }
-
- this.consumerDescription = consumerDescription;
- this.serviceDescription = serviceDescription;
- this.consumerAction = consumerAction;
- this.serviceProviderAction = serviceProviderAction;
- }
-
- /// <summary>
- /// Starts the simulation.
- /// </summary>
- internal void Run() {
- // Clone the template signing binding element.
- var signingElement = this.serviceDescription.CreateTamperProtectionElement();
- var consumerSigningElement = signingElement.Clone();
- var spSigningElement = signingElement.Clone();
-
- // Prepare token managers
- InMemoryTokenManager consumerTokenManager = new InMemoryTokenManager();
- InMemoryTokenManager serviceTokenManager = new InMemoryTokenManager();
- consumerTokenManager.AddConsumer(this.consumerDescription);
- serviceTokenManager.AddConsumer(this.consumerDescription);
-
- // Prepare channels that will pass messages directly back and forth.
- CoordinatingOAuthChannel consumerChannel = new CoordinatingOAuthChannel(consumerSigningElement, true, consumerTokenManager);
- CoordinatingOAuthChannel serviceProviderChannel = new CoordinatingOAuthChannel(spSigningElement, false, serviceTokenManager);
- consumerChannel.RemoteChannel = serviceProviderChannel;
- serviceProviderChannel.RemoteChannel = consumerChannel;
-
- // Prepare the Consumer and Service Provider objects
- WebConsumer consumer = new WebConsumer(this.serviceDescription, consumerTokenManager) {
- OAuthChannel = consumerChannel,
- ConsumerKey = this.consumerDescription.ConsumerKey,
- };
- ServiceProvider serviceProvider = new ServiceProvider(this.serviceDescription, serviceTokenManager) {
- OAuthChannel = serviceProviderChannel,
- };
-
- Thread consumerThread = null, serviceProviderThread = null;
- Exception failingException = null;
-
- // Each thread we create needs a surrounding exception catcher so that we can
- // terminate the other thread and inform the test host that the test failed.
- Action<Action> safeWrapper = (action) => {
- try {
- action();
- } catch (Exception ex) {
- // We may be the second thread in an ThreadAbortException, so check the "flag"
- if (failingException == null) {
- failingException = ex;
- if (Thread.CurrentThread == consumerThread) {
- serviceProviderThread.Abort();
- } else {
- consumerThread.Abort();
- }
- }
- }
- };
-
- // Run the threads, and wait for them to complete.
- // If this main thread is aborted (test run aborted), go ahead and abort the other two threads.
- consumerThread = new Thread(() => { safeWrapper(() => { consumerAction(consumer); }); });
- serviceProviderThread = new Thread(() => { safeWrapper(() => { serviceProviderAction(serviceProvider); }); });
- try {
- consumerThread.Start();
- serviceProviderThread.Start();
- consumerThread.Join();
- serviceProviderThread.Join();
- } catch (ThreadAbortException) {
- consumerThread.Abort();
- serviceProviderThread.Abort();
- throw;
- }
-
- // Use the failing reason of a failing sub-thread as our reason, if anything failed.
- if (failingException != null) {
- throw new AssertFailedException("Coordinator thread threw unhandled exception: " + failingException, failingException);
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="Coordinator.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test.Scenarios { + using System; + using System.Threading; + using DotNetOpenAuth.OAuth; + using DotNetOpenAuth.Test.Mocks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + /// <summary> + /// Runs a Consumer and Service Provider simultaneously so they can interact in a full simulation. + /// </summary> + internal class Coordinator { + private ConsumerDescription consumerDescription; + private ServiceProviderDescription serviceDescription; + private Action<WebConsumer> consumerAction; + private Action<ServiceProvider> serviceProviderAction; + + /// <summary>Initializes a new instance of the <see cref="Coordinator"/> class.</summary> + /// <param name="consumerDescription">The description of the consumer.</param> + /// <param name="serviceDescription">The service description that will be used to construct the Consumer and ServiceProvider objects.</param> + /// <param name="consumerAction">The code path of the Consumer.</param> + /// <param name="serviceProviderAction">The code path of the Service Provider.</param> + internal Coordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action<WebConsumer> consumerAction, Action<ServiceProvider> serviceProviderAction) { + if (consumerDescription == null) { + throw new ArgumentNullException("consumerDescription"); + } + if (serviceDescription == null) { + throw new ArgumentNullException("serviceDescription"); + } + if (consumerAction == null) { + throw new ArgumentNullException("consumerAction"); + } + if (serviceProviderAction == null) { + throw new ArgumentNullException("serviceProviderAction"); + } + + this.consumerDescription = consumerDescription; + this.serviceDescription = serviceDescription; + this.consumerAction = consumerAction; + this.serviceProviderAction = serviceProviderAction; + } + + /// <summary> + /// Starts the simulation. + /// </summary> + internal void Run() { + // Clone the template signing binding element. + var signingElement = this.serviceDescription.CreateTamperProtectionElement(); + var consumerSigningElement = signingElement.Clone(); + var spSigningElement = signingElement.Clone(); + + // Prepare token managers + InMemoryTokenManager consumerTokenManager = new InMemoryTokenManager(); + InMemoryTokenManager serviceTokenManager = new InMemoryTokenManager(); + consumerTokenManager.AddConsumer(this.consumerDescription); + serviceTokenManager.AddConsumer(this.consumerDescription); + + // Prepare channels that will pass messages directly back and forth. + CoordinatingOAuthChannel consumerChannel = new CoordinatingOAuthChannel(consumerSigningElement, true, consumerTokenManager); + CoordinatingOAuthChannel serviceProviderChannel = new CoordinatingOAuthChannel(spSigningElement, false, serviceTokenManager); + consumerChannel.RemoteChannel = serviceProviderChannel; + serviceProviderChannel.RemoteChannel = consumerChannel; + + // Prepare the Consumer and Service Provider objects + WebConsumer consumer = new WebConsumer(this.serviceDescription, consumerTokenManager) { + OAuthChannel = consumerChannel, + ConsumerKey = this.consumerDescription.ConsumerKey, + }; + ServiceProvider serviceProvider = new ServiceProvider(this.serviceDescription, serviceTokenManager) { + OAuthChannel = serviceProviderChannel, + }; + + Thread consumerThread = null, serviceProviderThread = null; + Exception failingException = null; + + // Each thread we create needs a surrounding exception catcher so that we can + // terminate the other thread and inform the test host that the test failed. + Action<Action> safeWrapper = (action) => { + try { + action(); + } catch (Exception ex) { + // We may be the second thread in an ThreadAbortException, so check the "flag" + if (failingException == null) { + failingException = ex; + if (Thread.CurrentThread == consumerThread) { + serviceProviderThread.Abort(); + } else { + consumerThread.Abort(); + } + } + } + }; + + // Run the threads, and wait for them to complete. + // If this main thread is aborted (test run aborted), go ahead and abort the other two threads. + consumerThread = new Thread(() => { safeWrapper(() => { consumerAction(consumer); }); }); + serviceProviderThread = new Thread(() => { safeWrapper(() => { serviceProviderAction(serviceProvider); }); }); + try { + consumerThread.Start(); + serviceProviderThread.Start(); + consumerThread.Join(); + serviceProviderThread.Join(); + } catch (ThreadAbortException) { + consumerThread.Abort(); + serviceProviderThread.Abort(); + throw; + } + + // Use the failing reason of a failing sub-thread as our reason, if anything failed. + if (failingException != null) { + throw new AssertFailedException("Coordinator thread threw unhandled exception: " + failingException, failingException); + } + } + } +} diff --git a/src/DotNetOAuth.Test/Settings.StyleCop b/src/DotNetOpenAuth.Test/Settings.StyleCop index c423ea4..26389d0 100644 --- a/src/DotNetOAuth.Test/Settings.StyleCop +++ b/src/DotNetOpenAuth.Test/Settings.StyleCop @@ -1,29 +1,29 @@ -<StyleCopSettings Version="4.3">
- <Analyzers>
- <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.DocumentationRules">
- <Rules>
- <Rule Name="ElementsMustBeDocumented">
- <RuleSettings>
- <BooleanProperty Name="Enabled">False</BooleanProperty>
- </RuleSettings>
- </Rule>
- <Rule Name="EnumerationItemsMustBeDocumented">
- <RuleSettings>
- <BooleanProperty Name="Enabled">False</BooleanProperty>
- </RuleSettings>
- </Rule>
- </Rules>
- <AnalyzerSettings />
- </Analyzer>
- <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.LayoutRules">
- <Rules>
- <Rule Name="SingleLineCommentMustBePrecededByBlankLine">
- <RuleSettings>
- <BooleanProperty Name="Enabled">False</BooleanProperty>
- </RuleSettings>
- </Rule>
- </Rules>
- <AnalyzerSettings />
- </Analyzer>
- </Analyzers>
+<StyleCopSettings Version="4.3"> + <Analyzers> + <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.DocumentationRules"> + <Rules> + <Rule Name="ElementsMustBeDocumented"> + <RuleSettings> + <BooleanProperty Name="Enabled">False</BooleanProperty> + </RuleSettings> + </Rule> + <Rule Name="EnumerationItemsMustBeDocumented"> + <RuleSettings> + <BooleanProperty Name="Enabled">False</BooleanProperty> + </RuleSettings> + </Rule> + </Rules> + <AnalyzerSettings /> + </Analyzer> + <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.LayoutRules"> + <Rules> + <Rule Name="SingleLineCommentMustBePrecededByBlankLine"> + <RuleSettings> + <BooleanProperty Name="Enabled">False</BooleanProperty> + </RuleSettings> + </Rule> + </Rules> + <AnalyzerSettings /> + </Analyzer> + </Analyzers> </StyleCopSettings>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Test/Test References/DotNetOpenAuth.accessor b/src/DotNetOpenAuth.Test/Test References/DotNetOpenAuth.accessor new file mode 100644 index 0000000..35adf51 --- /dev/null +++ b/src/DotNetOpenAuth.Test/Test References/DotNetOpenAuth.accessor @@ -0,0 +1 @@ +DotNetOpenAuth.dll diff --git a/src/DotNetOAuth.Test/TestBase.cs b/src/DotNetOpenAuth.Test/TestBase.cs index 997841c..9ec0858 100644 --- a/src/DotNetOAuth.Test/TestBase.cs +++ b/src/DotNetOpenAuth.Test/TestBase.cs @@ -1,45 +1,45 @@ -//-----------------------------------------------------------------------
-// <copyright file="TestBase.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test {
- using System.Reflection;
- using DotNetOAuth.OAuth.Messages;
- using log4net;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- /// <summary>
- /// The base class that all test classes inherit from.
- /// </summary>
- public class TestBase {
- /// <summary>
- /// The logger that tests should use.
- /// </summary>
- internal static readonly ILog TestLogger = LogManager.GetLogger("DotNetOAuth.Test");
-
- /// <summary>
- /// Gets or sets the test context which provides
- /// information about and functionality for the current test run.
- /// </summary>
- public TestContext TestContext { get; set; }
-
- /// <summary>
- /// The TestInitialize method for the test cases.
- /// </summary>
- [TestInitialize]
- public virtual void SetUp() {
- log4net.Config.XmlConfigurator.Configure(Assembly.GetExecutingAssembly().GetManifestResourceStream("DotNetOAuth.Test.Logging.config"));
- MessageBase.LowSecurityMode = true;
- }
-
- /// <summary>
- /// The TestCleanup method for the test cases.
- /// </summary>
- [TestCleanup]
- public virtual void Cleanup() {
- log4net.LogManager.Shutdown();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TestBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System.Reflection; + using DotNetOpenAuth.OAuth.Messages; + using log4net; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + /// <summary> + /// The base class that all test classes inherit from. + /// </summary> + public class TestBase { + /// <summary> + /// The logger that tests should use. + /// </summary> + internal static readonly ILog TestLogger = LogManager.GetLogger("DotNetOpenAuth.Test"); + + /// <summary> + /// Gets or sets the test context which provides + /// information about and functionality for the current test run. + /// </summary> + public TestContext TestContext { get; set; } + + /// <summary> + /// The TestInitialize method for the test cases. + /// </summary> + [TestInitialize] + public virtual void SetUp() { + log4net.Config.XmlConfigurator.Configure(Assembly.GetExecutingAssembly().GetManifestResourceStream("DotNetOpenAuth.Test.Logging.config")); + MessageBase.LowSecurityMode = true; + } + + /// <summary> + /// The TestCleanup method for the test cases. + /// </summary> + [TestCleanup] + public virtual void Cleanup() { + log4net.LogManager.Shutdown(); + } + } +} diff --git a/src/DotNetOAuth.Test/UriUtilTests.cs b/src/DotNetOpenAuth.Test/UriUtilTests.cs index 0201e8a..3bd0772 100644 --- a/src/DotNetOAuth.Test/UriUtilTests.cs +++ b/src/DotNetOpenAuth.Test/UriUtilTests.cs @@ -1,21 +1,21 @@ -//-----------------------------------------------------------------------
-// <copyright file="UriUtilTests.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Test {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Microsoft.VisualStudio.TestTools.UnitTesting;
-
- [TestClass]
- public class UriUtilTests {
- [TestMethod]
- public void QueryStringContainsOAuthParametersNull() {
- Assert.IsFalse(UriUtil.QueryStringContainsOAuthParameters(null));
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="UriUtilTests.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + + [TestClass] + public class UriUtilTests { + [TestMethod] + public void QueryStringContainsOAuthParametersNull() { + Assert.IsFalse(UriUtil.QueryStringContainsOAuthParameters(null)); + } + } +} diff --git a/src/DotNetOAuth.sln b/src/DotNetOpenAuth.sln index a546d59..9c82423 100644 --- a/src/DotNetOAuth.sln +++ b/src/DotNetOpenAuth.sln @@ -1,116 +1,116 @@ -
-Microsoft Visual Studio Solution File, Format Version 10.00
-# Visual Studio 2008
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOAuth", "DotNetOAuth\DotNetOAuth.csproj", "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOAuth.Test", "DotNetOAuth.Test\DotNetOAuth.Test.csproj", "{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{20B5E173-C3C4-49F8-BD25-E69044075B4D}"
- ProjectSection(SolutionItems) = preProject
- DotNetOAuth.vsmdi = DotNetOAuth.vsmdi
- LocalTestRun.testrunconfig = LocalTestRun.testrunconfig
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Specs", "Specs", "{CD57219F-24F4-4136-8741-6063D0D7A031}"
- ProjectSection(SolutionItems) = preProject
- ..\doc\specs\OAuth Core 1.0.htm = ..\doc\specs\OAuth Core 1.0.htm
- EndProjectSection
-EndProject
-Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "Consumer", "..\samples\Consumer", "{F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}"
- ProjectSection(WebsiteProperties) = preProject
- TargetFramework = "3.5"
- ProjectReferences = "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}|DotNetOAuth.dll;{AA78D112-D889-414B-A7D4-467B34C7B663}|DotNetOAuth.ApplicationBlock.dll;"
- Debug.AspNetCompiler.VirtualPath = "/Consumer"
- Debug.AspNetCompiler.PhysicalPath = "..\samples\Consumer\"
- Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\Consumer\"
- Debug.AspNetCompiler.Updateable = "true"
- Debug.AspNetCompiler.ForceOverwrite = "true"
- Debug.AspNetCompiler.FixedNames = "false"
- Debug.AspNetCompiler.Debug = "True"
- Release.AspNetCompiler.VirtualPath = "/Consumer"
- Release.AspNetCompiler.PhysicalPath = "..\samples\Consumer\"
- Release.AspNetCompiler.TargetPath = "PrecompiledWeb\Consumer\"
- Release.AspNetCompiler.Updateable = "true"
- Release.AspNetCompiler.ForceOverwrite = "true"
- Release.AspNetCompiler.FixedNames = "false"
- Release.AspNetCompiler.Debug = "False"
- VWDPort = "16323"
- DefaultWebSiteLanguage = "Visual C#"
- EndProjectSection
- ProjectSection(ProjectDependencies) = postProject
- {EC910270-AAB6-4AC6-9B57-99118CFBE557} = {EC910270-AAB6-4AC6-9B57-99118CFBE557}
- EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{B4C6F647-C046-4B54-BE12-7701C4119EE7}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumerWpf", "..\samples\ConsumerWpf\ConsumerWpf.csproj", "{6EC36418-DBC5-4AD1-A402-413604AA7A08}"
-EndProject
-Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "ServiceProvider", "..\samples\ServiceProvider", "{EC910270-AAB6-4AC6-9B57-99118CFBE557}"
- ProjectSection(WebsiteProperties) = preProject
- TargetFramework = "3.5"
- ProjectReferences = "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}|DotNetOAuth.dll;"
- Debug.AspNetCompiler.VirtualPath = "/ServiceProvider"
- Debug.AspNetCompiler.PhysicalPath = "..\samples\ServiceProvider\"
- Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\ServiceProvider\"
- Debug.AspNetCompiler.Updateable = "true"
- Debug.AspNetCompiler.ForceOverwrite = "true"
- Debug.AspNetCompiler.FixedNames = "false"
- Debug.AspNetCompiler.Debug = "True"
- Release.AspNetCompiler.VirtualPath = "/ServiceProvider"
- Release.AspNetCompiler.PhysicalPath = "..\samples\ServiceProvider\"
- Release.AspNetCompiler.TargetPath = "PrecompiledWeb\ServiceProvider\"
- Release.AspNetCompiler.Updateable = "true"
- Release.AspNetCompiler.ForceOverwrite = "true"
- Release.AspNetCompiler.FixedNames = "false"
- Release.AspNetCompiler.Debug = "False"
- VWDPort = "65169"
- DefaultWebSiteLanguage = "Visual C#"
- EndProjectSection
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOAuth.ApplicationBlock", "..\samples\DotNetOAuth.ApplicationBlock\DotNetOAuth.ApplicationBlock.csproj", "{AA78D112-D889-414B-A7D4-467B34C7B663}"
-EndProject
-Global
- GlobalSection(TestCaseManagementSettings) = postSolution
- CategoryFile = DotNetOAuth.vsmdi
- EndGlobalSection
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|Any CPU = Debug|Any CPU
- Release|Any CPU = Release|Any CPU
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Release|Any CPU.Build.0 = Release|Any CPU
- {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Release|Any CPU.Build.0 = Release|Any CPU
- {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Release|Any CPU.ActiveCfg = Debug|Any CPU
- {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Release|Any CPU.Build.0 = Debug|Any CPU
- {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Release|Any CPU.Build.0 = Release|Any CPU
- {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Release|Any CPU.ActiveCfg = Debug|Any CPU
- {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Release|Any CPU.Build.0 = Debug|Any CPU
- {AA78D112-D889-414B-A7D4-467B34C7B663}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {AA78D112-D889-414B-A7D4-467B34C7B663}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {AA78D112-D889-414B-A7D4-467B34C7B663}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {AA78D112-D889-414B-A7D4-467B34C7B663}.Release|Any CPU.Build.0 = Release|Any CPU
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
- GlobalSection(NestedProjects) = preSolution
- {CD57219F-24F4-4136-8741-6063D0D7A031} = {20B5E173-C3C4-49F8-BD25-E69044075B4D}
- {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB} = {B4C6F647-C046-4B54-BE12-7701C4119EE7}
- {6EC36418-DBC5-4AD1-A402-413604AA7A08} = {B4C6F647-C046-4B54-BE12-7701C4119EE7}
- {EC910270-AAB6-4AC6-9B57-99118CFBE557} = {B4C6F647-C046-4B54-BE12-7701C4119EE7}
- {AA78D112-D889-414B-A7D4-467B34C7B663} = {B4C6F647-C046-4B54-BE12-7701C4119EE7}
- EndGlobalSection
-EndGlobal
+ +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth", "DotNetOpenAuth\DotNetOpenAuth.csproj", "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.Test", "DotNetOpenAuth.Test\DotNetOpenAuth.Test.csproj", "{4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{20B5E173-C3C4-49F8-BD25-E69044075B4D}" + ProjectSection(SolutionItems) = preProject + DotNetOpenAuth.vsmdi = DotNetOpenAuth.vsmdi + LocalTestRun.testrunconfig = LocalTestRun.testrunconfig + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Specs", "Specs", "{CD57219F-24F4-4136-8741-6063D0D7A031}" + ProjectSection(SolutionItems) = preProject + ..\doc\specs\OAuth Core 1.0.htm = ..\doc\specs\OAuth Core 1.0.htm + EndProjectSection +EndProject +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "Consumer", "..\samples\Consumer", "{F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}" + ProjectSection(WebsiteProperties) = preProject + TargetFramework = "3.5" + ProjectReferences = "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}|DotNetOpenAuth.dll;{AA78D112-D889-414B-A7D4-467B34C7B663}|DotNetOpenAuth.ApplicationBlock.dll;" + Debug.AspNetCompiler.VirtualPath = "/Consumer" + Debug.AspNetCompiler.PhysicalPath = "..\samples\Consumer\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\Consumer\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/Consumer" + Release.AspNetCompiler.PhysicalPath = "..\samples\Consumer\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\Consumer\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "16323" + DefaultWebSiteLanguage = "Visual C#" + EndProjectSection + ProjectSection(ProjectDependencies) = postProject + {EC910270-AAB6-4AC6-9B57-99118CFBE557} = {EC910270-AAB6-4AC6-9B57-99118CFBE557} + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{B4C6F647-C046-4B54-BE12-7701C4119EE7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsumerWpf", "..\samples\ConsumerWpf\ConsumerWpf.csproj", "{6EC36418-DBC5-4AD1-A402-413604AA7A08}" +EndProject +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "ServiceProvider", "..\samples\ServiceProvider", "{EC910270-AAB6-4AC6-9B57-99118CFBE557}" + ProjectSection(WebsiteProperties) = preProject + TargetFramework = "3.5" + ProjectReferences = "{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}|DotNetOpenAuth.dll;" + Debug.AspNetCompiler.VirtualPath = "/ServiceProvider" + Debug.AspNetCompiler.PhysicalPath = "..\samples\ServiceProvider\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\ServiceProvider\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/ServiceProvider" + Release.AspNetCompiler.PhysicalPath = "..\samples\ServiceProvider\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\ServiceProvider\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "65169" + DefaultWebSiteLanguage = "Visual C#" + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.ApplicationBlock", "..\samples\DotNetOpenAuth.ApplicationBlock\DotNetOpenAuth.ApplicationBlock.csproj", "{AA78D112-D889-414B-A7D4-467B34C7B663}" +EndProject +Global + GlobalSection(TestCaseManagementSettings) = postSolution + CategoryFile = DotNetOpenAuth.vsmdi + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}.Release|Any CPU.Build.0 = Release|Any CPU + {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4376ECC9-C346-4A99-B13C-FA93C0FBD2C9}.Release|Any CPU.Build.0 = Release|Any CPU + {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Release|Any CPU.ActiveCfg = Debug|Any CPU + {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB}.Release|Any CPU.Build.0 = Debug|Any CPU + {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6EC36418-DBC5-4AD1-A402-413604AA7A08}.Release|Any CPU.Build.0 = Release|Any CPU + {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Release|Any CPU.ActiveCfg = Debug|Any CPU + {EC910270-AAB6-4AC6-9B57-99118CFBE557}.Release|Any CPU.Build.0 = Debug|Any CPU + {AA78D112-D889-414B-A7D4-467B34C7B663}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AA78D112-D889-414B-A7D4-467B34C7B663}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AA78D112-D889-414B-A7D4-467B34C7B663}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AA78D112-D889-414B-A7D4-467B34C7B663}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {CD57219F-24F4-4136-8741-6063D0D7A031} = {20B5E173-C3C4-49F8-BD25-E69044075B4D} + {F9076F04-17AF-4205-93A2-1D3BEBFCDAEB} = {B4C6F647-C046-4B54-BE12-7701C4119EE7} + {6EC36418-DBC5-4AD1-A402-413604AA7A08} = {B4C6F647-C046-4B54-BE12-7701C4119EE7} + {EC910270-AAB6-4AC6-9B57-99118CFBE557} = {B4C6F647-C046-4B54-BE12-7701C4119EE7} + {AA78D112-D889-414B-A7D4-467B34C7B663} = {B4C6F647-C046-4B54-BE12-7701C4119EE7} + EndGlobalSection +EndGlobal diff --git a/src/DotNetOAuth.vsmdi b/src/DotNetOpenAuth.vsmdi index 027090d..35648ec 100644 --- a/src/DotNetOAuth.vsmdi +++ b/src/DotNetOpenAuth.vsmdi @@ -1,6 +1,6 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<TestLists xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2006">
- <TestList name="Lists of Tests" id="8c43106b-9dc1-4907-a29f-aa66a61bf5b6">
- <RunConfiguration id="abbd81c0-7d7b-4c98-878c-05dbead62c27" name="Local Test Run" storage="localtestrun.testrunconfig" type="Microsoft.VisualStudio.TestTools.Common.TestRunConfiguration, Microsoft.VisualStudio.QualityTools.Common, PublicKeyToken=b03f5f7f11d50a3a" />
- </TestList>
+<?xml version="1.0" encoding="UTF-8"?> +<TestLists xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2006"> + <TestList name="Lists of Tests" id="8c43106b-9dc1-4907-a29f-aa66a61bf5b6"> + <RunConfiguration id="abbd81c0-7d7b-4c98-878c-05dbead62c27" name="Local Test Run" storage="localtestrun.testrunconfig" type="Microsoft.VisualStudio.TestTools.Common.TestRunConfiguration, Microsoft.VisualStudio.QualityTools.Common, PublicKeyToken=b03f5f7f11d50a3a" /> + </TestList> </TestLists>
\ No newline at end of file diff --git a/src/DotNetOAuth/ClassDiagram.cd b/src/DotNetOpenAuth/ClassDiagram.cd index 83bea98..f00414c 100644 --- a/src/DotNetOAuth/ClassDiagram.cd +++ b/src/DotNetOpenAuth/ClassDiagram.cd @@ -1,54 +1,54 @@ -<?xml version="1.0" encoding="utf-8"?>
-<ClassDiagram MajorVersion="1" MinorVersion="1" MembersFormat="NameAndType">
- <Class Name="DotNetOAuth.ServiceProvider">
- <Position X="0.5" Y="0.5" Width="5.75" />
- <Members>
- <Field Name="channel" Hidden="true" />
- </Members>
- <TypeIdentifier>
- <HashCode>EAoAAAsgAAAAIAAAEAAAAAAAAAAIAAEAAQAIAAwAAAA=</HashCode>
- <FileName>ServiceProvider.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.DesktopConsumer">
- <Position X="11.5" Y="4.5" Width="4.75" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAEAAAAAAABAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>DesktopConsumer.cs</FileName>
- <NewMemberFileName>WebConsumer.cs</NewMemberFileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.ServiceProviderDescription">
- <Position X="1.25" Y="5.25" Width="4.75" />
- <Compartments>
- <Compartment Name="Fields" Collapsed="true" />
- </Compartments>
- <TypeIdentifier>
- <HashCode>AAACAAgAAAAEAAAQAAAAAAAAAAAAACAAAAAgAAAAAAA=</HashCode>
- <FileName>ServiceProviderDescription.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.WebConsumer">
- <Position X="6.5" Y="4.5" Width="4.75" />
- <InheritanceLine Type="DotNetOAuth.ConsumerBase" FixedToPoint="true">
- <Path>
- <Point X="11.375" Y="3.978" />
- <Point X="11.375" Y="4.125" />
- <Point X="8.125" Y="4.125" />
- <Point X="8.125" Y="4.5" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAA=</HashCode>
- <FileName>WebConsumer.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.ConsumerBase">
- <Position X="9" Y="0.5" Width="4.75" />
- <TypeIdentifier>
- <HashCode>ACAAAAEgAAABAAAAAAAABgAAAAAIAAAAAQAAAAABABA=</HashCode>
- <FileName>ConsumerBase.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Font Name="Segoe UI" Size="9" />
+<?xml version="1.0" encoding="utf-8"?> +<ClassDiagram MajorVersion="1" MinorVersion="1" MembersFormat="NameAndType"> + <Class Name="DotNetOpenAuth.ServiceProvider"> + <Position X="0.5" Y="0.5" Width="5.75" /> + <Members> + <Field Name="channel" Hidden="true" /> + </Members> + <TypeIdentifier> + <HashCode>EAoAAAsgAAAAIAAAEAAAAAAAAAAIAAEAAQAIAAwAAAA=</HashCode> + <FileName>ServiceProvider.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.DesktopConsumer"> + <Position X="11.5" Y="4.5" Width="4.75" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAEAAAAAAABAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>DesktopConsumer.cs</FileName> + <NewMemberFileName>WebConsumer.cs</NewMemberFileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.ServiceProviderDescription"> + <Position X="1.25" Y="5.25" Width="4.75" /> + <Compartments> + <Compartment Name="Fields" Collapsed="true" /> + </Compartments> + <TypeIdentifier> + <HashCode>AAACAAgAAAAEAAAQAAAAAAAAAAAAACAAAAAgAAAAAAA=</HashCode> + <FileName>ServiceProviderDescription.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.WebConsumer"> + <Position X="6.5" Y="4.5" Width="4.75" /> + <InheritanceLine Type="DotNetOpenAuth.ConsumerBase" FixedToPoint="true"> + <Path> + <Point X="11.375" Y="3.978" /> + <Point X="11.375" Y="4.125" /> + <Point X="8.125" Y="4.125" /> + <Point X="8.125" Y="4.5" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAA=</HashCode> + <FileName>WebConsumer.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.ConsumerBase"> + <Position X="9" Y="0.5" Width="4.75" /> + <TypeIdentifier> + <HashCode>ACAAAAEgAAABAAAAAAAABgAAAAAIAAAAAQAAAAABABA=</HashCode> + <FileName>ConsumerBase.cs</FileName> + </TypeIdentifier> + </Class> + <Font Name="Segoe UI" Size="9" /> </ClassDiagram>
\ No newline at end of file diff --git a/src/DotNetOAuth/DotNetOAuth.csproj b/src/DotNetOpenAuth/DotNetOpenAuth.csproj index 807f73e..cf155b9 100644 --- a/src/DotNetOAuth/DotNetOAuth.csproj +++ b/src/DotNetOpenAuth/DotNetOpenAuth.csproj @@ -1,172 +1,172 @@ -<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProductVersion>9.0.30729</ProductVersion>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</ProjectGuid>
- <OutputType>Library</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>DotNetOAuth</RootNamespace>
- <AssemblyName>DotNetOAuth</AssemblyName>
- <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
- <FileAlignment>512</FileAlignment>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>true</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>false</Optimize>
- <OutputPath>..\..\bin\Debug\</OutputPath>
- <DefineConstants>DEBUG;TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
- <DocumentationFile>..\..\bin\debug\DotNetOAuth.xml</DocumentationFile>
- <RunCodeAnalysis>false</RunCodeAnalysis>
- <CodeAnalysisRules>-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055</CodeAnalysisRules>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <DebugType>pdbonly</DebugType>
- <Optimize>true</Optimize>
- <OutputPath>..\..\bin\Release\</OutputPath>
- <DefineConstants>TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
- <DocumentationFile>..\..\bin\debug\DotNetOAuth.xml</DocumentationFile>
- <RunCodeAnalysis>true</RunCodeAnalysis>
- <CodeAnalysisRules>-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055</CodeAnalysisRules>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Sign)' == 'true' ">
- <SignAssembly>true</SignAssembly>
- <AssemblyOriginatorKeyFile>..\official-build-key.pfx</AssemblyOriginatorKeyFile>
- <DefineConstants>$(DefineConstants);StrongNameSigned</DefineConstants>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\..\lib\log4net.dll</HintPath>
- </Reference>
- <Reference Include="System" />
- <Reference Include="System.Core">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Data" />
- <Reference Include="System.ServiceModel">
- <RequiredTargetFramework>3.0</RequiredTargetFramework>
- </Reference>
- <Reference Include="System.Web" />
- <Reference Include="System.XML" />
- <Reference Include="System.Xml.Linq">
- <RequiredTargetFramework>3.5</RequiredTargetFramework>
- </Reference>
- </ItemGroup>
- <ItemGroup>
- <Compile Include="OAuth\ChannelElements\OAuthConsumerMessageTypeProvider.cs" />
- <Compile Include="OAuth\ChannelElements\ITokenGenerator.cs" />
- <Compile Include="OAuth\ChannelElements\ITokenManager.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthHttpMethodBindingElement.cs" />
- <Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElement.cs" />
- <Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElement.cs" />
- <Compile Include="OAuth\ChannelElements\SigningBindingElementChain.cs" />
- <Compile Include="OAuth\ChannelElements\StandardTokenGenerator.cs" />
- <Compile Include="OAuth\ChannelElements\TokenType.cs" />
- <Compile Include="OAuth\ConsumerBase.cs" />
- <Compile Include="OAuth\DesktopConsumer.cs" />
- <Compile Include="GlobalSuppressions.cs" />
- <Compile Include="OAuth\Messages\ITokenSecretContainingMessage.cs" />
- <Compile Include="Messaging\ChannelEventArgs.cs" />
- <Compile Include="Messaging\ITamperProtectionChannelBindingElement.cs" />
- <Compile Include="OAuth\ServiceProviderDescription.cs" />
- <Compile Include="OAuth\Messages\ITokenContainingMessage.cs" />
- <Compile Include="OAuth\Messages\SignedMessageBase.cs" />
- <Compile Include="Messaging\Bindings\NonceMemoryStore.cs" />
- <Compile Include="OAuth\ChannelElements\SigningBindingElementBase.cs" />
- <Compile Include="OAuth\WebConsumer.cs" />
- <Compile Include="OAuth\ChannelElements\IWebRequestHandler.cs" />
- <Compile Include="OAuth\ChannelElements\ITamperResistantOAuthMessage.cs" />
- <Compile Include="OAuth\Messages\MessageBase.cs" />
- <Compile Include="OAuth\Messages\AuthorizedTokenRequest.cs" />
- <Compile Include="Messaging\Bindings\INonceStore.cs" />
- <Compile Include="Messaging\Bindings\StandardReplayProtectionBindingElement.cs" />
- <Compile Include="Messaging\MessagePartAttribute.cs" />
- <Compile Include="Messaging\MessageProtections.cs" />
- <Compile Include="Messaging\IChannelBindingElement.cs" />
- <Compile Include="Messaging\Bindings\ReplayedMessageException.cs" />
- <Compile Include="Messaging\Bindings\ExpiredMessageException.cs" />
- <Compile Include="Messaging\Bindings\InvalidSignatureException.cs" />
- <Compile Include="Messaging\Bindings\IReplayProtectedProtocolMessage.cs" />
- <Compile Include="Messaging\Bindings\IExpiringProtocolMessage.cs" />
- <Compile Include="OAuth\Messages\AccessProtectedResourceRequest.cs" />
- <Compile Include="OAuth\Messages\AuthorizedTokenResponse.cs" />
- <Compile Include="OAuth\ChannelElements\IOAuthDirectedMessage.cs" />
- <Compile Include="OAuth\Messages\UserAuthorizationResponse.cs" />
- <Compile Include="OAuth\Messages\UserAuthorizationRequest.cs" />
- <Compile Include="OAuth\Messages\UnauthorizedTokenResponse.cs" />
- <Compile Include="Messaging\Channel.cs" />
- <Compile Include="Messaging\HttpRequestInfo.cs" />
- <Compile Include="Messaging\IDirectedProtocolMessage.cs" />
- <Compile Include="Messaging\IMessageTypeProvider.cs" />
- <Compile Include="Messaging\ITamperResistantProtocolMessage.cs" />
- <Compile Include="Messaging\MessageSerializer.cs" />
- <Compile Include="Messaging\MessagingStrings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>MessagingStrings.resx</DependentUpon>
- </Compile>
- <Compile Include="Messaging\MessagingUtilities.cs" />
- <Compile Include="Messaging\Bindings\StandardExpirationBindingElement.cs" />
- <Compile Include="Messaging\Reflection\ValueMapping.cs" />
- <Compile Include="Messaging\Reflection\MessageDescription.cs" />
- <Compile Include="Messaging\Reflection\MessageDictionary.cs" />
- <Compile Include="Messaging\Reflection\MessagePart.cs" />
- <Compile Include="Messaging\UnprotectedMessageException.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthChannel.cs" />
- <Compile Include="Messaging\Response.cs" />
- <Compile Include="Messaging\IProtocolMessage.cs" />
- <Compile Include="Logger.cs" />
- <Compile Include="Loggers\ILog.cs" />
- <Compile Include="Loggers\Log4NetLogger.cs" />
- <Compile Include="Loggers\NoOpLogger.cs" />
- <Compile Include="Loggers\TraceLogger.cs" />
- <Compile Include="Messaging\HttpDeliveryMethods.cs" />
- <Compile Include="Messaging\MessageTransport.cs" />
- <Compile Include="OAuth\ChannelElements\OAuthServiceProviderMessageTypeProvider.cs" />
- <Compile Include="Messaging\ProtocolException.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="OAuth\Messages\UnauthorizedTokenRequest.cs" />
- <Compile Include="OAuth\ChannelElements\RsaSha1SigningBindingElement.cs" />
- <Compile Include="OAuth\ChannelElements\StandardWebRequestHandler.cs" />
- <Compile Include="Messaging\MessageReceivingEndpoint.cs" />
- <Compile Include="Util.cs" />
- <Compile Include="OAuth\Protocol.cs" />
- <Compile Include="OAuth\ServiceProvider.cs" />
- <Compile Include="Strings.Designer.cs">
- <AutoGen>True</AutoGen>
- <DesignTime>True</DesignTime>
- <DependentUpon>Strings.resx</DependentUpon>
- </Compile>
- <Compile Include="UriUtil.cs" />
- </ItemGroup>
- <ItemGroup>
- <None Include="ClassDiagram.cd" />
- <None Include="OAuth\Messages\OAuth Messages.cd" />
- <None Include="Messaging\Bindings\Bindings.cd" />
- <None Include="Messaging\Exceptions.cd" />
- <None Include="Messaging\Messaging.cd" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="Messaging\MessagingStrings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>MessagingStrings.Designer.cs</LastGenOutput>
- </EmbeddedResource>
- <EmbeddedResource Include="Strings.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>Strings.Designer.cs</LastGenOutput>
- <SubType>Designer</SubType>
- </EmbeddedResource>
- </ItemGroup>
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
- <Import Project="..\..\tools\DotNetOAuth.Versioning.targets" />
-</Project>
\ No newline at end of file +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.30729</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>DotNetOpenAuth</RootNamespace> + <AssemblyName>DotNetOpenAuth</AssemblyName> + <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>..\..\bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <AllowUnsafeBlocks>false</AllowUnsafeBlocks> + <DocumentationFile>..\..\bin\Debug\DotNetOpenAuth.xml</DocumentationFile> + <RunCodeAnalysis>false</RunCodeAnalysis> + <CodeAnalysisRules>-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055</CodeAnalysisRules> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>..\..\bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <AllowUnsafeBlocks>false</AllowUnsafeBlocks> + <DocumentationFile>..\..\bin\debug\DotNetOpenAuth.xml</DocumentationFile> + <RunCodeAnalysis>true</RunCodeAnalysis> + <CodeAnalysisRules>-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055</CodeAnalysisRules> + </PropertyGroup> + <PropertyGroup Condition=" '$(Sign)' == 'true' "> + <SignAssembly>true</SignAssembly> + <AssemblyOriginatorKeyFile>..\official-build-key.pfx</AssemblyOriginatorKeyFile> + <DefineConstants>$(DefineConstants);StrongNameSigned</DefineConstants> + </PropertyGroup> + <ItemGroup> + <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\lib\log4net.dll</HintPath> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data" /> + <Reference Include="System.ServiceModel"> + <RequiredTargetFramework>3.0</RequiredTargetFramework> + </Reference> + <Reference Include="System.Web" /> + <Reference Include="System.XML" /> + <Reference Include="System.Xml.Linq"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + </ItemGroup> + <ItemGroup> + <Compile Include="OAuth\ChannelElements\OAuthConsumerMessageTypeProvider.cs" /> + <Compile Include="OAuth\ChannelElements\ITokenGenerator.cs" /> + <Compile Include="OAuth\ChannelElements\ITokenManager.cs" /> + <Compile Include="OAuth\ChannelElements\OAuthHttpMethodBindingElement.cs" /> + <Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElement.cs" /> + <Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElement.cs" /> + <Compile Include="OAuth\ChannelElements\SigningBindingElementChain.cs" /> + <Compile Include="OAuth\ChannelElements\StandardTokenGenerator.cs" /> + <Compile Include="OAuth\ChannelElements\TokenType.cs" /> + <Compile Include="OAuth\ConsumerBase.cs" /> + <Compile Include="OAuth\DesktopConsumer.cs" /> + <Compile Include="GlobalSuppressions.cs" /> + <Compile Include="OAuth\Messages\ITokenSecretContainingMessage.cs" /> + <Compile Include="Messaging\ChannelEventArgs.cs" /> + <Compile Include="Messaging\ITamperProtectionChannelBindingElement.cs" /> + <Compile Include="OAuth\ServiceProviderDescription.cs" /> + <Compile Include="OAuth\Messages\ITokenContainingMessage.cs" /> + <Compile Include="OAuth\Messages\SignedMessageBase.cs" /> + <Compile Include="Messaging\Bindings\NonceMemoryStore.cs" /> + <Compile Include="OAuth\ChannelElements\SigningBindingElementBase.cs" /> + <Compile Include="OAuth\WebConsumer.cs" /> + <Compile Include="OAuth\ChannelElements\IWebRequestHandler.cs" /> + <Compile Include="OAuth\ChannelElements\ITamperResistantOAuthMessage.cs" /> + <Compile Include="OAuth\Messages\MessageBase.cs" /> + <Compile Include="OAuth\Messages\AuthorizedTokenRequest.cs" /> + <Compile Include="Messaging\Bindings\INonceStore.cs" /> + <Compile Include="Messaging\Bindings\StandardReplayProtectionBindingElement.cs" /> + <Compile Include="Messaging\MessagePartAttribute.cs" /> + <Compile Include="Messaging\MessageProtections.cs" /> + <Compile Include="Messaging\IChannelBindingElement.cs" /> + <Compile Include="Messaging\Bindings\ReplayedMessageException.cs" /> + <Compile Include="Messaging\Bindings\ExpiredMessageException.cs" /> + <Compile Include="Messaging\Bindings\InvalidSignatureException.cs" /> + <Compile Include="Messaging\Bindings\IReplayProtectedProtocolMessage.cs" /> + <Compile Include="Messaging\Bindings\IExpiringProtocolMessage.cs" /> + <Compile Include="OAuth\Messages\AccessProtectedResourceRequest.cs" /> + <Compile Include="OAuth\Messages\AuthorizedTokenResponse.cs" /> + <Compile Include="OAuth\ChannelElements\IOAuthDirectedMessage.cs" /> + <Compile Include="OAuth\Messages\UserAuthorizationResponse.cs" /> + <Compile Include="OAuth\Messages\UserAuthorizationRequest.cs" /> + <Compile Include="OAuth\Messages\UnauthorizedTokenResponse.cs" /> + <Compile Include="Messaging\Channel.cs" /> + <Compile Include="Messaging\HttpRequestInfo.cs" /> + <Compile Include="Messaging\IDirectedProtocolMessage.cs" /> + <Compile Include="Messaging\IMessageTypeProvider.cs" /> + <Compile Include="Messaging\ITamperResistantProtocolMessage.cs" /> + <Compile Include="Messaging\MessageSerializer.cs" /> + <Compile Include="Messaging\MessagingStrings.Designer.cs"> + <AutoGen>True</AutoGen> + <DesignTime>True</DesignTime> + <DependentUpon>MessagingStrings.resx</DependentUpon> + </Compile> + <Compile Include="Messaging\MessagingUtilities.cs" /> + <Compile Include="Messaging\Bindings\StandardExpirationBindingElement.cs" /> + <Compile Include="Messaging\Reflection\ValueMapping.cs" /> + <Compile Include="Messaging\Reflection\MessageDescription.cs" /> + <Compile Include="Messaging\Reflection\MessageDictionary.cs" /> + <Compile Include="Messaging\Reflection\MessagePart.cs" /> + <Compile Include="Messaging\UnprotectedMessageException.cs" /> + <Compile Include="OAuth\ChannelElements\OAuthChannel.cs" /> + <Compile Include="Messaging\Response.cs" /> + <Compile Include="Messaging\IProtocolMessage.cs" /> + <Compile Include="Logger.cs" /> + <Compile Include="Loggers\ILog.cs" /> + <Compile Include="Loggers\Log4NetLogger.cs" /> + <Compile Include="Loggers\NoOpLogger.cs" /> + <Compile Include="Loggers\TraceLogger.cs" /> + <Compile Include="Messaging\HttpDeliveryMethods.cs" /> + <Compile Include="Messaging\MessageTransport.cs" /> + <Compile Include="OAuth\ChannelElements\OAuthServiceProviderMessageTypeProvider.cs" /> + <Compile Include="Messaging\ProtocolException.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="OAuth\Messages\UnauthorizedTokenRequest.cs" /> + <Compile Include="OAuth\ChannelElements\RsaSha1SigningBindingElement.cs" /> + <Compile Include="OAuth\ChannelElements\StandardWebRequestHandler.cs" /> + <Compile Include="Messaging\MessageReceivingEndpoint.cs" /> + <Compile Include="Util.cs" /> + <Compile Include="OAuth\Protocol.cs" /> + <Compile Include="OAuth\ServiceProvider.cs" /> + <Compile Include="Strings.Designer.cs"> + <AutoGen>True</AutoGen> + <DesignTime>True</DesignTime> + <DependentUpon>Strings.resx</DependentUpon> + </Compile> + <Compile Include="UriUtil.cs" /> + </ItemGroup> + <ItemGroup> + <None Include="ClassDiagram.cd" /> + <None Include="OAuth\Messages\OAuth Messages.cd" /> + <None Include="Messaging\Bindings\Bindings.cd" /> + <None Include="Messaging\Exceptions.cd" /> + <None Include="Messaging\Messaging.cd" /> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="Messaging\MessagingStrings.resx"> + <Generator>ResXFileCodeGenerator</Generator> + <LastGenOutput>MessagingStrings.Designer.cs</LastGenOutput> + </EmbeddedResource> + <EmbeddedResource Include="Strings.resx"> + <Generator>ResXFileCodeGenerator</Generator> + <LastGenOutput>Strings.Designer.cs</LastGenOutput> + <SubType>Designer</SubType> + </EmbeddedResource> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <Import Project="..\..\tools\DotNetOpenAuth.Versioning.targets" /> +</Project> diff --git a/src/DotNetOAuth/GlobalSuppressions.cs b/src/DotNetOpenAuth/GlobalSuppressions.cs index ce8a2ef..487cc0c 100644 --- a/src/DotNetOAuth/GlobalSuppressions.cs +++ b/src/DotNetOpenAuth/GlobalSuppressions.cs @@ -1,15 +1,15 @@ -// <auto-generated/>
-// This file is used by Code Analysis to maintain SuppressMessage
-// attributes that are applied to this project.
-// Project-level suppressions either have no target or are given
-// a specific target and scoped to a namespace, type, member, etc.
-//
-// To add a suppression to this file, right-click the message in the
-// Error List, point to "Suppress Message(s)", and click
-// "In Project Suppression File".
-// You do not need to add suppressions to this file manually.
-
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.HmacSha1SigningBindingElement")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hmac", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.HmacSha1SigningBindingElement")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rsa", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.RsaSha1SigningBindingElement")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.RsaSha1SigningBindingElement")]
+// <auto-generated/> +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. +// +// To add a suppression to this file, right-click the message in the +// Error List, point to "Suppress Message(s)", and click +// "In Project Suppression File". +// You do not need to add suppressions to this file manually. + +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.HmacSha1SigningBindingElement")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hmac", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.HmacSha1SigningBindingElement")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Rsa", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.RsaSha1SigningBindingElement")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Scope = "type", Target = "DotNetOAuth.OAuth.ChannelElements.RsaSha1SigningBindingElement")] diff --git a/src/DotNetOAuth/Logger.cs b/src/DotNetOpenAuth/Logger.cs index 96357a0..86c7bfb 100644 --- a/src/DotNetOAuth/Logger.cs +++ b/src/DotNetOpenAuth/Logger.cs @@ -1,954 +1,954 @@ -//-----------------------------------------------------------------------
-// <copyright file="Logger.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth {
- using System;
- using System.Globalization;
- using DotNetOAuth.Loggers;
- using log4net.Core;
-
- /// <summary>
- /// A general logger for the entire DotNetOAuth library.
- /// </summary>
- /// <remarks>
- /// Because this logger is intended for use with non-localized strings, the
- /// overloads that take <see cref="CultureInfo"/> have been removed, and
- /// <see cref="CultureInfo.InvariantCulture"/> is used implicitly.
- /// </remarks>
- internal static class Logger {
- /// <summary>
- /// The <see cref="ILog"/> instance that is to be used
- /// by this static Logger for the duration of the appdomain.
- /// </summary>
- private static ILog facade = Create("DotNetOAuth");
-
- #region ILog Members
- //// Although this static class doesn't literally implement the ILog interface,
- //// we implement (mostly) all the same methods in a static way.
-
- /// <summary>
- /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Debug"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// <para>
- /// This function is intended to lessen the computational cost of
- /// disabled log debug statements.
- /// </para>
- /// <para> For some ILog interface <c>log</c>, when you write:</para>
- /// <code lang="C#">
- /// log.Debug("This is entry number: " + i );
- /// </code>
- /// <para>
- /// You incur the cost constructing the message, string construction and concatenation in
- /// this case, regardless of whether the message is logged or not.
- /// </para>
- /// <para>
- /// If you are worried about speed (who isn't), then you should write:
- /// </para>
- /// <code lang="C#">
- /// if (log.IsDebugEnabled)
- /// {
- /// log.Debug("This is entry number: " + i );
- /// }
- /// </code>
- /// <para>
- /// This way you will not incur the cost of parameter
- /// construction if debugging is disabled for <c>log</c>. On
- /// the other hand, if the <c>log</c> is debug enabled, you
- /// will incur the cost of evaluating whether the logger is debug
- /// enabled twice. Once in <see cref="IsDebugEnabled"/> and once in
- /// the <see cref="Debug(object)"/>. This is an insignificant overhead
- /// since evaluating a logger takes about 1% of the time it
- /// takes to actually log. This is the preferred style of logging.
- /// </para>
- /// <para>Alternatively if your logger is available statically then the is debug
- /// enabled state can be stored in a static variable like this:
- /// </para>
- /// <code lang="C#">
- /// private static readonly bool isDebugEnabled = log.IsDebugEnabled;
- /// </code>
- /// <para>
- /// Then when you come to log you can write:
- /// </para>
- /// <code lang="C#">
- /// if (isDebugEnabled)
- /// {
- /// log.Debug("This is entry number: " + i );
- /// }
- /// </code>
- /// <para>
- /// This way the debug enabled state is only queried once
- /// when the class is loaded. Using a <c>private static readonly</c>
- /// variable is the most efficient because it is a run time constant
- /// and can be heavily optimized by the JIT compiler.
- /// </para>
- /// <para>
- /// Of course if you use a static readonly variable to
- /// hold the enabled state of the logger then you cannot
- /// change the enabled state at runtime to vary the logging
- /// that is produced. You have to decide if you need absolute
- /// speed or runtime flexibility.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="DebugFormat(string, object[])"/>
- public static bool IsDebugEnabled {
- get { return facade.IsDebugEnabled; }
- }
-
- /// <summary>
- /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Info"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Info"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="InfoFormat(string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- public static bool IsInfoEnabled {
- get { return facade.IsInfoEnabled; }
- }
-
- /// <summary>
- /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Warn"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="WarnFormat(string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- public static bool IsWarnEnabled {
- get { return facade.IsWarnEnabled; }
- }
-
- /// <summary>
- /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Error"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Error"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="ErrorFormat(string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- public static bool IsErrorEnabled {
- get { return facade.IsErrorEnabled; }
- }
-
- /// <summary>
- /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Fatal"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="FatalFormat(string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- public static bool IsFatalEnabled {
- get { return facade.IsFatalEnabled; }
- }
-
- /// <overloads>Log a message object with the <see cref="Level.Debug"/> level.</overloads>
- /// <summary>
- /// Log a message object with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>DEBUG</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Debug"/> level. If this logger is
- /// <c>DEBUG</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of
- /// the additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Debug(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object,Exception)"/>
- /// <seealso cref="IsDebugEnabled"/>
- public static void Debug(object message) {
- facade.Debug(message);
- }
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Debug"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Debug(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- public static void Debug(object message, Exception exception) {
- facade.Debug(message, exception);
- }
-
- /// <overloads>Log a formatted string with the <see cref="Level.Debug"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- public static void DebugFormat(string format, params object[] args) {
- facade.DebugFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- public static void DebugFormat(string format, object arg0) {
- facade.DebugFormat(format, arg0);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- public static void DebugFormat(string format, object arg0, object arg1) {
- facade.DebugFormat(format, arg0, arg1);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- public static void DebugFormat(string format, object arg0, object arg1, object arg2) {
- facade.DebugFormat(format, arg0, arg1, arg2);
- }
-
- /*
- public static void DebugFormat(IFormatProvider provider, string format, params object[] args) {
- facade.DebugFormat(provider, format, args);
- }
- */
-
- /// <overloads>Log a message object with the <see cref="Level.Info"/> level.</overloads>
- /// <summary>
- /// Logs a message object with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>INFO</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Info"/> level. If this logger is
- /// <c>INFO</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Info(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <param name="message">The message object to log.</param>
- /// <seealso cref="Info(object,Exception)"/>
- /// <seealso cref="IsInfoEnabled"/>
- public static void Info(object message) {
- facade.Info(message);
- }
-
- /// <summary>
- /// Logs a message object with the <c>INFO</c> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Info(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- public static void Info(object message, Exception exception) {
- facade.Info(message, exception);
- }
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Info"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object,Exception)"/>
- /// <seealso cref="IsInfoEnabled"/>
- public static void InfoFormat(string format, params object[] args) {
- facade.InfoFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- public static void InfoFormat(string format, object arg0) {
- facade.InfoFormat(format, arg0);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- public static void InfoFormat(string format, object arg0, object arg1) {
- facade.InfoFormat(format, arg0, arg1);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- public static void InfoFormat(string format, object arg0, object arg1, object arg2) {
- facade.InfoFormat(format, arg0, arg1, arg2);
- }
-
- /*
- public static void InfoFormat(IFormatProvider provider, string format, params object[] args) {
- facade.InfoFormat(provider, format, args);
- }
- */
-
- /// <overloads>Log a message object with the <see cref="Level.Warn"/> level.</overloads>
- /// <summary>
- /// Log a message object with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>WARN</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Warn"/> level. If this logger is
- /// <c>WARN</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Warn(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <param name="message">The message object to log.</param>
- /// <seealso cref="Warn(object,Exception)"/>
- /// <seealso cref="IsWarnEnabled"/>
- public static void Warn(object message) {
- facade.Warn(message);
- }
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Warn"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Warn(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- public static void Warn(object message, Exception exception) {
- facade.Warn(message, exception);
- }
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Warn"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object,Exception)"/>
- /// <seealso cref="IsWarnEnabled"/>
- public static void WarnFormat(string format, params object[] args) {
- facade.WarnFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- public static void WarnFormat(string format, object arg0) {
- facade.WarnFormat(format, arg0);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- public static void WarnFormat(string format, object arg0, object arg1) {
- facade.WarnFormat(format, arg0, arg1);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- public static void WarnFormat(string format, object arg0, object arg1, object arg2) {
- facade.WarnFormat(format, arg0, arg1, arg2);
- }
-
- /*
- public static void WarnFormat(IFormatProvider provider, string format, params object[] args) {
- facade.WarnFormat(provider, format, args);
- }
- */
-
- /// <overloads>Log a message object with the <see cref="Level.Error"/> level.</overloads>
- /// <summary>
- /// Logs a message object with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>ERROR</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Error"/> level. If this logger is
- /// <c>ERROR</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Error(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object,Exception)"/>
- /// <seealso cref="IsErrorEnabled"/>
- public static void Error(object message) {
- facade.Error(message);
- }
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Error"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Error(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- public static void Error(object message, Exception exception) {
- facade.Error(message, exception);
- }
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Error"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object,Exception)"/>
- /// <seealso cref="IsErrorEnabled"/>
- public static void ErrorFormat(string format, params object[] args) {
- facade.ErrorFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- public static void ErrorFormat(string format, object arg0) {
- facade.ErrorFormat(format, arg0);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- public static void ErrorFormat(string format, object arg0, object arg1) {
- facade.ErrorFormat(format, arg0, arg1);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- public static void ErrorFormat(string format, object arg0, object arg1, object arg2) {
- facade.ErrorFormat(format, arg0, arg1, arg2);
- }
-
- /*
- public static void ErrorFormat(IFormatProvider provider, string format, params object[] args) {
- facade.ErrorFormat(provider, format, args);
- }
- */
-
- /// <overloads>Log a message object with the <see cref="Level.Fatal"/> level.</overloads>
- /// <summary>
- /// Log a message object with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>FATAL</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Fatal"/> level. If this logger is
- /// <c>FATAL</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Fatal(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <param name="message">The message object to log.</param>
- /// <seealso cref="Fatal(object,Exception)"/>
- /// <seealso cref="IsFatalEnabled"/>
- public static void Fatal(object message) {
- facade.Fatal(message);
- }
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Fatal"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Fatal(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- public static void Fatal(object message, Exception exception) {
- facade.Fatal(message, exception);
- }
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Fatal"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object,Exception)"/>
- /// <seealso cref="IsFatalEnabled"/>
- public static void FatalFormat(string format, params object[] args) {
- facade.FatalFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- public static void FatalFormat(string format, object arg0) {
- facade.FatalFormat(format, arg0);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- public static void FatalFormat(string format, object arg0, object arg1) {
- facade.FatalFormat(format, arg0, arg1);
- }
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- public static void FatalFormat(string format, object arg0, object arg1, object arg2) {
- facade.FatalFormat(format, arg0, arg1, arg2);
- }
-
- /*
- public static void FatalFormat(IFormatProvider provider, string format, params object[] args) {
- facade.FatalFormat(provider, format, args);
- }
- */
-
- #endregion
-
- /// <summary>
- /// Creates an additional logger on demand for a subsection of the application.
- /// </summary>
- /// <param name="name">A name that will be included in the log file.</param>
- /// <returns>The <see cref="ILog"/> instance created with the given name.</returns>
- internal static ILog Create(string name) {
- if (String.IsNullOrEmpty(name)) {
- throw new ArgumentNullException("name");
- }
-
- return InitializeFacade(name);
- }
-
- /// <summary>
- /// Creates an additional logger on demand for a subsection of the application.
- /// </summary>
- /// <param name="type">A type whose full name that will be included in the log file.</param>
- /// <returns>The <see cref="ILog"/> instance created with the given type name.</returns>
- internal static ILog Create(Type type) {
- if (type == null) {
- throw new ArgumentNullException("type");
- }
-
- return Create(type.FullName);
- }
-
- /// <summary>
- /// Discovers the presence of Log4net.dll and other logging mechanisms
- /// and returns the best available logger.
- /// </summary>
- /// <param name="name">The name of the log to initialize.</param>
- /// <returns>The <see cref="ILog"/> instance of the logger to use.</returns>
- private static ILog InitializeFacade(string name) {
- ILog result = Log4NetLogger.Initialize(name) ?? TraceLogger.Initialize(name) ?? NoOpLogger.Initialize();
- result.Info(Util.LibraryVersion);
- return result;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="Logger.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth { + using System; + using System.Globalization; + using DotNetOpenAuth.Loggers; + using log4net.Core; + + /// <summary> + /// A general logger for the entire DotNetOpenAuth library. + /// </summary> + /// <remarks> + /// Because this logger is intended for use with non-localized strings, the + /// overloads that take <see cref="CultureInfo"/> have been removed, and + /// <see cref="CultureInfo.InvariantCulture"/> is used implicitly. + /// </remarks> + internal static class Logger { + /// <summary> + /// The <see cref="ILog"/> instance that is to be used + /// by this static Logger for the duration of the appdomain. + /// </summary> + private static ILog facade = Create("DotNetOpenAuth"); + + #region ILog Members + //// Although this static class doesn't literally implement the ILog interface, + //// we implement (mostly) all the same methods in a static way. + + /// <summary> + /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Debug"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Debug"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// <para> + /// This function is intended to lessen the computational cost of + /// disabled log debug statements. + /// </para> + /// <para> For some ILog interface <c>log</c>, when you write:</para> + /// <code lang="C#"> + /// log.Debug("This is entry number: " + i ); + /// </code> + /// <para> + /// You incur the cost constructing the message, string construction and concatenation in + /// this case, regardless of whether the message is logged or not. + /// </para> + /// <para> + /// If you are worried about speed (who isn't), then you should write: + /// </para> + /// <code lang="C#"> + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// </code> + /// <para> + /// This way you will not incur the cost of parameter + /// construction if debugging is disabled for <c>log</c>. On + /// the other hand, if the <c>log</c> is debug enabled, you + /// will incur the cost of evaluating whether the logger is debug + /// enabled twice. Once in <see cref="IsDebugEnabled"/> and once in + /// the <see cref="Debug(object)"/>. This is an insignificant overhead + /// since evaluating a logger takes about 1% of the time it + /// takes to actually log. This is the preferred style of logging. + /// </para> + /// <para>Alternatively if your logger is available statically then the is debug + /// enabled state can be stored in a static variable like this: + /// </para> + /// <code lang="C#"> + /// private static readonly bool isDebugEnabled = log.IsDebugEnabled; + /// </code> + /// <para> + /// Then when you come to log you can write: + /// </para> + /// <code lang="C#"> + /// if (isDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// </code> + /// <para> + /// This way the debug enabled state is only queried once + /// when the class is loaded. Using a <c>private static readonly</c> + /// variable is the most efficient because it is a run time constant + /// and can be heavily optimized by the JIT compiler. + /// </para> + /// <para> + /// Of course if you use a static readonly variable to + /// hold the enabled state of the logger then you cannot + /// change the enabled state at runtime to vary the logging + /// that is produced. You have to decide if you need absolute + /// speed or runtime flexibility. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="DebugFormat(string, object[])"/> + public static bool IsDebugEnabled { + get { return facade.IsDebugEnabled; } + } + + /// <summary> + /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Info"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Info"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="InfoFormat(string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + public static bool IsInfoEnabled { + get { return facade.IsInfoEnabled; } + } + + /// <summary> + /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Warn"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Warn"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="WarnFormat(string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + public static bool IsWarnEnabled { + get { return facade.IsWarnEnabled; } + } + + /// <summary> + /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Error"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Error"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="ErrorFormat(string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + public static bool IsErrorEnabled { + get { return facade.IsErrorEnabled; } + } + + /// <summary> + /// Gets a value indicating whether this logger is enabled for the <see cref="Level.Fatal"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Fatal"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="FatalFormat(string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + public static bool IsFatalEnabled { + get { return facade.IsFatalEnabled; } + } + + /// <overloads>Log a message object with the <see cref="Level.Debug"/> level.</overloads> + /// <summary> + /// Log a message object with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>DEBUG</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Debug"/> level. If this logger is + /// <c>DEBUG</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Debug(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object,Exception)"/> + /// <seealso cref="IsDebugEnabled"/> + public static void Debug(object message) { + facade.Debug(message); + } + + /// <summary> + /// Log a message object with the <see cref="Level.Debug"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Debug(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + public static void Debug(object message, Exception exception) { + facade.Debug(message, exception); + } + + /// <overloads>Log a formatted string with the <see cref="Level.Debug"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + public static void DebugFormat(string format, params object[] args) { + facade.DebugFormat(CultureInfo.InvariantCulture, format, args); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + public static void DebugFormat(string format, object arg0) { + facade.DebugFormat(format, arg0); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + public static void DebugFormat(string format, object arg0, object arg1) { + facade.DebugFormat(format, arg0, arg1); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + public static void DebugFormat(string format, object arg0, object arg1, object arg2) { + facade.DebugFormat(format, arg0, arg1, arg2); + } + + /* + public static void DebugFormat(IFormatProvider provider, string format, params object[] args) { + facade.DebugFormat(provider, format, args); + } + */ + + /// <overloads>Log a message object with the <see cref="Level.Info"/> level.</overloads> + /// <summary> + /// Logs a message object with the <see cref="Level.Info"/> level. + /// </summary> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>INFO</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Info"/> level. If this logger is + /// <c>INFO</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Info(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <param name="message">The message object to log.</param> + /// <seealso cref="Info(object,Exception)"/> + /// <seealso cref="IsInfoEnabled"/> + public static void Info(object message) { + facade.Info(message); + } + + /// <summary> + /// Logs a message object with the <c>INFO</c> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Info(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + public static void Info(object message, Exception exception) { + facade.Info(message, exception); + } + + /// <overloads>Log a formatted message string with the <see cref="Level.Info"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object,Exception)"/> + /// <seealso cref="IsInfoEnabled"/> + public static void InfoFormat(string format, params object[] args) { + facade.InfoFormat(CultureInfo.InvariantCulture, format, args); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + public static void InfoFormat(string format, object arg0) { + facade.InfoFormat(format, arg0); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + public static void InfoFormat(string format, object arg0, object arg1) { + facade.InfoFormat(format, arg0, arg1); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + public static void InfoFormat(string format, object arg0, object arg1, object arg2) { + facade.InfoFormat(format, arg0, arg1, arg2); + } + + /* + public static void InfoFormat(IFormatProvider provider, string format, params object[] args) { + facade.InfoFormat(provider, format, args); + } + */ + + /// <overloads>Log a message object with the <see cref="Level.Warn"/> level.</overloads> + /// <summary> + /// Log a message object with the <see cref="Level.Warn"/> level. + /// </summary> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>WARN</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Warn"/> level. If this logger is + /// <c>WARN</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Warn(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <param name="message">The message object to log.</param> + /// <seealso cref="Warn(object,Exception)"/> + /// <seealso cref="IsWarnEnabled"/> + public static void Warn(object message) { + facade.Warn(message); + } + + /// <summary> + /// Log a message object with the <see cref="Level.Warn"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Warn(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + public static void Warn(object message, Exception exception) { + facade.Warn(message, exception); + } + + /// <overloads>Log a formatted message string with the <see cref="Level.Warn"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object,Exception)"/> + /// <seealso cref="IsWarnEnabled"/> + public static void WarnFormat(string format, params object[] args) { + facade.WarnFormat(CultureInfo.InvariantCulture, format, args); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + public static void WarnFormat(string format, object arg0) { + facade.WarnFormat(format, arg0); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + public static void WarnFormat(string format, object arg0, object arg1) { + facade.WarnFormat(format, arg0, arg1); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + public static void WarnFormat(string format, object arg0, object arg1, object arg2) { + facade.WarnFormat(format, arg0, arg1, arg2); + } + + /* + public static void WarnFormat(IFormatProvider provider, string format, params object[] args) { + facade.WarnFormat(provider, format, args); + } + */ + + /// <overloads>Log a message object with the <see cref="Level.Error"/> level.</overloads> + /// <summary> + /// Logs a message object with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>ERROR</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Error"/> level. If this logger is + /// <c>ERROR</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Error(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object,Exception)"/> + /// <seealso cref="IsErrorEnabled"/> + public static void Error(object message) { + facade.Error(message); + } + + /// <summary> + /// Log a message object with the <see cref="Level.Error"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Error(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + public static void Error(object message, Exception exception) { + facade.Error(message, exception); + } + + /// <overloads>Log a formatted message string with the <see cref="Level.Error"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object,Exception)"/> + /// <seealso cref="IsErrorEnabled"/> + public static void ErrorFormat(string format, params object[] args) { + facade.ErrorFormat(CultureInfo.InvariantCulture, format, args); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + public static void ErrorFormat(string format, object arg0) { + facade.ErrorFormat(format, arg0); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + public static void ErrorFormat(string format, object arg0, object arg1) { + facade.ErrorFormat(format, arg0, arg1); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + public static void ErrorFormat(string format, object arg0, object arg1, object arg2) { + facade.ErrorFormat(format, arg0, arg1, arg2); + } + + /* + public static void ErrorFormat(IFormatProvider provider, string format, params object[] args) { + facade.ErrorFormat(provider, format, args); + } + */ + + /// <overloads>Log a message object with the <see cref="Level.Fatal"/> level.</overloads> + /// <summary> + /// Log a message object with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>FATAL</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Fatal"/> level. If this logger is + /// <c>FATAL</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Fatal(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <param name="message">The message object to log.</param> + /// <seealso cref="Fatal(object,Exception)"/> + /// <seealso cref="IsFatalEnabled"/> + public static void Fatal(object message) { + facade.Fatal(message); + } + + /// <summary> + /// Log a message object with the <see cref="Level.Fatal"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Fatal(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + public static void Fatal(object message, Exception exception) { + facade.Fatal(message, exception); + } + + /// <overloads>Log a formatted message string with the <see cref="Level.Fatal"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object,Exception)"/> + /// <seealso cref="IsFatalEnabled"/> + public static void FatalFormat(string format, params object[] args) { + facade.FatalFormat(CultureInfo.InvariantCulture, format, args); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + public static void FatalFormat(string format, object arg0) { + facade.FatalFormat(format, arg0); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + public static void FatalFormat(string format, object arg0, object arg1) { + facade.FatalFormat(format, arg0, arg1); + } + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + public static void FatalFormat(string format, object arg0, object arg1, object arg2) { + facade.FatalFormat(format, arg0, arg1, arg2); + } + + /* + public static void FatalFormat(IFormatProvider provider, string format, params object[] args) { + facade.FatalFormat(provider, format, args); + } + */ + + #endregion + + /// <summary> + /// Creates an additional logger on demand for a subsection of the application. + /// </summary> + /// <param name="name">A name that will be included in the log file.</param> + /// <returns>The <see cref="ILog"/> instance created with the given name.</returns> + internal static ILog Create(string name) { + if (String.IsNullOrEmpty(name)) { + throw new ArgumentNullException("name"); + } + + return InitializeFacade(name); + } + + /// <summary> + /// Creates an additional logger on demand for a subsection of the application. + /// </summary> + /// <param name="type">A type whose full name that will be included in the log file.</param> + /// <returns>The <see cref="ILog"/> instance created with the given type name.</returns> + internal static ILog Create(Type type) { + if (type == null) { + throw new ArgumentNullException("type"); + } + + return Create(type.FullName); + } + + /// <summary> + /// Discovers the presence of Log4net.dll and other logging mechanisms + /// and returns the best available logger. + /// </summary> + /// <param name="name">The name of the log to initialize.</param> + /// <returns>The <see cref="ILog"/> instance of the logger to use.</returns> + private static ILog InitializeFacade(string name) { + ILog result = Log4NetLogger.Initialize(name) ?? TraceLogger.Initialize(name) ?? NoOpLogger.Initialize(); + result.Info(Util.LibraryVersion); + return result; + } + } +} diff --git a/src/DotNetOAuth/Loggers/ILog.cs b/src/DotNetOpenAuth/Loggers/ILog.cs index 51e5570..8a285a7 100644 --- a/src/DotNetOAuth/Loggers/ILog.cs +++ b/src/DotNetOpenAuth/Loggers/ILog.cs @@ -1,966 +1,966 @@ -// <auto-generated />
-
-#region Copyright & License
-//
-// Copyright 2001-2006 The Apache Software Foundation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-#endregion
-
-// This interface is designed to look like log4net's ILog interface.
-// We have this as a facade in front of it to avoid crashing if the
-// hosting web site chooses not to deploy log4net.dll along with
-// dotnetopenid.dll.
-
-namespace DotNetOAuth.Loggers
-{
- using System;
- using System.Reflection;
- using log4net;
- using log4net.Core;
-
- /// <summary>
- /// The ILog interface is use by application to log messages into
- /// the log4net framework.
- /// </summary>
- /// <remarks>
- /// <para>
- /// Use the <see cref="LogManager"/> to obtain logger instances
- /// that implement this interface. The <see cref="LogManager.GetLogger(Assembly,Type)"/>
- /// static method is used to get logger instances.
- /// </para>
- /// <para>
- /// This class contains methods for logging at different levels and also
- /// has properties for determining if those logging levels are
- /// enabled in the current configuration.
- /// </para>
- /// <para>
- /// This interface can be implemented in different ways. This documentation
- /// specifies reasonable behavior that a caller can expect from the actual
- /// implementation, however different implementations reserve the right to
- /// do things differently.
- /// </para>
- /// </remarks>
- /// <example>Simple example of logging messages
- /// <code lang="C#">
- /// ILog log = LogManager.GetLogger("application-log");
- ///
- /// log.Info("Application Start");
- /// log.Debug("This is a debug message");
- ///
- /// if (log.IsDebugEnabled)
- /// {
- /// log.Debug("This is another debug message");
- /// }
- /// </code>
- /// </example>
- /// <seealso cref="LogManager"/>
- /// <seealso cref="LogManager.GetLogger(Assembly, Type)"/>
- /// <author>Nicko Cadell</author>
- /// <author>Gert Driesen</author>
- interface ILog
- {
- /// <overloads>Log a message object with the <see cref="Level.Debug"/> level.</overloads>
- /// <summary>
- /// Log a message object with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>DEBUG</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Debug"/> level. If this logger is
- /// <c>DEBUG</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of
- /// the additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Debug(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object,Exception)"/>
- /// <seealso cref="IsDebugEnabled"/>
- void Debug(object message);
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Debug"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Debug(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- void Debug(object message, Exception exception);
-
- /// <overloads>Log a formatted string with the <see cref="Level.Debug"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- void DebugFormat(string format, params object[] args);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- void DebugFormat(string format, object arg0);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- void DebugFormat(string format, object arg0, object arg1);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- void DebugFormat(string format, object arg0, object arg1, object arg2);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="IsDebugEnabled"/>
- void DebugFormat(IFormatProvider provider, string format, params object[] args);
-
- /// <overloads>Log a message object with the <see cref="Level.Info"/> level.</overloads>
- /// <summary>
- /// Logs a message object with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>INFO</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Info"/> level. If this logger is
- /// <c>INFO</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Info(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <param name="message">The message object to log.</param>
- /// <seealso cref="Info(object,Exception)"/>
- /// <seealso cref="IsInfoEnabled"/>
- void Info(object message);
-
- /// <summary>
- /// Logs a message object with the <c>INFO</c> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Info(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- void Info(object message, Exception exception);
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Info"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object,Exception)"/>
- /// <seealso cref="IsInfoEnabled"/>
- void InfoFormat(string format, params object[] args);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- void InfoFormat(string format, object arg0);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- void InfoFormat(string format, object arg0, object arg1);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="IsInfoEnabled"/>
- void InfoFormat(string format, object arg0, object arg1, object arg2);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Info"/> level.
- /// </summary>
- /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Info(object,Exception)"/>
- /// <seealso cref="IsInfoEnabled"/>
- void InfoFormat(IFormatProvider provider, string format, params object[] args);
-
- /// <overloads>Log a message object with the <see cref="Level.Warn"/> level.</overloads>
- /// <summary>
- /// Log a message object with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>WARN</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Warn"/> level. If this logger is
- /// <c>WARN</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Warn(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <param name="message">The message object to log.</param>
- /// <seealso cref="Warn(object,Exception)"/>
- /// <seealso cref="IsWarnEnabled"/>
- void Warn(object message);
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Warn"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Warn(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- void Warn(object message, Exception exception);
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Warn"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object,Exception)"/>
- /// <seealso cref="IsWarnEnabled"/>
- void WarnFormat(string format, params object[] args);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- void WarnFormat(string format, object arg0);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- void WarnFormat(string format, object arg0, object arg1);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="IsWarnEnabled"/>
- void WarnFormat(string format, object arg0, object arg1, object arg2);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Warn(object,Exception)"/>
- /// <seealso cref="IsWarnEnabled"/>
- void WarnFormat(IFormatProvider provider, string format, params object[] args);
-
- /// <overloads>Log a message object with the <see cref="Level.Error"/> level.</overloads>
- /// <summary>
- /// Logs a message object with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>ERROR</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Error"/> level. If this logger is
- /// <c>ERROR</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Error(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object,Exception)"/>
- /// <seealso cref="IsErrorEnabled"/>
- void Error(object message);
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Error"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Error(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- void Error(object message, Exception exception);
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Error"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object,Exception)"/>
- /// <seealso cref="IsErrorEnabled"/>
- void ErrorFormat(string format, params object[] args);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- void ErrorFormat(string format, object arg0);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- void ErrorFormat(string format, object arg0, object arg1);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="IsErrorEnabled"/>
- void ErrorFormat(string format, object arg0, object arg1, object arg2);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Error"/> level.
- /// </summary>
- /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Error(object,Exception)"/>
- /// <seealso cref="IsErrorEnabled"/>
- void ErrorFormat(IFormatProvider provider, string format, params object[] args);
-
- /// <overloads>Log a message object with the <see cref="Level.Fatal"/> level.</overloads>
- /// <summary>
- /// Log a message object with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <remarks>
- /// <para>
- /// This method first checks if this logger is <c>FATAL</c>
- /// enabled by comparing the level of this logger with the
- /// <see cref="Level.Fatal"/> level. If this logger is
- /// <c>FATAL</c> enabled, then it converts the message object
- /// (passed as parameter) to a string by invoking the appropriate
- /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then
- /// proceeds to call all the registered appenders in this logger
- /// and also higher in the hierarchy depending on the value of the
- /// additivity flag.
- /// </para>
- /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/>
- /// to this method will print the name of the <see cref="Exception"/>
- /// but no stack trace. To print a stack trace use the
- /// <see cref="Fatal(object,Exception)"/> form instead.
- /// </para>
- /// </remarks>
- /// <param name="message">The message object to log.</param>
- /// <seealso cref="Fatal(object,Exception)"/>
- /// <seealso cref="IsFatalEnabled"/>
- void Fatal(object message);
-
- /// <summary>
- /// Log a message object with the <see cref="Level.Fatal"/> level including
- /// the stack trace of the <see cref="Exception"/> passed
- /// as a parameter.
- /// </summary>
- /// <param name="message">The message object to log.</param>
- /// <param name="exception">The exception to log, including its stack trace.</param>
- /// <remarks>
- /// <para>
- /// See the <see cref="Fatal(object)"/> form for more detailed information.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- void Fatal(object message, Exception exception);
-
- /// <overloads>Log a formatted message string with the <see cref="Level.Fatal"/> level.</overloads>
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object,Exception)"/>
- /// <seealso cref="IsFatalEnabled"/>
- void FatalFormat(string format, params object[] args);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- void FatalFormat(string format, object arg0);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- void FatalFormat(string format, object arg0, object arg1);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="arg0">An Object to format</param>
- /// <param name="arg1">An Object to format</param>
- /// <param name="arg2">An Object to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="IsFatalEnabled"/>
- void FatalFormat(string format, object arg0, object arg1, object arg2);
-
- /// <summary>
- /// Logs a formatted message string with the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param>
- /// <param name="format">A String containing zero or more format items</param>
- /// <param name="args">An Object array containing zero or more objects to format</param>
- /// <remarks>
- /// <para>
- /// The message is formatted using the <c>String.Format</c> method. See
- /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior
- /// of the formatting.
- /// </para>
- /// <para>
- /// This method does not take an <see cref="Exception"/> object to include in the
- /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object)"/>
- /// methods instead.
- /// </para>
- /// </remarks>
- /// <seealso cref="Fatal(object,Exception)"/>
- /// <seealso cref="IsFatalEnabled"/>
- void FatalFormat(IFormatProvider provider, string format, params object[] args);
-
- /// <summary>
- /// Checks if this logger is enabled for the <see cref="Level.Debug"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Debug"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// <para>
- /// This function is intended to lessen the computational cost of
- /// disabled log debug statements.
- /// </para>
- /// <para> For some ILog interface <c>log</c>, when you write:</para>
- /// <code lang="C#">
- /// log.Debug("This is entry number: " + i );
- /// </code>
- /// <para>
- /// You incur the cost constructing the message, string construction and concatenation in
- /// this case, regardless of whether the message is logged or not.
- /// </para>
- /// <para>
- /// If you are worried about speed (who isn't), then you should write:
- /// </para>
- /// <code lang="C#">
- /// if (log.IsDebugEnabled)
- /// {
- /// log.Debug("This is entry number: " + i );
- /// }
- /// </code>
- /// <para>
- /// This way you will not incur the cost of parameter
- /// construction if debugging is disabled for <c>log</c>. On
- /// the other hand, if the <c>log</c> is debug enabled, you
- /// will incur the cost of evaluating whether the logger is debug
- /// enabled twice. Once in <see cref="IsDebugEnabled"/> and once in
- /// the <see cref="Debug(object)"/>. This is an insignificant overhead
- /// since evaluating a logger takes about 1% of the time it
- /// takes to actually log. This is the preferred style of logging.
- /// </para>
- /// <para>Alternatively if your logger is available statically then the is debug
- /// enabled state can be stored in a static variable like this:
- /// </para>
- /// <code lang="C#">
- /// private static readonly bool isDebugEnabled = log.IsDebugEnabled;
- /// </code>
- /// <para>
- /// Then when you come to log you can write:
- /// </para>
- /// <code lang="C#">
- /// if (isDebugEnabled)
- /// {
- /// log.Debug("This is entry number: " + i );
- /// }
- /// </code>
- /// <para>
- /// This way the debug enabled state is only queried once
- /// when the class is loaded. Using a <c>private static readonly</c>
- /// variable is the most efficient because it is a run time constant
- /// and can be heavily optimized by the JIT compiler.
- /// </para>
- /// <para>
- /// Of course if you use a static readonly variable to
- /// hold the enabled state of the logger then you cannot
- /// change the enabled state at runtime to vary the logging
- /// that is produced. You have to decide if you need absolute
- /// speed or runtime flexibility.
- /// </para>
- /// </remarks>
- /// <seealso cref="Debug(object)"/>
- /// <seealso cref="DebugFormat(IFormatProvider, string, object[])"/>
- bool IsDebugEnabled { get; }
-
- /// <summary>
- /// Checks if this logger is enabled for the <see cref="Level.Info"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Info"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Info(object)"/>
- /// <seealso cref="InfoFormat(IFormatProvider, string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- bool IsInfoEnabled { get; }
-
- /// <summary>
- /// Checks if this logger is enabled for the <see cref="Level.Warn"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Warn"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Warn(object)"/>
- /// <seealso cref="WarnFormat(IFormatProvider, string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- bool IsWarnEnabled { get; }
-
- /// <summary>
- /// Checks if this logger is enabled for the <see cref="Level.Error"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Error"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Error(object)"/>
- /// <seealso cref="ErrorFormat(IFormatProvider, string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- bool IsErrorEnabled { get; }
-
- /// <summary>
- /// Checks if this logger is enabled for the <see cref="Level.Fatal"/> level.
- /// </summary>
- /// <value>
- /// <c>true</c> if this logger is enabled for <see cref="Level.Fatal"/> events, <c>false</c> otherwise.
- /// </value>
- /// <remarks>
- /// For more information see <see cref="ILog.IsDebugEnabled"/>.
- /// </remarks>
- /// <seealso cref="Fatal(object)"/>
- /// <seealso cref="FatalFormat(IFormatProvider, string, object[])"/>
- /// <seealso cref="ILog.IsDebugEnabled"/>
- bool IsFatalEnabled { get; }
- }
-}
+// <auto-generated /> + +#region Copyright & License +// +// Copyright 2001-2006 The Apache Software Foundation +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion + +// This interface is designed to look like log4net's ILog interface. +// We have this as a facade in front of it to avoid crashing if the +// hosting web site chooses not to deploy log4net.dll along with +// dotnetopenid.dll. + +namespace DotNetOpenAuth.Loggers +{ + using System; + using System.Reflection; + using log4net; + using log4net.Core; + + /// <summary> + /// The ILog interface is use by application to log messages into + /// the log4net framework. + /// </summary> + /// <remarks> + /// <para> + /// Use the <see cref="LogManager"/> to obtain logger instances + /// that implement this interface. The <see cref="LogManager.GetLogger(Assembly,Type)"/> + /// static method is used to get logger instances. + /// </para> + /// <para> + /// This class contains methods for logging at different levels and also + /// has properties for determining if those logging levels are + /// enabled in the current configuration. + /// </para> + /// <para> + /// This interface can be implemented in different ways. This documentation + /// specifies reasonable behavior that a caller can expect from the actual + /// implementation, however different implementations reserve the right to + /// do things differently. + /// </para> + /// </remarks> + /// <example>Simple example of logging messages + /// <code lang="C#"> + /// ILog log = LogManager.GetLogger("application-log"); + /// + /// log.Info("Application Start"); + /// log.Debug("This is a debug message"); + /// + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is another debug message"); + /// } + /// </code> + /// </example> + /// <seealso cref="LogManager"/> + /// <seealso cref="LogManager.GetLogger(Assembly, Type)"/> + /// <author>Nicko Cadell</author> + /// <author>Gert Driesen</author> + interface ILog + { + /// <overloads>Log a message object with the <see cref="Level.Debug"/> level.</overloads> + /// <summary> + /// Log a message object with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>DEBUG</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Debug"/> level. If this logger is + /// <c>DEBUG</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of + /// the additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Debug(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object,Exception)"/> + /// <seealso cref="IsDebugEnabled"/> + void Debug(object message); + + /// <summary> + /// Log a message object with the <see cref="Level.Debug"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Debug(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + void Debug(object message, Exception exception); + + /// <overloads>Log a formatted string with the <see cref="Level.Debug"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + void DebugFormat(string format, params object[] args); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + void DebugFormat(string format, object arg0); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + void DebugFormat(string format, object arg0, object arg1); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + void DebugFormat(string format, object arg0, object arg1, object arg2); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Debug"/> level. + /// </summary> + /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Debug(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="IsDebugEnabled"/> + void DebugFormat(IFormatProvider provider, string format, params object[] args); + + /// <overloads>Log a message object with the <see cref="Level.Info"/> level.</overloads> + /// <summary> + /// Logs a message object with the <see cref="Level.Info"/> level. + /// </summary> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>INFO</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Info"/> level. If this logger is + /// <c>INFO</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Info(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <param name="message">The message object to log.</param> + /// <seealso cref="Info(object,Exception)"/> + /// <seealso cref="IsInfoEnabled"/> + void Info(object message); + + /// <summary> + /// Logs a message object with the <c>INFO</c> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Info(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + void Info(object message, Exception exception); + + /// <overloads>Log a formatted message string with the <see cref="Level.Info"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object,Exception)"/> + /// <seealso cref="IsInfoEnabled"/> + void InfoFormat(string format, params object[] args); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + void InfoFormat(string format, object arg0); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + void InfoFormat(string format, object arg0, object arg1); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="IsInfoEnabled"/> + void InfoFormat(string format, object arg0, object arg1, object arg2); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Info"/> level. + /// </summary> + /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Info(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Info(object,Exception)"/> + /// <seealso cref="IsInfoEnabled"/> + void InfoFormat(IFormatProvider provider, string format, params object[] args); + + /// <overloads>Log a message object with the <see cref="Level.Warn"/> level.</overloads> + /// <summary> + /// Log a message object with the <see cref="Level.Warn"/> level. + /// </summary> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>WARN</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Warn"/> level. If this logger is + /// <c>WARN</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Warn(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <param name="message">The message object to log.</param> + /// <seealso cref="Warn(object,Exception)"/> + /// <seealso cref="IsWarnEnabled"/> + void Warn(object message); + + /// <summary> + /// Log a message object with the <see cref="Level.Warn"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Warn(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + void Warn(object message, Exception exception); + + /// <overloads>Log a formatted message string with the <see cref="Level.Warn"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object,Exception)"/> + /// <seealso cref="IsWarnEnabled"/> + void WarnFormat(string format, params object[] args); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + void WarnFormat(string format, object arg0); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + void WarnFormat(string format, object arg0, object arg1); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="IsWarnEnabled"/> + void WarnFormat(string format, object arg0, object arg1, object arg2); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Warn"/> level. + /// </summary> + /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Warn(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Warn(object,Exception)"/> + /// <seealso cref="IsWarnEnabled"/> + void WarnFormat(IFormatProvider provider, string format, params object[] args); + + /// <overloads>Log a message object with the <see cref="Level.Error"/> level.</overloads> + /// <summary> + /// Logs a message object with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>ERROR</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Error"/> level. If this logger is + /// <c>ERROR</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Error(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object,Exception)"/> + /// <seealso cref="IsErrorEnabled"/> + void Error(object message); + + /// <summary> + /// Log a message object with the <see cref="Level.Error"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Error(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + void Error(object message, Exception exception); + + /// <overloads>Log a formatted message string with the <see cref="Level.Error"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object,Exception)"/> + /// <seealso cref="IsErrorEnabled"/> + void ErrorFormat(string format, params object[] args); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + void ErrorFormat(string format, object arg0); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + void ErrorFormat(string format, object arg0, object arg1); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="IsErrorEnabled"/> + void ErrorFormat(string format, object arg0, object arg1, object arg2); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Error"/> level. + /// </summary> + /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Error(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Error(object,Exception)"/> + /// <seealso cref="IsErrorEnabled"/> + void ErrorFormat(IFormatProvider provider, string format, params object[] args); + + /// <overloads>Log a message object with the <see cref="Level.Fatal"/> level.</overloads> + /// <summary> + /// Log a message object with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <remarks> + /// <para> + /// This method first checks if this logger is <c>FATAL</c> + /// enabled by comparing the level of this logger with the + /// <see cref="Level.Fatal"/> level. If this logger is + /// <c>FATAL</c> enabled, then it converts the message object + /// (passed as parameter) to a string by invoking the appropriate + /// <see cref="log4net.ObjectRenderer.IObjectRenderer"/>. It then + /// proceeds to call all the registered appenders in this logger + /// and also higher in the hierarchy depending on the value of the + /// additivity flag. + /// </para> + /// <para><b>WARNING</b> Note that passing an <see cref="Exception"/> + /// to this method will print the name of the <see cref="Exception"/> + /// but no stack trace. To print a stack trace use the + /// <see cref="Fatal(object,Exception)"/> form instead. + /// </para> + /// </remarks> + /// <param name="message">The message object to log.</param> + /// <seealso cref="Fatal(object,Exception)"/> + /// <seealso cref="IsFatalEnabled"/> + void Fatal(object message); + + /// <summary> + /// Log a message object with the <see cref="Level.Fatal"/> level including + /// the stack trace of the <see cref="Exception"/> passed + /// as a parameter. + /// </summary> + /// <param name="message">The message object to log.</param> + /// <param name="exception">The exception to log, including its stack trace.</param> + /// <remarks> + /// <para> + /// See the <see cref="Fatal(object)"/> form for more detailed information. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + void Fatal(object message, Exception exception); + + /// <overloads>Log a formatted message string with the <see cref="Level.Fatal"/> level.</overloads> + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object,Exception)"/> + /// <seealso cref="IsFatalEnabled"/> + void FatalFormat(string format, params object[] args); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + void FatalFormat(string format, object arg0); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + void FatalFormat(string format, object arg0, object arg1); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="arg0">An Object to format</param> + /// <param name="arg1">An Object to format</param> + /// <param name="arg2">An Object to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object,Exception)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="IsFatalEnabled"/> + void FatalFormat(string format, object arg0, object arg1, object arg2); + + /// <summary> + /// Logs a formatted message string with the <see cref="Level.Fatal"/> level. + /// </summary> + /// <param name="provider">An <see cref="IFormatProvider"/> that supplies culture-specific formatting information</param> + /// <param name="format">A String containing zero or more format items</param> + /// <param name="args">An Object array containing zero or more objects to format</param> + /// <remarks> + /// <para> + /// The message is formatted using the <c>String.Format</c> method. See + /// <see cref="String.Format(string, object[])"/> for details of the syntax of the format string and the behavior + /// of the formatting. + /// </para> + /// <para> + /// This method does not take an <see cref="Exception"/> object to include in the + /// log event. To pass an <see cref="Exception"/> use one of the <see cref="Fatal(object)"/> + /// methods instead. + /// </para> + /// </remarks> + /// <seealso cref="Fatal(object,Exception)"/> + /// <seealso cref="IsFatalEnabled"/> + void FatalFormat(IFormatProvider provider, string format, params object[] args); + + /// <summary> + /// Checks if this logger is enabled for the <see cref="Level.Debug"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Debug"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// <para> + /// This function is intended to lessen the computational cost of + /// disabled log debug statements. + /// </para> + /// <para> For some ILog interface <c>log</c>, when you write:</para> + /// <code lang="C#"> + /// log.Debug("This is entry number: " + i ); + /// </code> + /// <para> + /// You incur the cost constructing the message, string construction and concatenation in + /// this case, regardless of whether the message is logged or not. + /// </para> + /// <para> + /// If you are worried about speed (who isn't), then you should write: + /// </para> + /// <code lang="C#"> + /// if (log.IsDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// </code> + /// <para> + /// This way you will not incur the cost of parameter + /// construction if debugging is disabled for <c>log</c>. On + /// the other hand, if the <c>log</c> is debug enabled, you + /// will incur the cost of evaluating whether the logger is debug + /// enabled twice. Once in <see cref="IsDebugEnabled"/> and once in + /// the <see cref="Debug(object)"/>. This is an insignificant overhead + /// since evaluating a logger takes about 1% of the time it + /// takes to actually log. This is the preferred style of logging. + /// </para> + /// <para>Alternatively if your logger is available statically then the is debug + /// enabled state can be stored in a static variable like this: + /// </para> + /// <code lang="C#"> + /// private static readonly bool isDebugEnabled = log.IsDebugEnabled; + /// </code> + /// <para> + /// Then when you come to log you can write: + /// </para> + /// <code lang="C#"> + /// if (isDebugEnabled) + /// { + /// log.Debug("This is entry number: " + i ); + /// } + /// </code> + /// <para> + /// This way the debug enabled state is only queried once + /// when the class is loaded. Using a <c>private static readonly</c> + /// variable is the most efficient because it is a run time constant + /// and can be heavily optimized by the JIT compiler. + /// </para> + /// <para> + /// Of course if you use a static readonly variable to + /// hold the enabled state of the logger then you cannot + /// change the enabled state at runtime to vary the logging + /// that is produced. You have to decide if you need absolute + /// speed or runtime flexibility. + /// </para> + /// </remarks> + /// <seealso cref="Debug(object)"/> + /// <seealso cref="DebugFormat(IFormatProvider, string, object[])"/> + bool IsDebugEnabled { get; } + + /// <summary> + /// Checks if this logger is enabled for the <see cref="Level.Info"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Info"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Info(object)"/> + /// <seealso cref="InfoFormat(IFormatProvider, string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + bool IsInfoEnabled { get; } + + /// <summary> + /// Checks if this logger is enabled for the <see cref="Level.Warn"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Warn"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Warn(object)"/> + /// <seealso cref="WarnFormat(IFormatProvider, string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + bool IsWarnEnabled { get; } + + /// <summary> + /// Checks if this logger is enabled for the <see cref="Level.Error"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Error"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Error(object)"/> + /// <seealso cref="ErrorFormat(IFormatProvider, string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + bool IsErrorEnabled { get; } + + /// <summary> + /// Checks if this logger is enabled for the <see cref="Level.Fatal"/> level. + /// </summary> + /// <value> + /// <c>true</c> if this logger is enabled for <see cref="Level.Fatal"/> events, <c>false</c> otherwise. + /// </value> + /// <remarks> + /// For more information see <see cref="ILog.IsDebugEnabled"/>. + /// </remarks> + /// <seealso cref="Fatal(object)"/> + /// <seealso cref="FatalFormat(IFormatProvider, string, object[])"/> + /// <seealso cref="ILog.IsDebugEnabled"/> + bool IsFatalEnabled { get; } + } +} diff --git a/src/DotNetOAuth/Loggers/Log4NetLogger.cs b/src/DotNetOpenAuth/Loggers/Log4NetLogger.cs index 49fd5de..30d93ae 100644 --- a/src/DotNetOAuth/Loggers/Log4NetLogger.cs +++ b/src/DotNetOpenAuth/Loggers/Log4NetLogger.cs @@ -1,211 +1,211 @@ -// <auto-generated />
-
-namespace DotNetOAuth.Loggers {
- using System;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
-
- internal class Log4NetLogger : ILog {
- private log4net.ILog log4netLogger;
-
- private Log4NetLogger(log4net.ILog logger) {
- this.log4netLogger = logger;
- }
-
- #region ILog Members
-
- public bool IsDebugEnabled {
- get { return this.log4netLogger.IsDebugEnabled; }
- }
-
- public bool IsInfoEnabled {
- get { return this.log4netLogger.IsInfoEnabled; }
- }
-
- public bool IsWarnEnabled {
- get { return this.log4netLogger.IsWarnEnabled; }
- }
-
- public bool IsErrorEnabled {
- get { return this.log4netLogger.IsErrorEnabled; }
- }
-
- public bool IsFatalEnabled {
- get { return this.log4netLogger.IsFatalEnabled; }
- }
-
- #endregion
-
- private static bool IsLog4NetPresent {
- get {
- try {
- Assembly.Load("log4net");
- return true;
- } catch (FileNotFoundException) {
- return false;
- }
- }
- }
-
- #region ILog methods
-
- public void Debug(object message) {
- this.log4netLogger.Debug(message);
- }
-
- public void Debug(object message, Exception exception) {
- this.log4netLogger.Debug(message, exception);
- }
-
- public void DebugFormat(string format, params object[] args) {
- this.log4netLogger.DebugFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- public void DebugFormat(string format, object arg0) {
- this.log4netLogger.DebugFormat(format, arg0);
- }
-
- public void DebugFormat(string format, object arg0, object arg1) {
- this.log4netLogger.DebugFormat(format, arg0, arg1);
- }
-
- public void DebugFormat(string format, object arg0, object arg1, object arg2) {
- this.log4netLogger.DebugFormat(format, arg0, arg1, arg2);
- }
-
- public void DebugFormat(IFormatProvider provider, string format, params object[] args) {
- this.log4netLogger.DebugFormat(provider, format, args);
- }
-
- public void Info(object message) {
- this.log4netLogger.Info(message);
- }
-
- public void Info(object message, Exception exception) {
- this.log4netLogger.Info(message, exception);
- }
-
- public void InfoFormat(string format, params object[] args) {
- this.log4netLogger.InfoFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- public void InfoFormat(string format, object arg0) {
- this.log4netLogger.InfoFormat(format, arg0);
- }
-
- public void InfoFormat(string format, object arg0, object arg1) {
- this.log4netLogger.InfoFormat(format, arg0, arg1);
- }
-
- public void InfoFormat(string format, object arg0, object arg1, object arg2) {
- this.log4netLogger.InfoFormat(format, arg0, arg1, arg2);
- }
-
- public void InfoFormat(IFormatProvider provider, string format, params object[] args) {
- this.log4netLogger.InfoFormat(provider, format, args);
- }
-
- public void Warn(object message) {
- this.log4netLogger.Warn(message);
- }
-
- public void Warn(object message, Exception exception) {
- this.log4netLogger.Warn(message, exception);
- }
-
- public void WarnFormat(string format, params object[] args) {
- this.log4netLogger.WarnFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- public void WarnFormat(string format, object arg0) {
- this.log4netLogger.WarnFormat(format, arg0);
- }
-
- public void WarnFormat(string format, object arg0, object arg1) {
- this.log4netLogger.WarnFormat(format, arg0, arg1);
- }
-
- public void WarnFormat(string format, object arg0, object arg1, object arg2) {
- this.log4netLogger.WarnFormat(format, arg0, arg1, arg2);
- }
-
- public void WarnFormat(IFormatProvider provider, string format, params object[] args) {
- this.log4netLogger.WarnFormat(provider, format, args);
- }
-
- public void Error(object message) {
- this.log4netLogger.Error(message);
- }
-
- public void Error(object message, Exception exception) {
- this.log4netLogger.Error(message, exception);
- }
-
- public void ErrorFormat(string format, params object[] args) {
- this.log4netLogger.ErrorFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- public void ErrorFormat(string format, object arg0) {
- this.log4netLogger.ErrorFormat(format, arg0);
- }
-
- public void ErrorFormat(string format, object arg0, object arg1) {
- this.log4netLogger.ErrorFormat(format, arg0, arg1);
- }
-
- public void ErrorFormat(string format, object arg0, object arg1, object arg2) {
- this.log4netLogger.ErrorFormat(format, arg0, arg1, arg2);
- }
-
- public void ErrorFormat(IFormatProvider provider, string format, params object[] args) {
- this.log4netLogger.ErrorFormat(provider, format, args);
- }
-
- public void Fatal(object message) {
- this.log4netLogger.Fatal(message);
- }
-
- public void Fatal(object message, Exception exception) {
- this.log4netLogger.Fatal(message, exception);
- }
-
- public void FatalFormat(string format, params object[] args) {
- this.log4netLogger.FatalFormat(CultureInfo.InvariantCulture, format, args);
- }
-
- public void FatalFormat(string format, object arg0) {
- this.log4netLogger.FatalFormat(format, arg0);
- }
-
- public void FatalFormat(string format, object arg0, object arg1) {
- this.log4netLogger.FatalFormat(format, arg0, arg1);
- }
-
- public void FatalFormat(string format, object arg0, object arg1, object arg2) {
- this.log4netLogger.FatalFormat(format, arg0, arg1, arg2);
- }
-
- public void FatalFormat(IFormatProvider provider, string format, params object[] args) {
- this.log4netLogger.FatalFormat(provider, format, args);
- }
-
- #endregion
-
- /// <summary>
- /// Returns a new log4net logger if it exists, or returns null if the assembly cannot be found.
- /// </summary>
- /// <returns>The created <see cref="ILog"/> instance.</returns>
- internal static ILog Initialize(string name) {
- return IsLog4NetPresent ? CreateLogger(name) : null;
- }
-
- /// <summary>
- /// Creates the log4net.LogManager. Call ONLY after log4net.dll is known to be present.
- /// </summary>
- /// <returns>The created <see cref="ILog"/> instance.</returns>
- private static ILog CreateLogger(string name) {
- return new Log4NetLogger(log4net.LogManager.GetLogger(name));
- }
- }
-}
+// <auto-generated /> + +namespace DotNetOpenAuth.Loggers { + using System; + using System.Globalization; + using System.IO; + using System.Reflection; + + internal class Log4NetLogger : ILog { + private log4net.ILog log4netLogger; + + private Log4NetLogger(log4net.ILog logger) { + this.log4netLogger = logger; + } + + #region ILog Members + + public bool IsDebugEnabled { + get { return this.log4netLogger.IsDebugEnabled; } + } + + public bool IsInfoEnabled { + get { return this.log4netLogger.IsInfoEnabled; } + } + + public bool IsWarnEnabled { + get { return this.log4netLogger.IsWarnEnabled; } + } + + public bool IsErrorEnabled { + get { return this.log4netLogger.IsErrorEnabled; } + } + + public bool IsFatalEnabled { + get { return this.log4netLogger.IsFatalEnabled; } + } + + #endregion + + private static bool IsLog4NetPresent { + get { + try { + Assembly.Load("log4net"); + return true; + } catch (FileNotFoundException) { + return false; + } + } + } + + #region ILog methods + + public void Debug(object message) { + this.log4netLogger.Debug(message); + } + + public void Debug(object message, Exception exception) { + this.log4netLogger.Debug(message, exception); + } + + public void DebugFormat(string format, params object[] args) { + this.log4netLogger.DebugFormat(CultureInfo.InvariantCulture, format, args); + } + + public void DebugFormat(string format, object arg0) { + this.log4netLogger.DebugFormat(format, arg0); + } + + public void DebugFormat(string format, object arg0, object arg1) { + this.log4netLogger.DebugFormat(format, arg0, arg1); + } + + public void DebugFormat(string format, object arg0, object arg1, object arg2) { + this.log4netLogger.DebugFormat(format, arg0, arg1, arg2); + } + + public void DebugFormat(IFormatProvider provider, string format, params object[] args) { + this.log4netLogger.DebugFormat(provider, format, args); + } + + public void Info(object message) { + this.log4netLogger.Info(message); + } + + public void Info(object message, Exception exception) { + this.log4netLogger.Info(message, exception); + } + + public void InfoFormat(string format, params object[] args) { + this.log4netLogger.InfoFormat(CultureInfo.InvariantCulture, format, args); + } + + public void InfoFormat(string format, object arg0) { + this.log4netLogger.InfoFormat(format, arg0); + } + + public void InfoFormat(string format, object arg0, object arg1) { + this.log4netLogger.InfoFormat(format, arg0, arg1); + } + + public void InfoFormat(string format, object arg0, object arg1, object arg2) { + this.log4netLogger.InfoFormat(format, arg0, arg1, arg2); + } + + public void InfoFormat(IFormatProvider provider, string format, params object[] args) { + this.log4netLogger.InfoFormat(provider, format, args); + } + + public void Warn(object message) { + this.log4netLogger.Warn(message); + } + + public void Warn(object message, Exception exception) { + this.log4netLogger.Warn(message, exception); + } + + public void WarnFormat(string format, params object[] args) { + this.log4netLogger.WarnFormat(CultureInfo.InvariantCulture, format, args); + } + + public void WarnFormat(string format, object arg0) { + this.log4netLogger.WarnFormat(format, arg0); + } + + public void WarnFormat(string format, object arg0, object arg1) { + this.log4netLogger.WarnFormat(format, arg0, arg1); + } + + public void WarnFormat(string format, object arg0, object arg1, object arg2) { + this.log4netLogger.WarnFormat(format, arg0, arg1, arg2); + } + + public void WarnFormat(IFormatProvider provider, string format, params object[] args) { + this.log4netLogger.WarnFormat(provider, format, args); + } + + public void Error(object message) { + this.log4netLogger.Error(message); + } + + public void Error(object message, Exception exception) { + this.log4netLogger.Error(message, exception); + } + + public void ErrorFormat(string format, params object[] args) { + this.log4netLogger.ErrorFormat(CultureInfo.InvariantCulture, format, args); + } + + public void ErrorFormat(string format, object arg0) { + this.log4netLogger.ErrorFormat(format, arg0); + } + + public void ErrorFormat(string format, object arg0, object arg1) { + this.log4netLogger.ErrorFormat(format, arg0, arg1); + } + + public void ErrorFormat(string format, object arg0, object arg1, object arg2) { + this.log4netLogger.ErrorFormat(format, arg0, arg1, arg2); + } + + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { + this.log4netLogger.ErrorFormat(provider, format, args); + } + + public void Fatal(object message) { + this.log4netLogger.Fatal(message); + } + + public void Fatal(object message, Exception exception) { + this.log4netLogger.Fatal(message, exception); + } + + public void FatalFormat(string format, params object[] args) { + this.log4netLogger.FatalFormat(CultureInfo.InvariantCulture, format, args); + } + + public void FatalFormat(string format, object arg0) { + this.log4netLogger.FatalFormat(format, arg0); + } + + public void FatalFormat(string format, object arg0, object arg1) { + this.log4netLogger.FatalFormat(format, arg0, arg1); + } + + public void FatalFormat(string format, object arg0, object arg1, object arg2) { + this.log4netLogger.FatalFormat(format, arg0, arg1, arg2); + } + + public void FatalFormat(IFormatProvider provider, string format, params object[] args) { + this.log4netLogger.FatalFormat(provider, format, args); + } + + #endregion + + /// <summary> + /// Returns a new log4net logger if it exists, or returns null if the assembly cannot be found. + /// </summary> + /// <returns>The created <see cref="ILog"/> instance.</returns> + internal static ILog Initialize(string name) { + return IsLog4NetPresent ? CreateLogger(name) : null; + } + + /// <summary> + /// Creates the log4net.LogManager. Call ONLY after log4net.dll is known to be present. + /// </summary> + /// <returns>The created <see cref="ILog"/> instance.</returns> + private static ILog CreateLogger(string name) { + return new Log4NetLogger(log4net.LogManager.GetLogger(name)); + } + } +} diff --git a/src/DotNetOAuth/Loggers/NoOpLogger.cs b/src/DotNetOpenAuth/Loggers/NoOpLogger.cs index 2f48b3c..7001eab 100644 --- a/src/DotNetOAuth/Loggers/NoOpLogger.cs +++ b/src/DotNetOpenAuth/Loggers/NoOpLogger.cs @@ -1,179 +1,179 @@ -// <auto-generated />
-
-namespace DotNetOAuth.Loggers {
- using System;
-
- internal class NoOpLogger : ILog {
- #region ILog Members
-
- public bool IsDebugEnabled {
- get { return false; }
- }
-
- public bool IsInfoEnabled {
- get { return false; }
- }
-
- public bool IsWarnEnabled {
- get { return false; }
- }
-
- public bool IsErrorEnabled {
- get { return false; }
- }
-
- public bool IsFatalEnabled {
- get { return false; }
- }
-
- public void Debug(object message) {
- return;
- }
-
- public void Debug(object message, Exception exception) {
- return;
- }
-
- public void DebugFormat(string format, params object[] args) {
- return;
- }
-
- public void DebugFormat(string format, object arg0) {
- return;
- }
-
- public void DebugFormat(string format, object arg0, object arg1) {
- return;
- }
-
- public void DebugFormat(string format, object arg0, object arg1, object arg2) {
- return;
- }
-
- public void DebugFormat(IFormatProvider provider, string format, params object[] args) {
- return;
- }
-
- public void Info(object message) {
- return;
- }
-
- public void Info(object message, Exception exception) {
- return;
- }
-
- public void InfoFormat(string format, params object[] args) {
- return;
- }
-
- public void InfoFormat(string format, object arg0) {
- return;
- }
-
- public void InfoFormat(string format, object arg0, object arg1) {
- return;
- }
-
- public void InfoFormat(string format, object arg0, object arg1, object arg2) {
- return;
- }
-
- public void InfoFormat(IFormatProvider provider, string format, params object[] args) {
- return;
- }
-
- public void Warn(object message) {
- return;
- }
-
- public void Warn(object message, Exception exception) {
- return;
- }
-
- public void WarnFormat(string format, params object[] args) {
- return;
- }
-
- public void WarnFormat(string format, object arg0) {
- return;
- }
-
- public void WarnFormat(string format, object arg0, object arg1) {
- return;
- }
-
- public void WarnFormat(string format, object arg0, object arg1, object arg2) {
- return;
- }
-
- public void WarnFormat(IFormatProvider provider, string format, params object[] args) {
- return;
- }
-
- public void Error(object message) {
- return;
- }
-
- public void Error(object message, Exception exception) {
- return;
- }
-
- public void ErrorFormat(string format, params object[] args) {
- return;
- }
-
- public void ErrorFormat(string format, object arg0) {
- return;
- }
-
- public void ErrorFormat(string format, object arg0, object arg1) {
- return;
- }
-
- public void ErrorFormat(string format, object arg0, object arg1, object arg2) {
- return;
- }
-
- public void ErrorFormat(IFormatProvider provider, string format, params object[] args) {
- return;
- }
-
- public void Fatal(object message) {
- return;
- }
-
- public void Fatal(object message, Exception exception) {
- return;
- }
-
- public void FatalFormat(string format, params object[] args) {
- return;
- }
-
- public void FatalFormat(string format, object arg0) {
- return;
- }
-
- public void FatalFormat(string format, object arg0, object arg1) {
- return;
- }
-
- public void FatalFormat(string format, object arg0, object arg1, object arg2) {
- return;
- }
-
- public void FatalFormat(IFormatProvider provider, string format, params object[] args) {
- return;
- }
-
- #endregion
-
- /// <summary>
- /// Returns a new logger that does nothing when invoked.
- /// </summary>
- /// <returns>The created <see cref="ILog"/> instance.</returns>
- internal static ILog Initialize() {
- return new NoOpLogger();
- }
- }
-}
+// <auto-generated /> + +namespace DotNetOpenAuth.Loggers { + using System; + + internal class NoOpLogger : ILog { + #region ILog Members + + public bool IsDebugEnabled { + get { return false; } + } + + public bool IsInfoEnabled { + get { return false; } + } + + public bool IsWarnEnabled { + get { return false; } + } + + public bool IsErrorEnabled { + get { return false; } + } + + public bool IsFatalEnabled { + get { return false; } + } + + public void Debug(object message) { + return; + } + + public void Debug(object message, Exception exception) { + return; + } + + public void DebugFormat(string format, params object[] args) { + return; + } + + public void DebugFormat(string format, object arg0) { + return; + } + + public void DebugFormat(string format, object arg0, object arg1) { + return; + } + + public void DebugFormat(string format, object arg0, object arg1, object arg2) { + return; + } + + public void DebugFormat(IFormatProvider provider, string format, params object[] args) { + return; + } + + public void Info(object message) { + return; + } + + public void Info(object message, Exception exception) { + return; + } + + public void InfoFormat(string format, params object[] args) { + return; + } + + public void InfoFormat(string format, object arg0) { + return; + } + + public void InfoFormat(string format, object arg0, object arg1) { + return; + } + + public void InfoFormat(string format, object arg0, object arg1, object arg2) { + return; + } + + public void InfoFormat(IFormatProvider provider, string format, params object[] args) { + return; + } + + public void Warn(object message) { + return; + } + + public void Warn(object message, Exception exception) { + return; + } + + public void WarnFormat(string format, params object[] args) { + return; + } + + public void WarnFormat(string format, object arg0) { + return; + } + + public void WarnFormat(string format, object arg0, object arg1) { + return; + } + + public void WarnFormat(string format, object arg0, object arg1, object arg2) { + return; + } + + public void WarnFormat(IFormatProvider provider, string format, params object[] args) { + return; + } + + public void Error(object message) { + return; + } + + public void Error(object message, Exception exception) { + return; + } + + public void ErrorFormat(string format, params object[] args) { + return; + } + + public void ErrorFormat(string format, object arg0) { + return; + } + + public void ErrorFormat(string format, object arg0, object arg1) { + return; + } + + public void ErrorFormat(string format, object arg0, object arg1, object arg2) { + return; + } + + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { + return; + } + + public void Fatal(object message) { + return; + } + + public void Fatal(object message, Exception exception) { + return; + } + + public void FatalFormat(string format, params object[] args) { + return; + } + + public void FatalFormat(string format, object arg0) { + return; + } + + public void FatalFormat(string format, object arg0, object arg1) { + return; + } + + public void FatalFormat(string format, object arg0, object arg1, object arg2) { + return; + } + + public void FatalFormat(IFormatProvider provider, string format, params object[] args) { + return; + } + + #endregion + + /// <summary> + /// Returns a new logger that does nothing when invoked. + /// </summary> + /// <returns>The created <see cref="ILog"/> instance.</returns> + internal static ILog Initialize() { + return new NoOpLogger(); + } + } +} diff --git a/src/DotNetOAuth/Loggers/TraceLogger.cs b/src/DotNetOpenAuth/Loggers/TraceLogger.cs index c55d6df..414fb5a 100644 --- a/src/DotNetOAuth/Loggers/TraceLogger.cs +++ b/src/DotNetOpenAuth/Loggers/TraceLogger.cs @@ -1,332 +1,332 @@ -// <auto-generated />
-
-namespace DotNetOAuth.Loggers {
- using System;
- using System.Diagnostics;
- using System.Security;
- using System.Security.Permissions;
-
- internal class TraceLogger : ILog {
- private TraceSwitch traceSwitch;
-
- internal TraceLogger(string name) {
- traceSwitch = new TraceSwitch(name, name + " Trace Switch");
- }
-
- #region ILog Properties
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public bool IsDebugEnabled {
- get { return this.traceSwitch.TraceVerbose; }
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public bool IsInfoEnabled {
- get { return this.traceSwitch.TraceInfo; }
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public bool IsWarnEnabled {
- get { return this.traceSwitch.TraceWarning; }
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public bool IsErrorEnabled {
- get { return this.traceSwitch.TraceError; }
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public bool IsFatalEnabled {
- get { return this.traceSwitch.TraceError; }
- }
-
- #endregion
-
- private static bool IsSufficientPermissionGranted {
- get {
- PermissionSet permissions = new PermissionSet(PermissionState.None);
- permissions.AddPermission(new KeyContainerPermission(PermissionState.Unrestricted));
- permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
- permissions.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
- permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.ControlThread));
- var file = new FileIOPermission(PermissionState.None);
- file.AllFiles = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read;
- permissions.AddPermission(file);
- try {
- permissions.Demand();
- return true;
- } catch (SecurityException) {
- return false;
- }
- }
- }
-
- #region ILog Methods
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Debug(object message) {
- Trace.TraceInformation(message.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Debug(object message, Exception exception) {
- Trace.TraceInformation(message + ": " + exception.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void DebugFormat(string format, params object[] args) {
- Trace.TraceInformation(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void DebugFormat(string format, object arg0) {
- Trace.TraceInformation(format, arg0);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void DebugFormat(string format, object arg0, object arg1) {
- Trace.TraceInformation(format, arg0, arg1);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void DebugFormat(string format, object arg0, object arg1, object arg2) {
- Trace.TraceInformation(format, arg0, arg1, arg2);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void DebugFormat(IFormatProvider provider, string format, params object[] args) {
- Trace.TraceInformation(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Info(object message) {
- Trace.TraceInformation(message.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Info(object message, Exception exception) {
- Trace.TraceInformation(message + ": " + exception.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void InfoFormat(string format, params object[] args) {
- Trace.TraceInformation(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void InfoFormat(string format, object arg0) {
- Trace.TraceInformation(format, arg0);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void InfoFormat(string format, object arg0, object arg1) {
- Trace.TraceInformation(format, arg0, arg1);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void InfoFormat(string format, object arg0, object arg1, object arg2) {
- Trace.TraceInformation(format, arg0, arg1, arg2);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void InfoFormat(IFormatProvider provider, string format, params object[] args) {
- Trace.TraceInformation(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Warn(object message) {
- Trace.TraceWarning(message.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Warn(object message, Exception exception) {
- Trace.TraceWarning(message + ": " + exception.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void WarnFormat(string format, params object[] args) {
- Trace.TraceWarning(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void WarnFormat(string format, object arg0) {
- Trace.TraceWarning(format, arg0);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void WarnFormat(string format, object arg0, object arg1) {
- Trace.TraceWarning(format, arg0, arg1);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void WarnFormat(string format, object arg0, object arg1, object arg2) {
- Trace.TraceWarning(format, arg0, arg1, arg2);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void WarnFormat(IFormatProvider provider, string format, params object[] args) {
- Trace.TraceWarning(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Error(object message) {
- Trace.TraceError(message.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Error(object message, Exception exception) {
- Trace.TraceError(message + ": " + exception.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void ErrorFormat(string format, params object[] args) {
- Trace.TraceError(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void ErrorFormat(string format, object arg0) {
- Trace.TraceError(format, arg0);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void ErrorFormat(string format, object arg0, object arg1) {
- Trace.TraceError(format, arg0, arg1);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void ErrorFormat(string format, object arg0, object arg1, object arg2) {
- Trace.TraceError(format, arg0, arg1, arg2);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void ErrorFormat(IFormatProvider provider, string format, params object[] args) {
- Trace.TraceError(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Fatal(object message) {
- Trace.TraceError(message.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void Fatal(object message, Exception exception) {
- Trace.TraceError(message + ": " + exception.ToString());
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void FatalFormat(string format, params object[] args) {
- Trace.TraceError(format, args);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void FatalFormat(string format, object arg0) {
- Trace.TraceError(format, arg0);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void FatalFormat(string format, object arg0, object arg1) {
- Trace.TraceError(format, arg0, arg1);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void FatalFormat(string format, object arg0, object arg1, object arg2) {
- Trace.TraceError(format, arg0, arg1, arg2);
- }
-
- /// <summary>
- /// See <see cref="ILog"/>.
- /// </summary>
- public void FatalFormat(IFormatProvider provider, string format, params object[] args) {
- Trace.TraceError(format, args);
- }
-
- #endregion
-
- /// <summary>
- /// Returns a new logger that uses the <see cref="System.Diagnostics.Trace"/> class
- /// if sufficient CAS permissions are granted to use it, otherwise returns false.
- /// </summary>
- /// <returns>The created <see cref="ILog"/> instance.</returns>
- internal static ILog Initialize(string name) {
- return IsSufficientPermissionGranted ? new TraceLogger(name) : null;
- }
- }
-}
+// <auto-generated /> + +namespace DotNetOpenAuth.Loggers { + using System; + using System.Diagnostics; + using System.Security; + using System.Security.Permissions; + + internal class TraceLogger : ILog { + private TraceSwitch traceSwitch; + + internal TraceLogger(string name) { + traceSwitch = new TraceSwitch(name, name + " Trace Switch"); + } + + #region ILog Properties + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public bool IsDebugEnabled { + get { return this.traceSwitch.TraceVerbose; } + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public bool IsInfoEnabled { + get { return this.traceSwitch.TraceInfo; } + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public bool IsWarnEnabled { + get { return this.traceSwitch.TraceWarning; } + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public bool IsErrorEnabled { + get { return this.traceSwitch.TraceError; } + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public bool IsFatalEnabled { + get { return this.traceSwitch.TraceError; } + } + + #endregion + + private static bool IsSufficientPermissionGranted { + get { + PermissionSet permissions = new PermissionSet(PermissionState.None); + permissions.AddPermission(new KeyContainerPermission(PermissionState.Unrestricted)); + permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)); + permissions.AddPermission(new RegistryPermission(PermissionState.Unrestricted)); + permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.ControlThread)); + var file = new FileIOPermission(PermissionState.None); + file.AllFiles = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read; + permissions.AddPermission(file); + try { + permissions.Demand(); + return true; + } catch (SecurityException) { + return false; + } + } + } + + #region ILog Methods + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Debug(object message) { + Trace.TraceInformation(message.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Debug(object message, Exception exception) { + Trace.TraceInformation(message + ": " + exception.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void DebugFormat(string format, params object[] args) { + Trace.TraceInformation(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void DebugFormat(string format, object arg0) { + Trace.TraceInformation(format, arg0); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void DebugFormat(string format, object arg0, object arg1) { + Trace.TraceInformation(format, arg0, arg1); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void DebugFormat(string format, object arg0, object arg1, object arg2) { + Trace.TraceInformation(format, arg0, arg1, arg2); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void DebugFormat(IFormatProvider provider, string format, params object[] args) { + Trace.TraceInformation(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Info(object message) { + Trace.TraceInformation(message.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Info(object message, Exception exception) { + Trace.TraceInformation(message + ": " + exception.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void InfoFormat(string format, params object[] args) { + Trace.TraceInformation(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void InfoFormat(string format, object arg0) { + Trace.TraceInformation(format, arg0); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void InfoFormat(string format, object arg0, object arg1) { + Trace.TraceInformation(format, arg0, arg1); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void InfoFormat(string format, object arg0, object arg1, object arg2) { + Trace.TraceInformation(format, arg0, arg1, arg2); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void InfoFormat(IFormatProvider provider, string format, params object[] args) { + Trace.TraceInformation(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Warn(object message) { + Trace.TraceWarning(message.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Warn(object message, Exception exception) { + Trace.TraceWarning(message + ": " + exception.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void WarnFormat(string format, params object[] args) { + Trace.TraceWarning(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void WarnFormat(string format, object arg0) { + Trace.TraceWarning(format, arg0); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void WarnFormat(string format, object arg0, object arg1) { + Trace.TraceWarning(format, arg0, arg1); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void WarnFormat(string format, object arg0, object arg1, object arg2) { + Trace.TraceWarning(format, arg0, arg1, arg2); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void WarnFormat(IFormatProvider provider, string format, params object[] args) { + Trace.TraceWarning(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Error(object message) { + Trace.TraceError(message.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Error(object message, Exception exception) { + Trace.TraceError(message + ": " + exception.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void ErrorFormat(string format, params object[] args) { + Trace.TraceError(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void ErrorFormat(string format, object arg0) { + Trace.TraceError(format, arg0); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void ErrorFormat(string format, object arg0, object arg1) { + Trace.TraceError(format, arg0, arg1); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void ErrorFormat(string format, object arg0, object arg1, object arg2) { + Trace.TraceError(format, arg0, arg1, arg2); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { + Trace.TraceError(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Fatal(object message) { + Trace.TraceError(message.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void Fatal(object message, Exception exception) { + Trace.TraceError(message + ": " + exception.ToString()); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void FatalFormat(string format, params object[] args) { + Trace.TraceError(format, args); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void FatalFormat(string format, object arg0) { + Trace.TraceError(format, arg0); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void FatalFormat(string format, object arg0, object arg1) { + Trace.TraceError(format, arg0, arg1); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void FatalFormat(string format, object arg0, object arg1, object arg2) { + Trace.TraceError(format, arg0, arg1, arg2); + } + + /// <summary> + /// See <see cref="ILog"/>. + /// </summary> + public void FatalFormat(IFormatProvider provider, string format, params object[] args) { + Trace.TraceError(format, args); + } + + #endregion + + /// <summary> + /// Returns a new logger that uses the <see cref="System.Diagnostics.Trace"/> class + /// if sufficient CAS permissions are granted to use it, otherwise returns false. + /// </summary> + /// <returns>The created <see cref="ILog"/> instance.</returns> + internal static ILog Initialize(string name) { + return IsSufficientPermissionGranted ? new TraceLogger(name) : null; + } + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/Bindings.cd b/src/DotNetOpenAuth/Messaging/Bindings/Bindings.cd index c663332..47a133a 100644 --- a/src/DotNetOAuth/Messaging/Bindings/Bindings.cd +++ b/src/DotNetOpenAuth/Messaging/Bindings/Bindings.cd @@ -1,76 +1,76 @@ -<?xml version="1.0" encoding="utf-8"?>
-<ClassDiagram MajorVersion="1" MinorVersion="1">
- <Class Name="DotNetOAuth.Messaging.Bindings.InvalidSignatureException" Collapsed="true">
- <Position X="8.25" Y="2" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\Bindings\InvalidSignatureException.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.Messaging.Bindings.ReplayedMessageException" Collapsed="true">
- <Position X="6" Y="2" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\Bindings\ReplayedMessageException.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.Messaging.Bindings.ExpiredMessageException" Collapsed="true">
- <Position X="3.75" Y="2" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\Bindings\ExpiredMessageException.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.Messaging.ProtocolException" Collapsed="true">
- <Position X="6" Y="0.5" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAKAAAAAAAAAAAAAIBAAAAACAQAIAAAAACAAAAAAAA=</HashCode>
- <FileName>Messaging\ProtocolException.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.Messaging.Bindings.StandardExpirationBindingElement" Collapsed="true">
- <Position X="1" Y="3" Width="2.75" />
- <TypeIdentifier>
- <HashCode>AAAQAAAAAAAARAAAAAAAEAAAAAIAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\Bindings\StandardExpirationBindingElement.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Interface Name="DotNetOAuth.Messaging.IProtocolMessage" Collapsed="true">
- <Position X="6" Y="3.5" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAQAAAAAAAAAAAAAYAAAAAAAAAAAACAAAAAAA=</HashCode>
- <FileName>Messaging\IProtocolMessage.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Interface Name="DotNetOAuth.Messaging.Bindings.IExpiringProtocolMessage" Collapsed="true">
- <Position X="3.75" Y="4.75" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\Bindings\IExpiringProtocolMessage.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Interface Name="DotNetOAuth.Messaging.Bindings.IReplayProtectedProtocolMessage" Collapsed="true">
- <Position X="6" Y="4.75" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAA=</HashCode>
- <FileName>Messaging\Bindings\IReplayProtectedProtocolMessage.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Interface Name="DotNetOAuth.Messaging.Bindings.ISignedOAuthMessage" Collapsed="true">
- <Position X="8.25" Y="4.75" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE=</HashCode>
- <FileName>Messaging\Bindings\ISignedOAuthMessage.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Interface Name="DotNetOAuth.Messaging.IChannelBindingElement">
- <Position X="0.5" Y="0.5" Width="2" />
- <TypeIdentifier>
- <HashCode>BAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAEAAAAAAAAA=</HashCode>
- <FileName>Messaging\IChannelBindingElement.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Font Name="Segoe UI" Size="9" />
+<?xml version="1.0" encoding="utf-8"?> +<ClassDiagram MajorVersion="1" MinorVersion="1"> + <Class Name="DotNetOpenAuth.Messaging.Bindings.InvalidSignatureException" Collapsed="true"> + <Position X="8.25" Y="2" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\Bindings\InvalidSignatureException.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.Messaging.Bindings.ReplayedMessageException" Collapsed="true"> + <Position X="6" Y="2" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\Bindings\ReplayedMessageException.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.Messaging.Bindings.ExpiredMessageException" Collapsed="true"> + <Position X="3.75" Y="2" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\Bindings\ExpiredMessageException.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.Messaging.ProtocolException" Collapsed="true"> + <Position X="6" Y="0.5" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAKAAAAAAAAAAAAAIBAAAAACAQAIAAAAACAAAAAAAA=</HashCode> + <FileName>Messaging\ProtocolException.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messaging.Bindings.StandardExpirationBindingElement" Collapsed="true"> + <Position X="1" Y="3" Width="2.75" /> + <TypeIdentifier> + <HashCode>AAAQAAAAAAAARAAAAAAAEAAAAAIAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\Bindings\StandardExpirationBindingElement.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Interface Name="DotNetOpenAuth.Messaging.IProtocolMessage" Collapsed="true"> + <Position X="6" Y="3.5" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAQAAAAAAAAAAAAAYAAAAAAAAAAAACAAAAAAA=</HashCode> + <FileName>Messaging\IProtocolMessage.cs</FileName> + </TypeIdentifier> + </Interface> + <Interface Name="DotNetOpenAuth.Messaging.Bindings.IExpiringProtocolMessage" Collapsed="true"> + <Position X="3.75" Y="4.75" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\Bindings\IExpiringProtocolMessage.cs</FileName> + </TypeIdentifier> + </Interface> + <Interface Name="DotNetOpenAuth.Messaging.Bindings.IReplayProtectedProtocolMessage" Collapsed="true"> + <Position X="6" Y="4.75" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAA=</HashCode> + <FileName>Messaging\Bindings\IReplayProtectedProtocolMessage.cs</FileName> + </TypeIdentifier> + </Interface> + <Interface Name="DotNetOpenAuth.Messaging.Bindings.ISignedOAuthMessage" Collapsed="true"> + <Position X="8.25" Y="4.75" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE=</HashCode> + <FileName>Messaging\Bindings\ISignedOAuthMessage.cs</FileName> + </TypeIdentifier> + </Interface> + <Interface Name="DotNetOpenAuth.Messaging.IChannelBindingElement"> + <Position X="0.5" Y="0.5" Width="2" /> + <TypeIdentifier> + <HashCode>BAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAEAAAAAAAAA=</HashCode> + <FileName>Messaging\IChannelBindingElement.cs</FileName> + </TypeIdentifier> + </Interface> + <Font Name="Segoe UI" Size="9" /> </ClassDiagram>
\ No newline at end of file diff --git a/src/DotNetOAuth/Messaging/Bindings/ExpiredMessageException.cs b/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs index fabe7e4..fe5bf3a 100644 --- a/src/DotNetOAuth/Messaging/Bindings/ExpiredMessageException.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs @@ -1,37 +1,37 @@ -//-----------------------------------------------------------------------
-// <copyright file="ExpiredMessageException.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
- using System.Globalization;
-
- /// <summary>
- /// An exception thrown when a message is received that exceeds the maximum message age limit.
- /// </summary>
- [Serializable]
- internal class ExpiredMessageException : ProtocolException {
- /// <summary>
- /// Initializes a new instance of the <see cref="ExpiredMessageException"/> class.
- /// </summary>
- /// <param name="utcExpirationDate">The date the message expired.</param>
- /// <param name="faultedMessage">The expired message.</param>
- public ExpiredMessageException(DateTime utcExpirationDate, IProtocolMessage faultedMessage)
- : base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.ExpiredMessage, utcExpirationDate.ToUniversalTime(), DateTime.UtcNow), faultedMessage) {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ExpiredMessageException"/> class.
- /// </summary>
- /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/>
- /// that holds the serialized object data about the exception being thrown.</param>
- /// <param name="context">The System.Runtime.Serialization.StreamingContext
- /// that contains contextual information about the source or destination.</param>
- protected ExpiredMessageException(
- System.Runtime.Serialization.SerializationInfo info,
- System.Runtime.Serialization.StreamingContext context)
- : base(info, context) { }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ExpiredMessageException.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + using System.Globalization; + + /// <summary> + /// An exception thrown when a message is received that exceeds the maximum message age limit. + /// </summary> + [Serializable] + internal class ExpiredMessageException : ProtocolException { + /// <summary> + /// Initializes a new instance of the <see cref="ExpiredMessageException"/> class. + /// </summary> + /// <param name="utcExpirationDate">The date the message expired.</param> + /// <param name="faultedMessage">The expired message.</param> + public ExpiredMessageException(DateTime utcExpirationDate, IProtocolMessage faultedMessage) + : base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.ExpiredMessage, utcExpirationDate.ToUniversalTime(), DateTime.UtcNow), faultedMessage) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ExpiredMessageException"/> class. + /// </summary> + /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> + /// that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The System.Runtime.Serialization.StreamingContext + /// that contains contextual information about the source or destination.</param> + protected ExpiredMessageException( + System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) + : base(info, context) { } + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/IExpiringProtocolMessage.cs b/src/DotNetOpenAuth/Messaging/Bindings/IExpiringProtocolMessage.cs index 39c4f97..fc43ae6 100644 --- a/src/DotNetOAuth/Messaging/Bindings/IExpiringProtocolMessage.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/IExpiringProtocolMessage.cs @@ -1,29 +1,29 @@ -//-----------------------------------------------------------------------
-// <copyright file="IExpiringProtocolMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
-
- /// <summary>
- /// The contract a message that has an allowable time window for processing must implement.
- /// </summary>
- /// <remarks>
- /// All expiring messages must also be signed to prevent tampering with the creation date.
- /// </remarks>
- internal interface IExpiringProtocolMessage : IProtocolMessage {
- /// <summary>
- /// Gets or sets the UTC date/time the message was originally sent onto the network.
- /// </summary>
- /// <remarks>
- /// The property setter should ensure a UTC date/time,
- /// and throw an exception if this is not possible.
- /// </remarks>
- /// <exception cref="ArgumentException">
- /// Thrown when a DateTime that cannot be converted to UTC is set.
- /// </exception>
- DateTime UtcCreationDate { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IExpiringProtocolMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + + /// <summary> + /// The contract a message that has an allowable time window for processing must implement. + /// </summary> + /// <remarks> + /// All expiring messages must also be signed to prevent tampering with the creation date. + /// </remarks> + internal interface IExpiringProtocolMessage : IProtocolMessage { + /// <summary> + /// Gets or sets the UTC date/time the message was originally sent onto the network. + /// </summary> + /// <remarks> + /// The property setter should ensure a UTC date/time, + /// and throw an exception if this is not possible. + /// </remarks> + /// <exception cref="ArgumentException"> + /// Thrown when a DateTime that cannot be converted to UTC is set. + /// </exception> + DateTime UtcCreationDate { get; set; } + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/INonceStore.cs b/src/DotNetOpenAuth/Messaging/Bindings/INonceStore.cs index 0ff7e60..bf8fcfe 100644 --- a/src/DotNetOAuth/Messaging/Bindings/INonceStore.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/INonceStore.cs @@ -1,37 +1,37 @@ -//-----------------------------------------------------------------------
-// <copyright file="INonceStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
-
- /// <summary>
- /// Describes the contract a nonce store must fulfill.
- /// </summary>
- internal interface INonceStore {
- /// <summary>
- /// Stores a given nonce and timestamp.
- /// </summary>
- /// <param name="nonce">
- /// A series of random characters.
- /// </param>
- /// <param name="timestamp">
- /// The timestamp that together with the nonce string make it unique.
- /// The timestamp may also be used by the data store to clear out old nonces.
- /// </param>
- /// <returns>
- /// True if the nonce+timestamp (combination) was not previously in the database.
- /// False if the nonce was stored previously with the same timestamp.
- /// </returns>
- /// <remarks>
- /// The nonce must be stored for no less than the maximum time window a message may
- /// be processed within before being discarded as an expired message.
- /// If the binding element is applicable to your channel, this expiration window
- /// is retrieved or set using the
- /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
- /// </remarks>
- bool StoreNonce(string nonce, DateTime timestamp);
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="INonceStore.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + + /// <summary> + /// Describes the contract a nonce store must fulfill. + /// </summary> + internal interface INonceStore { + /// <summary> + /// Stores a given nonce and timestamp. + /// </summary> + /// <param name="nonce"> + /// A series of random characters. + /// </param> + /// <param name="timestamp"> + /// The timestamp that together with the nonce string make it unique. + /// The timestamp may also be used by the data store to clear out old nonces. + /// </param> + /// <returns> + /// True if the nonce+timestamp (combination) was not previously in the database. + /// False if the nonce was stored previously with the same timestamp. + /// </returns> + /// <remarks> + /// The nonce must be stored for no less than the maximum time window a message may + /// be processed within before being discarded as an expired message. + /// If the binding element is applicable to your channel, this expiration window + /// is retrieved or set using the + /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property. + /// </remarks> + bool StoreNonce(string nonce, DateTime timestamp); + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs b/src/DotNetOpenAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs index bc685ce..02f3ee3 100644 --- a/src/DotNetOAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/IReplayProtectedProtocolMessage.cs @@ -1,24 +1,24 @@ -//-----------------------------------------------------------------------
-// <copyright file="IReplayProtectedProtocolMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// The contract a message that has an allowable time window for processing must implement.
- /// </summary>
- /// <remarks>
- /// All replay-protected messages must also be set to expire so the nonces do not have
- /// to be stored indefinitely.
- /// </remarks>
- internal interface IReplayProtectedProtocolMessage : IExpiringProtocolMessage {
- /// <summary>
- /// Gets or sets the nonce that will protect the message from replay attacks.
- /// </summary>
- string Nonce { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IReplayProtectedProtocolMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// The contract a message that has an allowable time window for processing must implement. + /// </summary> + /// <remarks> + /// All replay-protected messages must also be set to expire so the nonces do not have + /// to be stored indefinitely. + /// </remarks> + internal interface IReplayProtectedProtocolMessage : IExpiringProtocolMessage { + /// <summary> + /// Gets or sets the nonce that will protect the message from replay attacks. + /// </summary> + string Nonce { get; set; } + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/InvalidSignatureException.cs b/src/DotNetOpenAuth/Messaging/Bindings/InvalidSignatureException.cs index 89fa938..28b7e96 100644 --- a/src/DotNetOAuth/Messaging/Bindings/InvalidSignatureException.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/InvalidSignatureException.cs @@ -1,34 +1,34 @@ -//-----------------------------------------------------------------------
-// <copyright file="InvalidSignatureException.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
-
- /// <summary>
- /// An exception thrown when a signed message does not pass signature validation.
- /// </summary>
- [Serializable]
- internal class InvalidSignatureException : ProtocolException {
- /// <summary>
- /// Initializes a new instance of the <see cref="InvalidSignatureException"/> class.
- /// </summary>
- /// <param name="faultedMessage">The message with the invalid signature.</param>
- public InvalidSignatureException(IProtocolMessage faultedMessage)
- : base(MessagingStrings.SignatureInvalid, faultedMessage) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="InvalidSignatureException"/> class.
- /// </summary>
- /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/>
- /// that holds the serialized object data about the exception being thrown.</param>
- /// <param name="context">The System.Runtime.Serialization.StreamingContext
- /// that contains contextual information about the source or destination.</param>
- protected InvalidSignatureException(
- System.Runtime.Serialization.SerializationInfo info,
- System.Runtime.Serialization.StreamingContext context)
- : base(info, context) { }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="InvalidSignatureException.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + + /// <summary> + /// An exception thrown when a signed message does not pass signature validation. + /// </summary> + [Serializable] + internal class InvalidSignatureException : ProtocolException { + /// <summary> + /// Initializes a new instance of the <see cref="InvalidSignatureException"/> class. + /// </summary> + /// <param name="faultedMessage">The message with the invalid signature.</param> + public InvalidSignatureException(IProtocolMessage faultedMessage) + : base(MessagingStrings.SignatureInvalid, faultedMessage) { } + + /// <summary> + /// Initializes a new instance of the <see cref="InvalidSignatureException"/> class. + /// </summary> + /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> + /// that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The System.Runtime.Serialization.StreamingContext + /// that contains contextual information about the source or destination.</param> + protected InvalidSignatureException( + System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) + : base(info, context) { } + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/NonceMemoryStore.cs b/src/DotNetOpenAuth/Messaging/Bindings/NonceMemoryStore.cs index 98b93ff..5fa3fe1 100644 --- a/src/DotNetOAuth/Messaging/Bindings/NonceMemoryStore.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/NonceMemoryStore.cs @@ -1,72 +1,72 @@ -//-----------------------------------------------------------------------
-// <copyright file="NonceMemoryStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging.Bindings;
-
- /// <summary>
- /// An in-memory nonce store. Useful for single-server web applications.
- /// NOT for web farms.
- /// </summary>
- internal class NonceMemoryStore : INonceStore {
- /// <summary>
- /// The maximum age a message can be before it is discarded.
- /// </summary>
- /// <remarks>
- /// This is useful for knowing how long used nonces must be retained.
- /// </remarks>
- private readonly TimeSpan maximumMessageAge;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="NonceMemoryStore"/> class.
- /// </summary>
- /// <param name="maximumMessageAge">The maximum age a message can be before it is discarded.</param>
- internal NonceMemoryStore(TimeSpan maximumMessageAge) {
- this.maximumMessageAge = maximumMessageAge;
- }
-
- #region INonceStore Members
-
- /// <summary>
- /// Stores a given nonce and timestamp.
- /// </summary>
- /// <param name="nonce">
- /// A series of random characters.
- /// </param>
- /// <param name="timestamp">
- /// The timestamp that together with the nonce string make it unique.
- /// The timestamp may also be used by the data store to clear out old nonces.
- /// </param>
- /// <returns>
- /// True if the nonce+timestamp (combination) was not previously in the database.
- /// False if the nonce was stored previously with the same timestamp.
- /// </returns>
- /// <remarks>
- /// The nonce must be stored for no less than the maximum time window a message may
- /// be processed within before being discarded as an expired message.
- /// If the binding element is applicable to your channel, this expiration window
- /// is retrieved or set using the
- /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
- /// </remarks>
- public bool StoreNonce(string nonce, DateTime timestamp) {
- if (timestamp.ToUniversalTime() + this.maximumMessageAge < DateTime.UtcNow) {
- // The expiration binding element should have taken care of this, but perhaps
- // it's at the boundary case. We should fail just to be safe.
- return false;
- }
-
- // TODO: implement actual nonce checking.
- Logger.Warn("Nonce checking not implemented yet.");
- return true;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="NonceMemoryStore.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging.Bindings; + + /// <summary> + /// An in-memory nonce store. Useful for single-server web applications. + /// NOT for web farms. + /// </summary> + internal class NonceMemoryStore : INonceStore { + /// <summary> + /// The maximum age a message can be before it is discarded. + /// </summary> + /// <remarks> + /// This is useful for knowing how long used nonces must be retained. + /// </remarks> + private readonly TimeSpan maximumMessageAge; + + /// <summary> + /// Initializes a new instance of the <see cref="NonceMemoryStore"/> class. + /// </summary> + /// <param name="maximumMessageAge">The maximum age a message can be before it is discarded.</param> + internal NonceMemoryStore(TimeSpan maximumMessageAge) { + this.maximumMessageAge = maximumMessageAge; + } + + #region INonceStore Members + + /// <summary> + /// Stores a given nonce and timestamp. + /// </summary> + /// <param name="nonce"> + /// A series of random characters. + /// </param> + /// <param name="timestamp"> + /// The timestamp that together with the nonce string make it unique. + /// The timestamp may also be used by the data store to clear out old nonces. + /// </param> + /// <returns> + /// True if the nonce+timestamp (combination) was not previously in the database. + /// False if the nonce was stored previously with the same timestamp. + /// </returns> + /// <remarks> + /// The nonce must be stored for no less than the maximum time window a message may + /// be processed within before being discarded as an expired message. + /// If the binding element is applicable to your channel, this expiration window + /// is retrieved or set using the + /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property. + /// </remarks> + public bool StoreNonce(string nonce, DateTime timestamp) { + if (timestamp.ToUniversalTime() + this.maximumMessageAge < DateTime.UtcNow) { + // The expiration binding element should have taken care of this, but perhaps + // it's at the boundary case. We should fail just to be safe. + return false; + } + + // TODO: implement actual nonce checking. + Logger.Warn("Nonce checking not implemented yet."); + return true; + } + + #endregion + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/ReplayedMessageException.cs b/src/DotNetOpenAuth/Messaging/Bindings/ReplayedMessageException.cs index 11cf096..2b8df9d 100644 --- a/src/DotNetOAuth/Messaging/Bindings/ReplayedMessageException.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/ReplayedMessageException.cs @@ -1,34 +1,34 @@ -//-----------------------------------------------------------------------
-// <copyright file="ReplayedMessageException.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
-
- /// <summary>
- /// An exception thrown when a message is received for the second time, signalling a possible
- /// replay attack.
- /// </summary>
- [Serializable]
- internal class ReplayedMessageException : ProtocolException {
- /// <summary>
- /// Initializes a new instance of the <see cref="ReplayedMessageException"/> class.
- /// </summary>
- /// <param name="faultedMessage">The replayed message.</param>
- public ReplayedMessageException(IProtocolMessage faultedMessage) : base(MessagingStrings.ReplayAttackDetected, faultedMessage) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ReplayedMessageException"/> class.
- /// </summary>
- /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/>
- /// that holds the serialized object data about the exception being thrown.</param>
- /// <param name="context">The System.Runtime.Serialization.StreamingContext
- /// that contains contextual information about the source or destination.</param>
- protected ReplayedMessageException(
- System.Runtime.Serialization.SerializationInfo info,
- System.Runtime.Serialization.StreamingContext context)
- : base(info, context) { }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ReplayedMessageException.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + + /// <summary> + /// An exception thrown when a message is received for the second time, signalling a possible + /// replay attack. + /// </summary> + [Serializable] + internal class ReplayedMessageException : ProtocolException { + /// <summary> + /// Initializes a new instance of the <see cref="ReplayedMessageException"/> class. + /// </summary> + /// <param name="faultedMessage">The replayed message.</param> + public ReplayedMessageException(IProtocolMessage faultedMessage) : base(MessagingStrings.ReplayAttackDetected, faultedMessage) { } + + /// <summary> + /// Initializes a new instance of the <see cref="ReplayedMessageException"/> class. + /// </summary> + /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> + /// that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The System.Runtime.Serialization.StreamingContext + /// that contains contextual information about the source or destination.</param> + protected ReplayedMessageException( + System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) + : base(info, context) { } + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/StandardExpirationBindingElement.cs b/src/DotNetOpenAuth/Messaging/Bindings/StandardExpirationBindingElement.cs index fa7f78c..d2baa48 100644 --- a/src/DotNetOAuth/Messaging/Bindings/StandardExpirationBindingElement.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/StandardExpirationBindingElement.cs @@ -1,119 +1,119 @@ -//-----------------------------------------------------------------------
-// <copyright file="StandardExpirationBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
-
- /// <summary>
- /// A message expiration enforcing binding element that supports messages
- /// implementing the <see cref="IExpiringProtocolMessage"/> interface.
- /// </summary>
- internal class StandardExpirationBindingElement : IChannelBindingElement {
- /// <summary>
- /// The default maximum message age to use if the default constructor is called.
- /// </summary>
- internal static readonly TimeSpan DefaultMaximumMessageAge = TimeSpan.FromMinutes(13);
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StandardExpirationBindingElement"/> class
- /// with a default maximum message lifetime of 13 minutes.
- /// </summary>
- internal StandardExpirationBindingElement()
- : this(DefaultMaximumMessageAge) {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StandardExpirationBindingElement"/> class.
- /// </summary>
- /// <param name="maximumAge">
- /// <para>The maximum age a message implementing the
- /// <see cref="IExpiringProtocolMessage"/> interface can be before
- /// being discarded as too old.</para>
- /// <para>This time limit should take into account expected time skew for servers
- /// across the Internet. For example, if a server could conceivably have its
- /// clock d = 5 minutes off UTC time, then any two servers could have
- /// their clocks disagree by as much as 2*d = 10 minutes.
- /// If a message should live for at least t = 3 minutes,
- /// this property should be set to (2*d + t) = 13 minutes.</para>
- /// </param>
- internal StandardExpirationBindingElement(TimeSpan maximumAge) {
- this.MaximumMessageAge = maximumAge;
- }
-
- #region IChannelBindingElement Properties
-
- /// <summary>
- /// Gets the protection offered by this binding element.
- /// </summary>
- /// <value><see cref="MessageProtections.Expiration"/></value>
- MessageProtections IChannelBindingElement.Protection {
- get { return MessageProtections.Expiration; }
- }
-
- #endregion
-
- /// <summary>
- /// Gets the maximum age a message implementing the
- /// <see cref="IExpiringProtocolMessage"/> interface can be before
- /// being discarded as too old.
- /// </summary>
- protected internal TimeSpan MaximumMessageAge {
- get;
- private set;
- }
-
- #region IChannelBindingElement Methods
-
- /// <summary>
- /// Sets the timestamp on an outgoing message.
- /// </summary>
- /// <param name="message">The outgoing message.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False otherwise.
- /// </returns>
- bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) {
- IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage;
- if (expiringMessage != null) {
- expiringMessage.UtcCreationDate = DateTime.UtcNow;
- return true;
- }
-
- return false;
- }
-
- /// <summary>
- /// Reads the timestamp on a message and throws an exception if the message is too old.
- /// </summary>
- /// <param name="message">The incoming message.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False if the operation did not apply to this message.
- /// </returns>
- /// <exception cref="ExpiredMessageException">Thrown if the given message has already expired.</exception>
- /// <exception cref="ProtocolException">
- /// Thrown when the binding element rules indicate that this message is invalid and should
- /// NOT be processed.
- /// </exception>
- bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) {
- IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage;
- if (expiringMessage != null) {
- // Yes the UtcCreationDate is supposed to always be in UTC already,
- // but just in case a given message failed to guarantee that, we do it here.
- DateTime expirationDate = expiringMessage.UtcCreationDate.ToUniversalTime() + this.MaximumMessageAge;
- if (expirationDate < DateTime.UtcNow) {
- throw new ExpiredMessageException(expirationDate, expiringMessage);
- }
-
- return true;
- }
-
- return false;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="StandardExpirationBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + + /// <summary> + /// A message expiration enforcing binding element that supports messages + /// implementing the <see cref="IExpiringProtocolMessage"/> interface. + /// </summary> + internal class StandardExpirationBindingElement : IChannelBindingElement { + /// <summary> + /// The default maximum message age to use if the default constructor is called. + /// </summary> + internal static readonly TimeSpan DefaultMaximumMessageAge = TimeSpan.FromMinutes(13); + + /// <summary> + /// Initializes a new instance of the <see cref="StandardExpirationBindingElement"/> class + /// with a default maximum message lifetime of 13 minutes. + /// </summary> + internal StandardExpirationBindingElement() + : this(DefaultMaximumMessageAge) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="StandardExpirationBindingElement"/> class. + /// </summary> + /// <param name="maximumAge"> + /// <para>The maximum age a message implementing the + /// <see cref="IExpiringProtocolMessage"/> interface can be before + /// being discarded as too old.</para> + /// <para>This time limit should take into account expected time skew for servers + /// across the Internet. For example, if a server could conceivably have its + /// clock d = 5 minutes off UTC time, then any two servers could have + /// their clocks disagree by as much as 2*d = 10 minutes. + /// If a message should live for at least t = 3 minutes, + /// this property should be set to (2*d + t) = 13 minutes.</para> + /// </param> + internal StandardExpirationBindingElement(TimeSpan maximumAge) { + this.MaximumMessageAge = maximumAge; + } + + #region IChannelBindingElement Properties + + /// <summary> + /// Gets the protection offered by this binding element. + /// </summary> + /// <value><see cref="MessageProtections.Expiration"/></value> + MessageProtections IChannelBindingElement.Protection { + get { return MessageProtections.Expiration; } + } + + #endregion + + /// <summary> + /// Gets the maximum age a message implementing the + /// <see cref="IExpiringProtocolMessage"/> interface can be before + /// being discarded as too old. + /// </summary> + protected internal TimeSpan MaximumMessageAge { + get; + private set; + } + + #region IChannelBindingElement Methods + + /// <summary> + /// Sets the timestamp on an outgoing message. + /// </summary> + /// <param name="message">The outgoing message.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False otherwise. + /// </returns> + bool IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) { + IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage; + if (expiringMessage != null) { + expiringMessage.UtcCreationDate = DateTime.UtcNow; + return true; + } + + return false; + } + + /// <summary> + /// Reads the timestamp on a message and throws an exception if the message is too old. + /// </summary> + /// <param name="message">The incoming message.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False if the operation did not apply to this message. + /// </returns> + /// <exception cref="ExpiredMessageException">Thrown if the given message has already expired.</exception> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + bool IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) { + IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage; + if (expiringMessage != null) { + // Yes the UtcCreationDate is supposed to always be in UTC already, + // but just in case a given message failed to guarantee that, we do it here. + DateTime expirationDate = expiringMessage.UtcCreationDate.ToUniversalTime() + this.MaximumMessageAge; + if (expirationDate < DateTime.UtcNow) { + throw new ExpiredMessageException(expirationDate, expiringMessage); + } + + return true; + } + + return false; + } + + #endregion + } +} diff --git a/src/DotNetOAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs b/src/DotNetOpenAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs index b97b25e..9c80555 100644 --- a/src/DotNetOAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs +++ b/src/DotNetOpenAuth/Messaging/Bindings/StandardReplayProtectionBindingElement.cs @@ -1,135 +1,135 @@ -//-----------------------------------------------------------------------
-// <copyright file="StandardReplayProtectionBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Bindings {
- using System;
- using System.Diagnostics;
-
- /// <summary>
- /// A binding element that checks/verifies a nonce message part.
- /// </summary>
- internal class StandardReplayProtectionBindingElement : IChannelBindingElement {
- /// <summary>
- /// These are the characters that may be chosen from when forming a random nonce.
- /// </summary>
- private const string AllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
-
- /// <summary>
- /// The persistent store for nonces received.
- /// </summary>
- private INonceStore nonceStore;
-
- /// <summary>
- /// The length of generated nonces.
- /// </summary>
- private int nonceLength = 8;
-
- /// <summary>
- /// A random number generator.
- /// </summary>
- private Random generator = new Random();
-
- /// <summary>
- /// Initializes a new instance of the <see cref="StandardReplayProtectionBindingElement"/> class.
- /// </summary>
- /// <param name="nonceStore">The store where nonces will be persisted and checked.</param>
- internal StandardReplayProtectionBindingElement(INonceStore nonceStore) {
- if (nonceStore == null) {
- throw new ArgumentNullException("nonceStore");
- }
-
- this.nonceStore = nonceStore;
- }
-
- #region IChannelBindingElement Properties
-
- /// <summary>
- /// Gets the protection that this binding element provides messages.
- /// </summary>
- public MessageProtections Protection {
- get { return MessageProtections.ReplayProtection; }
- }
-
- #endregion
-
- /// <summary>
- /// Gets or sets the strength of the nonce, which is measured by the number of
- /// nonces that could theoretically be generated.
- /// </summary>
- /// <remarks>
- /// The strength of the nonce is equal to the number of characters that might appear
- /// in the nonce to the power of the length of the nonce.
- /// </remarks>
- internal double NonceStrength {
- get {
- return Math.Pow(AllowedCharacters.Length, this.nonceLength);
- }
-
- set {
- value = Math.Max(value, AllowedCharacters.Length);
- this.nonceLength = (int)Math.Log(value, AllowedCharacters.Length);
- Debug.Assert(this.nonceLength > 0, "Nonce length calculated to be below 1!");
- }
- }
-
- #region IChannelBindingElement Methods
-
- /// <summary>
- /// Applies a nonce to the message.
- /// </summary>
- /// <param name="message">The message to apply replay protection to.</param>
- /// <returns>True if the message protection was applied. False otherwise.</returns>
- public bool PrepareMessageForSending(IProtocolMessage message) {
- IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage;
- if (nonceMessage != null) {
- nonceMessage.Nonce = this.GenerateUniqueFragment();
- return true;
- }
-
- return false;
- }
-
- /// <summary>
- /// Verifies that the nonce in an incoming message has not been seen before.
- /// </summary>
- /// <param name="message">The incoming message.</param>
- /// <returns>
- /// True if the message nonce passed replay detection checks.
- /// False if the message did not have a nonce that could be checked at all.
- /// </returns>
- /// <exception cref="ReplayedMessageException">Thrown when the nonce check revealed a replayed message.</exception>
- public bool PrepareMessageForReceiving(IProtocolMessage message) {
- IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage;
- if (nonceMessage != null) {
- if (nonceMessage.Nonce == null || nonceMessage.Nonce.Length <= 0) {
- throw new ProtocolException(MessagingStrings.InvalidNonceReceived);
- }
-
- if (!this.nonceStore.StoreNonce(nonceMessage.Nonce, nonceMessage.UtcCreationDate)) {
- throw new ReplayedMessageException(message);
- }
-
- return true;
- }
-
- return false;
- }
-
- #endregion
-
- /// <summary>
- /// Generates a string of random characters for use as a nonce.
- /// </summary>
- /// <returns>The nonce string.</returns>
- private string GenerateUniqueFragment() {
- char[] nonce = new char[this.nonceLength];
- for (int i = 0; i < nonce.Length; i++) {
- nonce[i] = AllowedCharacters[this.generator.Next(AllowedCharacters.Length)];
- }
- return new string(nonce);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="StandardReplayProtectionBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + using System.Diagnostics; + + /// <summary> + /// A binding element that checks/verifies a nonce message part. + /// </summary> + internal class StandardReplayProtectionBindingElement : IChannelBindingElement { + /// <summary> + /// These are the characters that may be chosen from when forming a random nonce. + /// </summary> + private const string AllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + /// <summary> + /// The persistent store for nonces received. + /// </summary> + private INonceStore nonceStore; + + /// <summary> + /// The length of generated nonces. + /// </summary> + private int nonceLength = 8; + + /// <summary> + /// A random number generator. + /// </summary> + private Random generator = new Random(); + + /// <summary> + /// Initializes a new instance of the <see cref="StandardReplayProtectionBindingElement"/> class. + /// </summary> + /// <param name="nonceStore">The store where nonces will be persisted and checked.</param> + internal StandardReplayProtectionBindingElement(INonceStore nonceStore) { + if (nonceStore == null) { + throw new ArgumentNullException("nonceStore"); + } + + this.nonceStore = nonceStore; + } + + #region IChannelBindingElement Properties + + /// <summary> + /// Gets the protection that this binding element provides messages. + /// </summary> + public MessageProtections Protection { + get { return MessageProtections.ReplayProtection; } + } + + #endregion + + /// <summary> + /// Gets or sets the strength of the nonce, which is measured by the number of + /// nonces that could theoretically be generated. + /// </summary> + /// <remarks> + /// The strength of the nonce is equal to the number of characters that might appear + /// in the nonce to the power of the length of the nonce. + /// </remarks> + internal double NonceStrength { + get { + return Math.Pow(AllowedCharacters.Length, this.nonceLength); + } + + set { + value = Math.Max(value, AllowedCharacters.Length); + this.nonceLength = (int)Math.Log(value, AllowedCharacters.Length); + Debug.Assert(this.nonceLength > 0, "Nonce length calculated to be below 1!"); + } + } + + #region IChannelBindingElement Methods + + /// <summary> + /// Applies a nonce to the message. + /// </summary> + /// <param name="message">The message to apply replay protection to.</param> + /// <returns>True if the message protection was applied. False otherwise.</returns> + public bool PrepareMessageForSending(IProtocolMessage message) { + IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage; + if (nonceMessage != null) { + nonceMessage.Nonce = this.GenerateUniqueFragment(); + return true; + } + + return false; + } + + /// <summary> + /// Verifies that the nonce in an incoming message has not been seen before. + /// </summary> + /// <param name="message">The incoming message.</param> + /// <returns> + /// True if the message nonce passed replay detection checks. + /// False if the message did not have a nonce that could be checked at all. + /// </returns> + /// <exception cref="ReplayedMessageException">Thrown when the nonce check revealed a replayed message.</exception> + public bool PrepareMessageForReceiving(IProtocolMessage message) { + IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage; + if (nonceMessage != null) { + if (nonceMessage.Nonce == null || nonceMessage.Nonce.Length <= 0) { + throw new ProtocolException(MessagingStrings.InvalidNonceReceived); + } + + if (!this.nonceStore.StoreNonce(nonceMessage.Nonce, nonceMessage.UtcCreationDate)) { + throw new ReplayedMessageException(message); + } + + return true; + } + + return false; + } + + #endregion + + /// <summary> + /// Generates a string of random characters for use as a nonce. + /// </summary> + /// <returns>The nonce string.</returns> + private string GenerateUniqueFragment() { + char[] nonce = new char[this.nonceLength]; + for (int i = 0; i < nonce.Length; i++) { + nonce[i] = AllowedCharacters[this.generator.Next(AllowedCharacters.Length)]; + } + return new string(nonce); + } + } +} diff --git a/src/DotNetOAuth/Messaging/Channel.cs b/src/DotNetOpenAuth/Messaging/Channel.cs index 0f2fe04..a4ec142 100644 --- a/src/DotNetOAuth/Messaging/Channel.cs +++ b/src/DotNetOpenAuth/Messaging/Channel.cs @@ -1,693 +1,693 @@ -//-----------------------------------------------------------------------
-// <copyright file="Channel.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Diagnostics;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Web;
- using DotNetOAuth.Messaging.Reflection;
-
- /// <summary>
- /// Manages sending direct messages to a remote party and receiving responses.
- /// </summary>
- public abstract class Channel {
- /// <summary>
- /// The maximum allowable size for a 301 Redirect response before we send
- /// a 200 OK response with a scripted form POST with the parameters instead
- /// in order to ensure successfully sending a large payload to another server
- /// that might have a maximum allowable size restriction on its GET request.
- /// </summary>
- private static int indirectMessageGetToPostThreshold = 2 * 1024; // 2KB, recommended by OpenID group
-
- /// <summary>
- /// The template for indirect messages that require form POST to forward through the user agent.
- /// </summary>
- /// <remarks>
- /// We are intentionally using " instead of the html single quote ' below because
- /// the HtmlEncode'd values that we inject will only escape the double quote, so
- /// only the double-quote used around these values is safe.
- /// </remarks>
- private static string indirectMessageFormPostFormat = @"
-<html>
-<body onload=""var btn = document.getElementById('submit_button'); btn.disabled = true; btn.value = 'Login in progress'; document.getElementById('openid_message').submit()"">
-<form id=""openid_message"" action=""{0}"" method=""post"" accept-charset=""UTF-8"" enctype=""application/x-www-form-urlencoded"" onSubmit=""var btn = document.getElementById('submit_button'); btn.disabled = true; btn.value = 'Login in progress'; return true;"">
-{1}
- <input id=""submit_button"" type=""submit"" value=""Continue"" />
-</form>
-</body>
-</html>
-";
-
- /// <summary>
- /// A tool that can figure out what kind of message is being received
- /// so it can be deserialized.
- /// </summary>
- private IMessageTypeProvider messageTypeProvider;
-
- /// <summary>
- /// A list of binding elements in the order they must be applied to outgoing messages.
- /// </summary>
- /// <remarks>
- /// Incoming messages should have the binding elements applied in reverse order.
- /// </remarks>
- [DebuggerBrowsable(DebuggerBrowsableState.Never)]
- private List<IChannelBindingElement> bindingElements = new List<IChannelBindingElement>();
-
- /// <summary>
- /// Initializes a new instance of the <see cref="Channel"/> class.
- /// </summary>
- /// <param name="messageTypeProvider">
- /// A class prepared to analyze incoming messages and indicate what concrete
- /// message types can deserialize from it.
- /// </param>
- /// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param>
- protected Channel(IMessageTypeProvider messageTypeProvider, params IChannelBindingElement[] bindingElements) {
- if (messageTypeProvider == null) {
- throw new ArgumentNullException("messageTypeProvider");
- }
-
- this.messageTypeProvider = messageTypeProvider;
- this.bindingElements = new List<IChannelBindingElement>(ValidateAndPrepareBindingElements(bindingElements));
- }
-
- /// <summary>
- /// An event fired whenever a message is about to be encoded and sent.
- /// </summary>
- internal event EventHandler<ChannelEventArgs> Sending;
-
- /// <summary>
- /// Gets the binding elements used by this channel, in the order they are applied to outgoing messages.
- /// </summary>
- /// <remarks>
- /// Incoming messages are processed by this binding elements in the reverse order.
- /// </remarks>
- protected internal ReadOnlyCollection<IChannelBindingElement> BindingElements {
- get {
- return this.bindingElements.AsReadOnly();
- }
- }
-
- /// <summary>
- /// Gets a tool that can figure out what kind of message is being received
- /// so it can be deserialized.
- /// </summary>
- protected IMessageTypeProvider MessageTypeProvider {
- get { return this.messageTypeProvider; }
- }
-
- /// <summary>
- /// Queues an indirect message (either a request or response)
- /// or direct message response for transmission to a remote party.
- /// </summary>
- /// <param name="message">The one-way message to send</param>
- /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
- public Response Send(IProtocolMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
- this.PrepareMessageForSending(message);
- Logger.DebugFormat("Sending message: {0}", message);
-
- switch (message.Transport) {
- case MessageTransport.Direct:
- // This is a response to a direct message.
- return this.SendDirectMessageResponse(message);
- case MessageTransport.Indirect:
- var directedMessage = message as IDirectedProtocolMessage;
- if (directedMessage == null) {
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.IndirectMessagesMustImplementIDirectedProtocolMessage,
- typeof(IDirectedProtocolMessage).FullName),
- "message");
- }
- if (directedMessage.Recipient == null) {
- throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "message");
- }
- return this.SendIndirectMessage(directedMessage);
- default:
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.UnrecognizedEnumValue,
- "Transport",
- message.Transport),
- "message");
- }
- }
-
- /// <summary>
- /// Gets the protocol message embedded in the given HTTP request, if present.
- /// </summary>
- /// <returns>The deserialized message, if one is found. Null otherwise.</returns>
- /// <remarks>
- /// Requires an HttpContext.Current context.
- /// </remarks>
- /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception>
- public IProtocolMessage ReadFromRequest() {
- return this.ReadFromRequest(this.GetRequestFromContext());
- }
-
- /// <summary>
- /// Gets the protocol message embedded in the given HTTP request, if present.
- /// </summary>
- /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam>
- /// <param name="request">The deserialized message, if one is found. Null otherwise.</param>
- /// <returns>True if the expected message was recognized and deserialized. False otherwise.</returns>
- /// <remarks>
- /// Requires an HttpContext.Current context.
- /// </remarks>
- /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception>
- /// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception>
- public bool TryReadFromRequest<TREQUEST>(out TREQUEST request)
- where TREQUEST : class, IProtocolMessage {
- return TryReadFromRequest<TREQUEST>(this.GetRequestFromContext(), out request);
- }
-
- /// <summary>
- /// Gets the protocol message embedded in the given HTTP request, if present.
- /// </summary>
- /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam>
- /// <param name="httpRequest">The request to search for an embedded message.</param>
- /// <param name="request">The deserialized message, if one is found. Null otherwise.</param>
- /// <returns>True if the expected message was recognized and deserialized. False otherwise.</returns>
- /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception>
- /// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception>
- public bool TryReadFromRequest<TREQUEST>(HttpRequestInfo httpRequest, out TREQUEST request)
- where TREQUEST : class, IProtocolMessage {
- IProtocolMessage untypedRequest = this.ReadFromRequest(httpRequest);
- if (untypedRequest == null) {
- request = null;
- return false;
- }
-
- request = untypedRequest as TREQUEST;
- if (request == null) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.UnexpectedMessageReceived,
- typeof(TREQUEST),
- untypedRequest.GetType()));
- }
-
- return true;
- }
-
- /// <summary>
- /// Gets the protocol message embedded in the given HTTP request, if present.
- /// </summary>
- /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam>
- /// <returns>The deserialized message.</returns>
- /// <remarks>
- /// Requires an HttpContext.Current context.
- /// </remarks>
- /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception>
- /// <exception cref="ProtocolException">Thrown if the expected message was not recognized in the response.</exception>
- public TREQUEST ReadFromRequest<TREQUEST>()
- where TREQUEST : class, IProtocolMessage {
- return this.ReadFromRequest<TREQUEST>(this.GetRequestFromContext());
- }
-
- /// <summary>
- /// Gets the protocol message that may be embedded in the given HTTP request.
- /// </summary>
- /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam>
- /// <param name="httpRequest">The request to search for an embedded message.</param>
- /// <returns>The deserialized message, if one is found. Null otherwise.</returns>
- /// <exception cref="ProtocolException">Thrown if the expected message was not recognized in the response.</exception>
- public TREQUEST ReadFromRequest<TREQUEST>(HttpRequestInfo httpRequest)
- where TREQUEST : class, IProtocolMessage {
- TREQUEST request;
- if (this.TryReadFromRequest<TREQUEST>(httpRequest, out request)) {
- return request;
- } else {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.ExpectedMessageNotReceived,
- typeof(TREQUEST)));
- }
- }
-
- /// <summary>
- /// Gets the protocol message that may be embedded in the given HTTP request.
- /// </summary>
- /// <param name="httpRequest">The request to search for an embedded message.</param>
- /// <returns>The deserialized message, if one is found. Null otherwise.</returns>
- public IProtocolMessage ReadFromRequest(HttpRequestInfo httpRequest) {
- IProtocolMessage requestMessage = this.ReadFromRequestInternal(httpRequest);
- if (requestMessage != null) {
- Logger.DebugFormat("Incoming request received: {0}", requestMessage);
- this.VerifyMessageAfterReceiving(requestMessage);
- }
-
- return requestMessage;
- }
-
- /// <summary>
- /// Sends a direct message to a remote party and waits for the response.
- /// </summary>
- /// <typeparam name="TRESPONSE">The expected type of the message to be received.</typeparam>
- /// <param name="request">The message to send.</param>
- /// <returns>The remote party's response.</returns>
- /// <exception cref="ProtocolException">
- /// Thrown if no message is recognized in the response
- /// or an unexpected type of message is received.
- /// </exception>
- public TRESPONSE Request<TRESPONSE>(IDirectedProtocolMessage request)
- where TRESPONSE : class, IProtocolMessage {
- IProtocolMessage response = this.Request(request);
- if (response == null) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.ExpectedMessageNotReceived,
- typeof(TRESPONSE)));
- }
-
- var expectedResponse = response as TRESPONSE;
- if (expectedResponse == null) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.UnexpectedMessageReceived,
- typeof(TRESPONSE),
- response.GetType()));
- }
-
- return expectedResponse;
- }
-
- /// <summary>
- /// Sends a direct message to a remote party and waits for the response.
- /// </summary>
- /// <param name="request">The message to send.</param>
- /// <returns>The remote party's response.</returns>
- public IProtocolMessage Request(IDirectedProtocolMessage request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- this.PrepareMessageForSending(request);
- Logger.DebugFormat("Sending request: {0}", request);
- IProtocolMessage response = this.RequestInternal(request);
- if (response != null) {
- Logger.DebugFormat("Received response: {0}", response);
- this.VerifyMessageAfterReceiving(response);
- }
-
- return response;
- }
-
- /// <summary>
- /// Gets the current HTTP request being processed.
- /// </summary>
- /// <returns>The HttpRequestInfo for the current request.</returns>
- /// <remarks>
- /// Requires an HttpContext.Current context.
- /// </remarks>
- /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception>
- protected internal virtual HttpRequestInfo GetRequestFromContext() {
- if (HttpContext.Current == null) {
- throw new InvalidOperationException(MessagingStrings.HttpContextRequired);
- }
-
- return new HttpRequestInfo(HttpContext.Current.Request);
- }
-
- /// <summary>
- /// Fires the <see cref="Sending"/> event.
- /// </summary>
- /// <param name="message">The message about to be encoded and sent.</param>
- protected virtual void OnSending(IProtocolMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- var sending = this.Sending;
- if (sending != null) {
- sending(this, new ChannelEventArgs(message));
- }
- }
-
- /// <summary>
- /// Gets the protocol message that may be embedded in the given HTTP request.
- /// </summary>
- /// <param name="request">The request to search for an embedded message.</param>
- /// <returns>The deserialized message, if one is found. Null otherwise.</returns>
- protected virtual IProtocolMessage ReadFromRequestInternal(HttpRequestInfo request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- // Search Form data first, and if nothing is there search the QueryString
- var fields = request.Form.ToDictionary();
- if (fields.Count == 0) {
- fields = request.QueryString.ToDictionary();
- }
-
- return this.Receive(fields, request.GetRecipient());
- }
-
- /// <summary>
- /// Deserializes a dictionary of values into a message.
- /// </summary>
- /// <param name="fields">The dictionary of values that were read from an HTTP request or response.</param>
- /// <param name="recipient">Information about where the message was been directed. Null for direct response messages.</param>
- /// <returns>The deserialized message, or null if no message could be recognized in the provided data.</returns>
- protected virtual IProtocolMessage Receive(Dictionary<string, string> fields, MessageReceivingEndpoint recipient) {
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- Type messageType = this.MessageTypeProvider.GetRequestMessageType(fields);
-
- // If there was no data, or we couldn't recognize it as a message, abort.
- if (messageType == null) {
- return null;
- }
-
- // We have a message! Assemble it.
- var serializer = MessageSerializer.Get(messageType);
- IProtocolMessage message = serializer.Deserialize(fields, recipient);
-
- return message;
- }
-
- /// <summary>
- /// Queues an indirect message for transmittal via the user agent.
- /// </summary>
- /// <param name="message">The message to send.</param>
- /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
- protected virtual Response SendIndirectMessage(IDirectedProtocolMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- var serializer = MessageSerializer.Get(message.GetType());
- var fields = serializer.Serialize(message);
- Response response;
- if (CalculateSizeOfPayload(fields) > indirectMessageGetToPostThreshold) {
- response = this.CreateFormPostResponse(message, fields);
- } else {
- response = this.Create301RedirectResponse(message, fields);
- }
-
- return response;
- }
-
- /// <summary>
- /// Encodes an HTTP response that will instruct the user agent to forward a message to
- /// some remote third party using a 301 Redirect GET method.
- /// </summary>
- /// <param name="message">The message to forward.</param>
- /// <param name="fields">The pre-serialized fields from the message.</param>
- /// <returns>The encoded HTTP response.</returns>
- protected virtual Response Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
- if (message.Recipient == null) {
- throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "message");
- }
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- WebHeaderCollection headers = new WebHeaderCollection();
- UriBuilder builder = new UriBuilder(message.Recipient);
- MessagingUtilities.AppendQueryArgs(builder, fields);
- headers.Add(HttpResponseHeader.Location, builder.Uri.AbsoluteUri);
- Logger.DebugFormat("Redirecting to {0}", builder.Uri.AbsoluteUri);
- Response response = new Response {
- Status = HttpStatusCode.Redirect,
- Headers = headers,
- Body = null,
- OriginalMessage = message
- };
-
- return response;
- }
-
- /// <summary>
- /// Encodes an HTTP response that will instruct the user agent to forward a message to
- /// some remote third party using a form POST method.
- /// </summary>
- /// <param name="message">The message to forward.</param>
- /// <param name="fields">The pre-serialized fields from the message.</param>
- /// <returns>The encoded HTTP response.</returns>
- protected virtual Response CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
- if (message.Recipient == null) {
- throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "message");
- }
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- WebHeaderCollection headers = new WebHeaderCollection();
- StringWriter bodyWriter = new StringWriter(CultureInfo.InvariantCulture);
- StringBuilder hiddenFields = new StringBuilder();
- foreach (var field in fields) {
- hiddenFields.AppendFormat(
- "\t<input type=\"hidden\" name=\"{0}\" value=\"{1}\" />\r\n",
- HttpUtility.HtmlEncode(field.Key),
- HttpUtility.HtmlEncode(field.Value));
- }
- bodyWriter.WriteLine(
- indirectMessageFormPostFormat,
- HttpUtility.HtmlEncode(message.Recipient.AbsoluteUri),
- hiddenFields);
- bodyWriter.Flush();
- Response response = new Response {
- Status = HttpStatusCode.OK,
- Headers = headers,
- Body = bodyWriter.ToString(),
- OriginalMessage = message
- };
-
- return response;
- }
-
- /// <summary>
- /// Gets the protocol message that may be in the given HTTP response stream.
- /// </summary>
- /// <param name="responseStream">The response that is anticipated to contain an OAuth message.</param>
- /// <returns>The deserialized message, if one is found. Null otherwise.</returns>
- protected abstract IProtocolMessage ReadFromResponseInternal(Stream responseStream);
-
- /// <summary>
- /// Sends a direct message to a remote party and waits for the response.
- /// </summary>
- /// <param name="request">The message to send.</param>
- /// <returns>The remote party's response.</returns>
- protected abstract IProtocolMessage RequestInternal(IDirectedProtocolMessage request);
-
- /// <summary>
- /// Queues a message for sending in the response stream where the fields
- /// are sent in the response stream in querystring style.
- /// </summary>
- /// <param name="response">The message to send as a response.</param>
- /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
- /// <remarks>
- /// This method implements spec V1.0 section 5.3.
- /// </remarks>
- protected abstract Response SendDirectMessageResponse(IProtocolMessage response);
-
- /// <summary>
- /// Prepares a message for transmit by applying signatures, nonces, etc.
- /// </summary>
- /// <param name="message">The message to prepare for sending.</param>
- /// <remarks>
- /// This method should NOT be called by derived types
- /// except when sending ONE WAY request messages.
- /// </remarks>
- protected void PrepareMessageForSending(IProtocolMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- this.OnSending(message);
-
- MessageProtections appliedProtection = MessageProtections.None;
- foreach (IChannelBindingElement bindingElement in this.bindingElements) {
- if (bindingElement.PrepareMessageForSending(message)) {
- appliedProtection |= bindingElement.Protection;
- }
- }
-
- // Ensure that the message's protection requirements have been satisfied.
- if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection) {
- throw new UnprotectedMessageException(message, appliedProtection);
- }
-
- EnsureValidMessageParts(message);
- message.EnsureValidMessage();
- }
-
- /// <summary>
- /// Verifies that all required message parts are initialized to values
- /// prior to sending the message to a remote party.
- /// </summary>
- /// <param name="message">The message to verify.</param>
- /// <exception cref="ProtocolException">
- /// Thrown when any required message part does not have a value.
- /// </exception>
- private static void EnsureValidMessageParts(IProtocolMessage message) {
- Debug.Assert(message != null, "message == null");
-
- MessageDictionary dictionary = new MessageDictionary(message);
- MessageDescription description = MessageDescription.Get(message.GetType());
- description.EnsureRequiredMessagePartsArePresent(dictionary.Keys);
- }
-
- /// <summary>
- /// Calculates a fairly accurate estimation on the size of a message that contains
- /// a given set of fields.
- /// </summary>
- /// <param name="fields">The fields that would be included in a message.</param>
- /// <returns>The size (in bytes) of the message payload.</returns>
- private static int CalculateSizeOfPayload(IDictionary<string, string> fields) {
- Debug.Assert(fields != null, "fields == null");
-
- int size = 0;
- foreach (var field in fields) {
- size += field.Key.Length;
- size += field.Value.Length;
- size += 2; // & and =
- }
- return size;
- }
-
- /// <summary>
- /// Ensures a consistent and secure set of binding elements and
- /// sorts them as necessary for a valid sequence of operations.
- /// </summary>
- /// <param name="elements">The binding elements provided to the channel.</param>
- /// <returns>The properly ordered list of elements.</returns>
- /// <exception cref="ProtocolException">Thrown when the binding elements are incomplete or inconsistent with each other.</exception>
- private static IEnumerable<IChannelBindingElement> ValidateAndPrepareBindingElements(IEnumerable<IChannelBindingElement> elements) {
- if (elements == null) {
- return new IChannelBindingElement[0];
- }
- if (elements.Contains(null)) {
- throw new ArgumentException(MessagingStrings.SequenceContainsNullElement, "elements");
- }
-
- // Filter the elements between the mere transforming ones and the protection ones.
- var transformationElements = new List<IChannelBindingElement>(
- elements.Where(element => element.Protection == MessageProtections.None));
- var protectionElements = new List<IChannelBindingElement>(
- elements.Where(element => element.Protection != MessageProtections.None));
-
- bool wasLastProtectionPresent = true;
- foreach (MessageProtections protectionKind in Enum.GetValues(typeof(MessageProtections))) {
- if (protectionKind == MessageProtections.None) {
- continue;
- }
-
- int countProtectionsOfThisKind = protectionElements.Count(element => (element.Protection & protectionKind) == protectionKind);
-
- // Each protection binding element is backed by the presence of its dependent protection(s).
- if (countProtectionsOfThisKind > 0 && !wasLastProtectionPresent) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.RequiredProtectionMissing,
- protectionKind));
- }
-
- // At most one binding element for each protection type.
- if (countProtectionsOfThisKind > 1) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.TooManyBindingsOfferingSameProtection,
- protectionKind,
- countProtectionsOfThisKind));
- }
- wasLastProtectionPresent = countProtectionsOfThisKind > 0;
- }
-
- // Put the binding elements in order so they are correctly applied to outgoing messages.
- // Start with the transforming (non-protecting) binding elements first and preserve their original order.
- var orderedList = new List<IChannelBindingElement>(transformationElements);
-
- // Now sort the protection binding elements among themselves and add them to the list.
- orderedList.AddRange(protectionElements.OrderBy(element => element.Protection, BindingElementOutgoingMessageApplicationOrder));
- return orderedList;
- }
-
- /// <summary>
- /// Puts binding elements in their correct outgoing message processing order.
- /// </summary>
- /// <param name="protection1">The first protection type to compare.</param>
- /// <param name="protection2">The second protection type to compare.</param>
- /// <returns>
- /// -1 if <paramref name="element1"/> should be applied to an outgoing message before <paramref name="element2"/>.
- /// 1 if <paramref name="element2"/> should be applied to an outgoing message before <paramref name="element1"/>.
- /// 0 if it doesn't matter.
- /// </returns>
- private static int BindingElementOutgoingMessageApplicationOrder(MessageProtections protection1, MessageProtections protection2) {
- Debug.Assert(protection1 != MessageProtections.None || protection2 != MessageProtections.None, "This comparison function should only be used to compare protection binding elements. Otherwise we change the order of user-defined message transformations.");
-
- // Now put the protection ones in the right order.
- return -((int)protection1).CompareTo((int)protection2); // descending flag ordinal order
- }
-
- /// <summary>
- /// Gets the protocol message that may be in the given HTTP response stream.
- /// </summary>
- /// <param name="responseStream">The response that is anticipated to contain an OAuth message.</param>
- /// <returns>The deserialized message, if one is found. Null otherwise.</returns>
- private IProtocolMessage ReadFromResponse(Stream responseStream) {
- IProtocolMessage message = this.ReadFromResponseInternal(responseStream);
- Logger.DebugFormat("Received message response: {0}", message);
- this.VerifyMessageAfterReceiving(message);
- return message;
- }
-
- /// <summary>
- /// Verifies the integrity and applicability of an incoming message.
- /// </summary>
- /// <param name="message">The message just received.</param>
- /// <exception cref="ProtocolException">
- /// Thrown when the message is somehow invalid.
- /// This can be due to tampering, replay attack or expiration, among other things.
- /// </exception>
- private void VerifyMessageAfterReceiving(IProtocolMessage message) {
- Debug.Assert(message != null, "message == null");
-
- MessageProtections appliedProtection = MessageProtections.None;
- foreach (IChannelBindingElement bindingElement in this.bindingElements.Reverse<IChannelBindingElement>()) {
- if (bindingElement.PrepareMessageForReceiving(message)) {
- appliedProtection |= bindingElement.Protection;
- }
- }
-
- // Ensure that the message's protection requirements have been satisfied.
- if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection) {
- throw new UnprotectedMessageException(message, appliedProtection);
- }
-
- // We do NOT verify that all required message parts are present here... the
- // message deserializer did for us. It would be too late to do it here since
- // they might look initialized by the time we have an IProtocolMessage instance.
- message.EnsureValidMessage();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="Channel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using DotNetOpenAuth.Messaging.Reflection; + + /// <summary> + /// Manages sending direct messages to a remote party and receiving responses. + /// </summary> + public abstract class Channel { + /// <summary> + /// The maximum allowable size for a 301 Redirect response before we send + /// a 200 OK response with a scripted form POST with the parameters instead + /// in order to ensure successfully sending a large payload to another server + /// that might have a maximum allowable size restriction on its GET request. + /// </summary> + private static int indirectMessageGetToPostThreshold = 2 * 1024; // 2KB, recommended by OpenID group + + /// <summary> + /// The template for indirect messages that require form POST to forward through the user agent. + /// </summary> + /// <remarks> + /// We are intentionally using " instead of the html single quote ' below because + /// the HtmlEncode'd values that we inject will only escape the double quote, so + /// only the double-quote used around these values is safe. + /// </remarks> + private static string indirectMessageFormPostFormat = @" +<html> +<body onload=""var btn = document.getElementById('submit_button'); btn.disabled = true; btn.value = 'Login in progress'; document.getElementById('openid_message').submit()""> +<form id=""openid_message"" action=""{0}"" method=""post"" accept-charset=""UTF-8"" enctype=""application/x-www-form-urlencoded"" onSubmit=""var btn = document.getElementById('submit_button'); btn.disabled = true; btn.value = 'Login in progress'; return true;""> +{1} + <input id=""submit_button"" type=""submit"" value=""Continue"" /> +</form> +</body> +</html> +"; + + /// <summary> + /// A tool that can figure out what kind of message is being received + /// so it can be deserialized. + /// </summary> + private IMessageTypeProvider messageTypeProvider; + + /// <summary> + /// A list of binding elements in the order they must be applied to outgoing messages. + /// </summary> + /// <remarks> + /// Incoming messages should have the binding elements applied in reverse order. + /// </remarks> + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private List<IChannelBindingElement> bindingElements = new List<IChannelBindingElement>(); + + /// <summary> + /// Initializes a new instance of the <see cref="Channel"/> class. + /// </summary> + /// <param name="messageTypeProvider"> + /// A class prepared to analyze incoming messages and indicate what concrete + /// message types can deserialize from it. + /// </param> + /// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param> + protected Channel(IMessageTypeProvider messageTypeProvider, params IChannelBindingElement[] bindingElements) { + if (messageTypeProvider == null) { + throw new ArgumentNullException("messageTypeProvider"); + } + + this.messageTypeProvider = messageTypeProvider; + this.bindingElements = new List<IChannelBindingElement>(ValidateAndPrepareBindingElements(bindingElements)); + } + + /// <summary> + /// An event fired whenever a message is about to be encoded and sent. + /// </summary> + internal event EventHandler<ChannelEventArgs> Sending; + + /// <summary> + /// Gets the binding elements used by this channel, in the order they are applied to outgoing messages. + /// </summary> + /// <remarks> + /// Incoming messages are processed by this binding elements in the reverse order. + /// </remarks> + protected internal ReadOnlyCollection<IChannelBindingElement> BindingElements { + get { + return this.bindingElements.AsReadOnly(); + } + } + + /// <summary> + /// Gets a tool that can figure out what kind of message is being received + /// so it can be deserialized. + /// </summary> + protected IMessageTypeProvider MessageTypeProvider { + get { return this.messageTypeProvider; } + } + + /// <summary> + /// Queues an indirect message (either a request or response) + /// or direct message response for transmission to a remote party. + /// </summary> + /// <param name="message">The one-way message to send</param> + /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> + public Response Send(IProtocolMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + this.PrepareMessageForSending(message); + Logger.DebugFormat("Sending message: {0}", message); + + switch (message.Transport) { + case MessageTransport.Direct: + // This is a response to a direct message. + return this.SendDirectMessageResponse(message); + case MessageTransport.Indirect: + var directedMessage = message as IDirectedProtocolMessage; + if (directedMessage == null) { + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.IndirectMessagesMustImplementIDirectedProtocolMessage, + typeof(IDirectedProtocolMessage).FullName), + "message"); + } + if (directedMessage.Recipient == null) { + throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "message"); + } + return this.SendIndirectMessage(directedMessage); + default: + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.UnrecognizedEnumValue, + "Transport", + message.Transport), + "message"); + } + } + + /// <summary> + /// Gets the protocol message embedded in the given HTTP request, if present. + /// </summary> + /// <returns>The deserialized message, if one is found. Null otherwise.</returns> + /// <remarks> + /// Requires an HttpContext.Current context. + /// </remarks> + /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> + public IProtocolMessage ReadFromRequest() { + return this.ReadFromRequest(this.GetRequestFromContext()); + } + + /// <summary> + /// Gets the protocol message embedded in the given HTTP request, if present. + /// </summary> + /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam> + /// <param name="request">The deserialized message, if one is found. Null otherwise.</param> + /// <returns>True if the expected message was recognized and deserialized. False otherwise.</returns> + /// <remarks> + /// Requires an HttpContext.Current context. + /// </remarks> + /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> + /// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception> + public bool TryReadFromRequest<TREQUEST>(out TREQUEST request) + where TREQUEST : class, IProtocolMessage { + return TryReadFromRequest<TREQUEST>(this.GetRequestFromContext(), out request); + } + + /// <summary> + /// Gets the protocol message embedded in the given HTTP request, if present. + /// </summary> + /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam> + /// <param name="httpRequest">The request to search for an embedded message.</param> + /// <param name="request">The deserialized message, if one is found. Null otherwise.</param> + /// <returns>True if the expected message was recognized and deserialized. False otherwise.</returns> + /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> + /// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception> + public bool TryReadFromRequest<TREQUEST>(HttpRequestInfo httpRequest, out TREQUEST request) + where TREQUEST : class, IProtocolMessage { + IProtocolMessage untypedRequest = this.ReadFromRequest(httpRequest); + if (untypedRequest == null) { + request = null; + return false; + } + + request = untypedRequest as TREQUEST; + if (request == null) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.UnexpectedMessageReceived, + typeof(TREQUEST), + untypedRequest.GetType())); + } + + return true; + } + + /// <summary> + /// Gets the protocol message embedded in the given HTTP request, if present. + /// </summary> + /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam> + /// <returns>The deserialized message.</returns> + /// <remarks> + /// Requires an HttpContext.Current context. + /// </remarks> + /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> + /// <exception cref="ProtocolException">Thrown if the expected message was not recognized in the response.</exception> + public TREQUEST ReadFromRequest<TREQUEST>() + where TREQUEST : class, IProtocolMessage { + return this.ReadFromRequest<TREQUEST>(this.GetRequestFromContext()); + } + + /// <summary> + /// Gets the protocol message that may be embedded in the given HTTP request. + /// </summary> + /// <typeparam name="TREQUEST">The expected type of the message to be received.</typeparam> + /// <param name="httpRequest">The request to search for an embedded message.</param> + /// <returns>The deserialized message, if one is found. Null otherwise.</returns> + /// <exception cref="ProtocolException">Thrown if the expected message was not recognized in the response.</exception> + public TREQUEST ReadFromRequest<TREQUEST>(HttpRequestInfo httpRequest) + where TREQUEST : class, IProtocolMessage { + TREQUEST request; + if (this.TryReadFromRequest<TREQUEST>(httpRequest, out request)) { + return request; + } else { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.ExpectedMessageNotReceived, + typeof(TREQUEST))); + } + } + + /// <summary> + /// Gets the protocol message that may be embedded in the given HTTP request. + /// </summary> + /// <param name="httpRequest">The request to search for an embedded message.</param> + /// <returns>The deserialized message, if one is found. Null otherwise.</returns> + public IProtocolMessage ReadFromRequest(HttpRequestInfo httpRequest) { + IProtocolMessage requestMessage = this.ReadFromRequestInternal(httpRequest); + if (requestMessage != null) { + Logger.DebugFormat("Incoming request received: {0}", requestMessage); + this.VerifyMessageAfterReceiving(requestMessage); + } + + return requestMessage; + } + + /// <summary> + /// Sends a direct message to a remote party and waits for the response. + /// </summary> + /// <typeparam name="TRESPONSE">The expected type of the message to be received.</typeparam> + /// <param name="request">The message to send.</param> + /// <returns>The remote party's response.</returns> + /// <exception cref="ProtocolException"> + /// Thrown if no message is recognized in the response + /// or an unexpected type of message is received. + /// </exception> + public TRESPONSE Request<TRESPONSE>(IDirectedProtocolMessage request) + where TRESPONSE : class, IProtocolMessage { + IProtocolMessage response = this.Request(request); + if (response == null) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.ExpectedMessageNotReceived, + typeof(TRESPONSE))); + } + + var expectedResponse = response as TRESPONSE; + if (expectedResponse == null) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.UnexpectedMessageReceived, + typeof(TRESPONSE), + response.GetType())); + } + + return expectedResponse; + } + + /// <summary> + /// Sends a direct message to a remote party and waits for the response. + /// </summary> + /// <param name="request">The message to send.</param> + /// <returns>The remote party's response.</returns> + public IProtocolMessage Request(IDirectedProtocolMessage request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + this.PrepareMessageForSending(request); + Logger.DebugFormat("Sending request: {0}", request); + IProtocolMessage response = this.RequestInternal(request); + if (response != null) { + Logger.DebugFormat("Received response: {0}", response); + this.VerifyMessageAfterReceiving(response); + } + + return response; + } + + /// <summary> + /// Gets the current HTTP request being processed. + /// </summary> + /// <returns>The HttpRequestInfo for the current request.</returns> + /// <remarks> + /// Requires an HttpContext.Current context. + /// </remarks> + /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> + protected internal virtual HttpRequestInfo GetRequestFromContext() { + if (HttpContext.Current == null) { + throw new InvalidOperationException(MessagingStrings.HttpContextRequired); + } + + return new HttpRequestInfo(HttpContext.Current.Request); + } + + /// <summary> + /// Fires the <see cref="Sending"/> event. + /// </summary> + /// <param name="message">The message about to be encoded and sent.</param> + protected virtual void OnSending(IProtocolMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + var sending = this.Sending; + if (sending != null) { + sending(this, new ChannelEventArgs(message)); + } + } + + /// <summary> + /// Gets the protocol message that may be embedded in the given HTTP request. + /// </summary> + /// <param name="request">The request to search for an embedded message.</param> + /// <returns>The deserialized message, if one is found. Null otherwise.</returns> + protected virtual IProtocolMessage ReadFromRequestInternal(HttpRequestInfo request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + // Search Form data first, and if nothing is there search the QueryString + var fields = request.Form.ToDictionary(); + if (fields.Count == 0) { + fields = request.QueryString.ToDictionary(); + } + + return this.Receive(fields, request.GetRecipient()); + } + + /// <summary> + /// Deserializes a dictionary of values into a message. + /// </summary> + /// <param name="fields">The dictionary of values that were read from an HTTP request or response.</param> + /// <param name="recipient">Information about where the message was been directed. Null for direct response messages.</param> + /// <returns>The deserialized message, or null if no message could be recognized in the provided data.</returns> + protected virtual IProtocolMessage Receive(Dictionary<string, string> fields, MessageReceivingEndpoint recipient) { + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + Type messageType = this.MessageTypeProvider.GetRequestMessageType(fields); + + // If there was no data, or we couldn't recognize it as a message, abort. + if (messageType == null) { + return null; + } + + // We have a message! Assemble it. + var serializer = MessageSerializer.Get(messageType); + IProtocolMessage message = serializer.Deserialize(fields, recipient); + + return message; + } + + /// <summary> + /// Queues an indirect message for transmittal via the user agent. + /// </summary> + /// <param name="message">The message to send.</param> + /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> + protected virtual Response SendIndirectMessage(IDirectedProtocolMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + var serializer = MessageSerializer.Get(message.GetType()); + var fields = serializer.Serialize(message); + Response response; + if (CalculateSizeOfPayload(fields) > indirectMessageGetToPostThreshold) { + response = this.CreateFormPostResponse(message, fields); + } else { + response = this.Create301RedirectResponse(message, fields); + } + + return response; + } + + /// <summary> + /// Encodes an HTTP response that will instruct the user agent to forward a message to + /// some remote third party using a 301 Redirect GET method. + /// </summary> + /// <param name="message">The message to forward.</param> + /// <param name="fields">The pre-serialized fields from the message.</param> + /// <returns>The encoded HTTP response.</returns> + protected virtual Response Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) { + if (message == null) { + throw new ArgumentNullException("message"); + } + if (message.Recipient == null) { + throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "message"); + } + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + WebHeaderCollection headers = new WebHeaderCollection(); + UriBuilder builder = new UriBuilder(message.Recipient); + MessagingUtilities.AppendQueryArgs(builder, fields); + headers.Add(HttpResponseHeader.Location, builder.Uri.AbsoluteUri); + Logger.DebugFormat("Redirecting to {0}", builder.Uri.AbsoluteUri); + Response response = new Response { + Status = HttpStatusCode.Redirect, + Headers = headers, + Body = null, + OriginalMessage = message + }; + + return response; + } + + /// <summary> + /// Encodes an HTTP response that will instruct the user agent to forward a message to + /// some remote third party using a form POST method. + /// </summary> + /// <param name="message">The message to forward.</param> + /// <param name="fields">The pre-serialized fields from the message.</param> + /// <returns>The encoded HTTP response.</returns> + protected virtual Response CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) { + if (message == null) { + throw new ArgumentNullException("message"); + } + if (message.Recipient == null) { + throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "message"); + } + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + WebHeaderCollection headers = new WebHeaderCollection(); + StringWriter bodyWriter = new StringWriter(CultureInfo.InvariantCulture); + StringBuilder hiddenFields = new StringBuilder(); + foreach (var field in fields) { + hiddenFields.AppendFormat( + "\t<input type=\"hidden\" name=\"{0}\" value=\"{1}\" />\r\n", + HttpUtility.HtmlEncode(field.Key), + HttpUtility.HtmlEncode(field.Value)); + } + bodyWriter.WriteLine( + indirectMessageFormPostFormat, + HttpUtility.HtmlEncode(message.Recipient.AbsoluteUri), + hiddenFields); + bodyWriter.Flush(); + Response response = new Response { + Status = HttpStatusCode.OK, + Headers = headers, + Body = bodyWriter.ToString(), + OriginalMessage = message + }; + + return response; + } + + /// <summary> + /// Gets the protocol message that may be in the given HTTP response stream. + /// </summary> + /// <param name="responseStream">The response that is anticipated to contain an OAuth message.</param> + /// <returns>The deserialized message, if one is found. Null otherwise.</returns> + protected abstract IProtocolMessage ReadFromResponseInternal(Stream responseStream); + + /// <summary> + /// Sends a direct message to a remote party and waits for the response. + /// </summary> + /// <param name="request">The message to send.</param> + /// <returns>The remote party's response.</returns> + protected abstract IProtocolMessage RequestInternal(IDirectedProtocolMessage request); + + /// <summary> + /// Queues a message for sending in the response stream where the fields + /// are sent in the response stream in querystring style. + /// </summary> + /// <param name="response">The message to send as a response.</param> + /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> + /// <remarks> + /// This method implements spec V1.0 section 5.3. + /// </remarks> + protected abstract Response SendDirectMessageResponse(IProtocolMessage response); + + /// <summary> + /// Prepares a message for transmit by applying signatures, nonces, etc. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <remarks> + /// This method should NOT be called by derived types + /// except when sending ONE WAY request messages. + /// </remarks> + protected void PrepareMessageForSending(IProtocolMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + this.OnSending(message); + + MessageProtections appliedProtection = MessageProtections.None; + foreach (IChannelBindingElement bindingElement in this.bindingElements) { + if (bindingElement.PrepareMessageForSending(message)) { + appliedProtection |= bindingElement.Protection; + } + } + + // Ensure that the message's protection requirements have been satisfied. + if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection) { + throw new UnprotectedMessageException(message, appliedProtection); + } + + EnsureValidMessageParts(message); + message.EnsureValidMessage(); + } + + /// <summary> + /// Verifies that all required message parts are initialized to values + /// prior to sending the message to a remote party. + /// </summary> + /// <param name="message">The message to verify.</param> + /// <exception cref="ProtocolException"> + /// Thrown when any required message part does not have a value. + /// </exception> + private static void EnsureValidMessageParts(IProtocolMessage message) { + Debug.Assert(message != null, "message == null"); + + MessageDictionary dictionary = new MessageDictionary(message); + MessageDescription description = MessageDescription.Get(message.GetType()); + description.EnsureRequiredMessagePartsArePresent(dictionary.Keys); + } + + /// <summary> + /// Calculates a fairly accurate estimation on the size of a message that contains + /// a given set of fields. + /// </summary> + /// <param name="fields">The fields that would be included in a message.</param> + /// <returns>The size (in bytes) of the message payload.</returns> + private static int CalculateSizeOfPayload(IDictionary<string, string> fields) { + Debug.Assert(fields != null, "fields == null"); + + int size = 0; + foreach (var field in fields) { + size += field.Key.Length; + size += field.Value.Length; + size += 2; // & and = + } + return size; + } + + /// <summary> + /// Ensures a consistent and secure set of binding elements and + /// sorts them as necessary for a valid sequence of operations. + /// </summary> + /// <param name="elements">The binding elements provided to the channel.</param> + /// <returns>The properly ordered list of elements.</returns> + /// <exception cref="ProtocolException">Thrown when the binding elements are incomplete or inconsistent with each other.</exception> + private static IEnumerable<IChannelBindingElement> ValidateAndPrepareBindingElements(IEnumerable<IChannelBindingElement> elements) { + if (elements == null) { + return new IChannelBindingElement[0]; + } + if (elements.Contains(null)) { + throw new ArgumentException(MessagingStrings.SequenceContainsNullElement, "elements"); + } + + // Filter the elements between the mere transforming ones and the protection ones. + var transformationElements = new List<IChannelBindingElement>( + elements.Where(element => element.Protection == MessageProtections.None)); + var protectionElements = new List<IChannelBindingElement>( + elements.Where(element => element.Protection != MessageProtections.None)); + + bool wasLastProtectionPresent = true; + foreach (MessageProtections protectionKind in Enum.GetValues(typeof(MessageProtections))) { + if (protectionKind == MessageProtections.None) { + continue; + } + + int countProtectionsOfThisKind = protectionElements.Count(element => (element.Protection & protectionKind) == protectionKind); + + // Each protection binding element is backed by the presence of its dependent protection(s). + if (countProtectionsOfThisKind > 0 && !wasLastProtectionPresent) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.RequiredProtectionMissing, + protectionKind)); + } + + // At most one binding element for each protection type. + if (countProtectionsOfThisKind > 1) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.TooManyBindingsOfferingSameProtection, + protectionKind, + countProtectionsOfThisKind)); + } + wasLastProtectionPresent = countProtectionsOfThisKind > 0; + } + + // Put the binding elements in order so they are correctly applied to outgoing messages. + // Start with the transforming (non-protecting) binding elements first and preserve their original order. + var orderedList = new List<IChannelBindingElement>(transformationElements); + + // Now sort the protection binding elements among themselves and add them to the list. + orderedList.AddRange(protectionElements.OrderBy(element => element.Protection, BindingElementOutgoingMessageApplicationOrder)); + return orderedList; + } + + /// <summary> + /// Puts binding elements in their correct outgoing message processing order. + /// </summary> + /// <param name="protection1">The first protection type to compare.</param> + /// <param name="protection2">The second protection type to compare.</param> + /// <returns> + /// -1 if <paramref name="element1"/> should be applied to an outgoing message before <paramref name="element2"/>. + /// 1 if <paramref name="element2"/> should be applied to an outgoing message before <paramref name="element1"/>. + /// 0 if it doesn't matter. + /// </returns> + private static int BindingElementOutgoingMessageApplicationOrder(MessageProtections protection1, MessageProtections protection2) { + Debug.Assert(protection1 != MessageProtections.None || protection2 != MessageProtections.None, "This comparison function should only be used to compare protection binding elements. Otherwise we change the order of user-defined message transformations."); + + // Now put the protection ones in the right order. + return -((int)protection1).CompareTo((int)protection2); // descending flag ordinal order + } + + /// <summary> + /// Gets the protocol message that may be in the given HTTP response stream. + /// </summary> + /// <param name="responseStream">The response that is anticipated to contain an OAuth message.</param> + /// <returns>The deserialized message, if one is found. Null otherwise.</returns> + private IProtocolMessage ReadFromResponse(Stream responseStream) { + IProtocolMessage message = this.ReadFromResponseInternal(responseStream); + Logger.DebugFormat("Received message response: {0}", message); + this.VerifyMessageAfterReceiving(message); + return message; + } + + /// <summary> + /// Verifies the integrity and applicability of an incoming message. + /// </summary> + /// <param name="message">The message just received.</param> + /// <exception cref="ProtocolException"> + /// Thrown when the message is somehow invalid. + /// This can be due to tampering, replay attack or expiration, among other things. + /// </exception> + private void VerifyMessageAfterReceiving(IProtocolMessage message) { + Debug.Assert(message != null, "message == null"); + + MessageProtections appliedProtection = MessageProtections.None; + foreach (IChannelBindingElement bindingElement in this.bindingElements.Reverse<IChannelBindingElement>()) { + if (bindingElement.PrepareMessageForReceiving(message)) { + appliedProtection |= bindingElement.Protection; + } + } + + // Ensure that the message's protection requirements have been satisfied. + if ((message.RequiredProtection & appliedProtection) != message.RequiredProtection) { + throw new UnprotectedMessageException(message, appliedProtection); + } + + // We do NOT verify that all required message parts are present here... the + // message deserializer did for us. It would be too late to do it here since + // they might look initialized by the time we have an IProtocolMessage instance. + message.EnsureValidMessage(); + } + } +} diff --git a/src/DotNetOAuth/Messaging/ChannelEventArgs.cs b/src/DotNetOpenAuth/Messaging/ChannelEventArgs.cs index 82506c3..f427bd2 100644 --- a/src/DotNetOAuth/Messaging/ChannelEventArgs.cs +++ b/src/DotNetOpenAuth/Messaging/ChannelEventArgs.cs @@ -1,31 +1,31 @@ -//-----------------------------------------------------------------------
-// <copyright file="ChannelEventArgs.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
-
- /// <summary>
- /// The data packet sent with Channel events.
- /// </summary>
- public class ChannelEventArgs : EventArgs {
- /// <summary>
- /// Initializes a new instance of the <see cref="ChannelEventArgs"/> class.
- /// </summary>
- /// <param name="message">The message behind the fired event..</param>
- internal ChannelEventArgs(IProtocolMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- this.Message = message;
- }
-
- /// <summary>
- /// Gets the message that caused the event to fire.
- /// </summary>
- public IProtocolMessage Message { get; private set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ChannelEventArgs.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + + /// <summary> + /// The data packet sent with Channel events. + /// </summary> + public class ChannelEventArgs : EventArgs { + /// <summary> + /// Initializes a new instance of the <see cref="ChannelEventArgs"/> class. + /// </summary> + /// <param name="message">The message behind the fired event..</param> + internal ChannelEventArgs(IProtocolMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + this.Message = message; + } + + /// <summary> + /// Gets the message that caused the event to fire. + /// </summary> + public IProtocolMessage Message { get; private set; } + } +} diff --git a/src/DotNetOAuth/Messaging/Exceptions.cd b/src/DotNetOpenAuth/Messaging/Exceptions.cd index f0e527b..7225dc0 100644 --- a/src/DotNetOAuth/Messaging/Exceptions.cd +++ b/src/DotNetOpenAuth/Messaging/Exceptions.cd @@ -1,33 +1,33 @@ -<?xml version="1.0" encoding="utf-8"?>
-<ClassDiagram MajorVersion="1" MinorVersion="1">
- <Class Name="DotNetOAuth.Messaging.ExpiredMessageException">
- <Position X="7.25" Y="2.25" Width="2" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\ExpiredMessageException.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.Messaging.ProtocolException" Collapsed="true">
- <Position X="9.75" Y="0.75" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAAKAAAAAAAAQAAAAIBAAAAACAAAAAAAAACAAAAAAAA=</HashCode>
- <FileName>Messaging\ProtocolException.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.Messaging.InvalidSignatureException" Collapsed="true">
- <Position X="9.5" Y="2.25" Width="2" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\InvalidSignatureException.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.Messaging.ReplayedMessageException" Collapsed="true">
- <Position X="11.75" Y="2.25" Width="2.25" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\ReplayedMessageException.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Font Name="Segoe UI" Size="9" />
+<?xml version="1.0" encoding="utf-8"?> +<ClassDiagram MajorVersion="1" MinorVersion="1"> + <Class Name="DotNetOpenAuth.Messaging.ExpiredMessageException"> + <Position X="7.25" Y="2.25" Width="2" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\ExpiredMessageException.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.Messaging.ProtocolException" Collapsed="true"> + <Position X="9.75" Y="0.75" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAAKAAAAAAAAQAAAAIBAAAAACAAAAAAAAACAAAAAAAA=</HashCode> + <FileName>Messaging\ProtocolException.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messaging.InvalidSignatureException" Collapsed="true"> + <Position X="9.5" Y="2.25" Width="2" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\InvalidSignatureException.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.Messaging.ReplayedMessageException" Collapsed="true"> + <Position X="11.75" Y="2.25" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\ReplayedMessageException.cs</FileName> + </TypeIdentifier> + </Class> + <Font Name="Segoe UI" Size="9" /> </ClassDiagram>
\ No newline at end of file diff --git a/src/DotNetOAuth/Messaging/HttpDeliveryMethods.cs b/src/DotNetOpenAuth/Messaging/HttpDeliveryMethods.cs index e0f26c0..961ce41 100644 --- a/src/DotNetOAuth/Messaging/HttpDeliveryMethods.cs +++ b/src/DotNetOpenAuth/Messaging/HttpDeliveryMethods.cs @@ -1,43 +1,43 @@ -//-----------------------------------------------------------------------
-// <copyright file="HttpDeliveryMethods.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
-
- /// <summary>
- /// The methods available for the Consumer to send direct messages to the Service Provider.
- /// </summary>
- /// <remarks>
- /// See 1.0 spec section 5.2.
- /// </remarks>
- [Flags]
- public enum HttpDeliveryMethods {
- /// <summary>
- /// No HTTP methods are allowed.
- /// </summary>
- None = 0x0,
-
- /// <summary>
- /// In the HTTP Authorization header as defined in OAuth HTTP Authorization Scheme (OAuth HTTP Authorization Scheme).
- /// </summary>
- AuthorizationHeaderRequest = 0x1,
-
- /// <summary>
- /// As the HTTP POST request body with a content-type of application/x-www-form-urlencoded.
- /// </summary>
- PostRequest = 0x2,
-
- /// <summary>
- /// Added to the URLs in the query part (as defined by [RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .) section 3).
- /// </summary>
- GetRequest = 0x4,
-
- /// <summary>
- /// All HTTP requests are acceptable.
- /// </summary>
- All = AuthorizationHeaderRequest | PostRequest | GetRequest,
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="HttpDeliveryMethods.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + + /// <summary> + /// The methods available for the Consumer to send direct messages to the Service Provider. + /// </summary> + /// <remarks> + /// See 1.0 spec section 5.2. + /// </remarks> + [Flags] + public enum HttpDeliveryMethods { + /// <summary> + /// No HTTP methods are allowed. + /// </summary> + None = 0x0, + + /// <summary> + /// In the HTTP Authorization header as defined in OAuth HTTP Authorization Scheme (OAuth HTTP Authorization Scheme). + /// </summary> + AuthorizationHeaderRequest = 0x1, + + /// <summary> + /// As the HTTP POST request body with a content-type of application/x-www-form-urlencoded. + /// </summary> + PostRequest = 0x2, + + /// <summary> + /// Added to the URLs in the query part (as defined by [RFC3986] (Berners-Lee, T., “Uniform Resource Identifiers (URI): Generic Syntax,” .) section 3). + /// </summary> + GetRequest = 0x4, + + /// <summary> + /// All HTTP requests are acceptable. + /// </summary> + All = AuthorizationHeaderRequest | PostRequest | GetRequest, + } +} diff --git a/src/DotNetOAuth/Messaging/HttpRequestInfo.cs b/src/DotNetOpenAuth/Messaging/HttpRequestInfo.cs index 3b037c6..48c16c0 100644 --- a/src/DotNetOAuth/Messaging/HttpRequestInfo.cs +++ b/src/DotNetOpenAuth/Messaging/HttpRequestInfo.cs @@ -1,180 +1,180 @@ -//-----------------------------------------------------------------------
-// <copyright file="HttpRequestInfo.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Specialized;
- using System.Diagnostics;
- using System.IO;
- using System.Net;
- using System.ServiceModel.Channels;
- using System.Web;
-
- /// <summary>
- /// A property store of details of an incoming HTTP request.
- /// </summary>
- /// <remarks>
- /// This serves a very similar purpose to <see cref="HttpRequest"/>, except that
- /// ASP.NET does not let us fully initialize that class, so we have to write one
- /// of our one.
- /// </remarks>
- public class HttpRequestInfo {
- /// <summary>
- /// The key/value pairs found in the entity of a POST request.
- /// </summary>
- private NameValueCollection form;
-
- /// <summary>
- /// The key/value pairs found in the querystring of the incoming request.
- /// </summary>
- private NameValueCollection queryString;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
- /// </summary>
- internal HttpRequestInfo() {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
- /// </summary>
- /// <param name="request">The ASP.NET structure to copy from.</param>
- internal HttpRequestInfo(HttpRequest request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- this.HttpMethod = request.HttpMethod;
- this.Url = request.Url;
- this.Headers = GetHeaderCollection(request.Headers);
- this.InputStream = request.InputStream;
-
- // These values would normally be calculated, but we'll reuse them from
- // HttpRequest since they're already calculated, and there's a chance (<g>)
- // that ASP.NET does a better job of being comprehensive about gathering
- // these as well.
- this.form = request.Form;
- this.queryString = request.QueryString;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
- /// </summary>
- /// <param name="request">The WCF incoming request structure to get the HTTP information from.</param>
- /// <param name="requestUri">The URI of the service endpoint.</param>
- internal HttpRequestInfo(HttpRequestMessageProperty request, Uri requestUri) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- this.HttpMethod = request.Method;
- this.Headers = request.Headers;
- this.Url = requestUri;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
- /// </summary>
- /// <param name="request">The HttpWebRequest (that was never used) to copy from.</param>
- internal HttpRequestInfo(WebRequest request) {
- this.HttpMethod = request.Method;
- this.Url = request.RequestUri;
- this.Headers = GetHeaderCollection(request.Headers);
- this.InputStream = null;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class.
- /// </summary>
- /// <param name="message">The message being passed in through a mock transport.</param>
- internal HttpRequestInfo(IProtocolMessage message) {
- this.Message = message;
- }
-
- /// <summary>
- /// Gets or sets the message that is being sent over a mock transport (for testing).
- /// </summary>
- internal IProtocolMessage Message { get; set; }
-
- /// <summary>
- /// Gets or sets the verb in the request (i.e. GET, POST, etc.)
- /// </summary>
- internal string HttpMethod { get; set; }
-
- /// <summary>
- /// Gets or sets the entire URL of the request.
- /// </summary>
- internal Uri Url { get; set; }
-
- /// <summary>
- /// Gets the query part of the URL (The ? and everything after it).
- /// </summary>
- internal string Query {
- get { return this.Url != null ? this.Url.Query : null; }
- }
-
- /// <summary>
- /// Gets or sets the collection of headers that came in with the request.
- /// </summary>
- internal WebHeaderCollection Headers { get; set; }
-
- /// <summary>
- /// Gets or sets the entity, or body of the request, if any.
- /// </summary>
- internal Stream InputStream { get; set; }
-
- /// <summary>
- /// Gets the key/value pairs found in the entity of a POST request.
- /// </summary>
- internal NameValueCollection Form {
- get {
- if (this.form == null) {
- if (this.HttpMethod == "POST" && this.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded") {
- StreamReader reader = new StreamReader(this.InputStream);
- long originalPosition = this.InputStream.Position;
- this.form = HttpUtility.ParseQueryString(reader.ReadToEnd());
- if (this.InputStream.CanSeek) {
- this.InputStream.Seek(originalPosition, SeekOrigin.Begin);
- }
- } else {
- this.form = new NameValueCollection();
- }
- }
-
- return this.form;
- }
- }
-
- /// <summary>
- /// Gets the key/value pairs found in the querystring of the incoming request.
- /// </summary>
- internal NameValueCollection QueryString {
- get {
- if (this.queryString == null) {
- this.queryString = HttpUtility.ParseQueryString(this.Query);
- }
-
- return this.queryString;
- }
- }
-
- /// <summary>
- /// Converts a NameValueCollection to a WebHeaderCollection.
- /// </summary>
- /// <param name="pairs">The collection a HTTP headers.</param>
- /// <returns>A new collection of the given headers.</returns>
- private static WebHeaderCollection GetHeaderCollection(NameValueCollection pairs) {
- Debug.Assert(pairs != null, "pairs == null");
-
- WebHeaderCollection headers = new WebHeaderCollection();
- foreach (string key in pairs) {
- headers.Add(key, pairs[key]);
- }
-
- return headers;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="HttpRequestInfo.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Specialized; + using System.Diagnostics; + using System.IO; + using System.Net; + using System.ServiceModel.Channels; + using System.Web; + + /// <summary> + /// A property store of details of an incoming HTTP request. + /// </summary> + /// <remarks> + /// This serves a very similar purpose to <see cref="HttpRequest"/>, except that + /// ASP.NET does not let us fully initialize that class, so we have to write one + /// of our one. + /// </remarks> + public class HttpRequestInfo { + /// <summary> + /// The key/value pairs found in the entity of a POST request. + /// </summary> + private NameValueCollection form; + + /// <summary> + /// The key/value pairs found in the querystring of the incoming request. + /// </summary> + private NameValueCollection queryString; + + /// <summary> + /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class. + /// </summary> + internal HttpRequestInfo() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class. + /// </summary> + /// <param name="request">The ASP.NET structure to copy from.</param> + internal HttpRequestInfo(HttpRequest request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + this.HttpMethod = request.HttpMethod; + this.Url = request.Url; + this.Headers = GetHeaderCollection(request.Headers); + this.InputStream = request.InputStream; + + // These values would normally be calculated, but we'll reuse them from + // HttpRequest since they're already calculated, and there's a chance (<g>) + // that ASP.NET does a better job of being comprehensive about gathering + // these as well. + this.form = request.Form; + this.queryString = request.QueryString; + } + + /// <summary> + /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class. + /// </summary> + /// <param name="request">The WCF incoming request structure to get the HTTP information from.</param> + /// <param name="requestUri">The URI of the service endpoint.</param> + internal HttpRequestInfo(HttpRequestMessageProperty request, Uri requestUri) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + this.HttpMethod = request.Method; + this.Headers = request.Headers; + this.Url = requestUri; + } + + /// <summary> + /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class. + /// </summary> + /// <param name="request">The HttpWebRequest (that was never used) to copy from.</param> + internal HttpRequestInfo(WebRequest request) { + this.HttpMethod = request.Method; + this.Url = request.RequestUri; + this.Headers = GetHeaderCollection(request.Headers); + this.InputStream = null; + } + + /// <summary> + /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class. + /// </summary> + /// <param name="message">The message being passed in through a mock transport.</param> + internal HttpRequestInfo(IProtocolMessage message) { + this.Message = message; + } + + /// <summary> + /// Gets or sets the message that is being sent over a mock transport (for testing). + /// </summary> + internal IProtocolMessage Message { get; set; } + + /// <summary> + /// Gets or sets the verb in the request (i.e. GET, POST, etc.) + /// </summary> + internal string HttpMethod { get; set; } + + /// <summary> + /// Gets or sets the entire URL of the request. + /// </summary> + internal Uri Url { get; set; } + + /// <summary> + /// Gets the query part of the URL (The ? and everything after it). + /// </summary> + internal string Query { + get { return this.Url != null ? this.Url.Query : null; } + } + + /// <summary> + /// Gets or sets the collection of headers that came in with the request. + /// </summary> + internal WebHeaderCollection Headers { get; set; } + + /// <summary> + /// Gets or sets the entity, or body of the request, if any. + /// </summary> + internal Stream InputStream { get; set; } + + /// <summary> + /// Gets the key/value pairs found in the entity of a POST request. + /// </summary> + internal NameValueCollection Form { + get { + if (this.form == null) { + if (this.HttpMethod == "POST" && this.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded") { + StreamReader reader = new StreamReader(this.InputStream); + long originalPosition = this.InputStream.Position; + this.form = HttpUtility.ParseQueryString(reader.ReadToEnd()); + if (this.InputStream.CanSeek) { + this.InputStream.Seek(originalPosition, SeekOrigin.Begin); + } + } else { + this.form = new NameValueCollection(); + } + } + + return this.form; + } + } + + /// <summary> + /// Gets the key/value pairs found in the querystring of the incoming request. + /// </summary> + internal NameValueCollection QueryString { + get { + if (this.queryString == null) { + this.queryString = HttpUtility.ParseQueryString(this.Query); + } + + return this.queryString; + } + } + + /// <summary> + /// Converts a NameValueCollection to a WebHeaderCollection. + /// </summary> + /// <param name="pairs">The collection a HTTP headers.</param> + /// <returns>A new collection of the given headers.</returns> + private static WebHeaderCollection GetHeaderCollection(NameValueCollection pairs) { + Debug.Assert(pairs != null, "pairs == null"); + + WebHeaderCollection headers = new WebHeaderCollection(); + foreach (string key in pairs) { + headers.Add(key, pairs[key]); + } + + return headers; + } + } +} diff --git a/src/DotNetOAuth/Messaging/IChannelBindingElement.cs b/src/DotNetOpenAuth/Messaging/IChannelBindingElement.cs index a11509d..6c2dc8d 100644 --- a/src/DotNetOAuth/Messaging/IChannelBindingElement.cs +++ b/src/DotNetOpenAuth/Messaging/IChannelBindingElement.cs @@ -1,48 +1,48 @@ -//-----------------------------------------------------------------------
-// <copyright file="IChannelBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- /// <summary>
- /// An interface that must be implemented by message transforms/validators in order
- /// to be included in the channel stack.
- /// </summary>
- public interface IChannelBindingElement {
- /// <summary>
- /// Gets the protection offered (if any) by this binding element.
- /// </summary>
- MessageProtections Protection { get; }
-
- /// <summary>
- /// Prepares a message for sending based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The message to prepare for sending.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False otherwise.
- /// </returns>
- bool PrepareMessageForSending(IProtocolMessage message);
-
- /// <summary>
- /// Performs any transformation on an incoming message that may be necessary and/or
- /// validates an incoming message based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The incoming message to process.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False if the operation did not apply to this message.
- /// </returns>
- /// <exception cref="ProtocolException">
- /// Thrown when the binding element rules indicate that this message is invalid and should
- /// NOT be processed.
- /// </exception>
- bool PrepareMessageForReceiving(IProtocolMessage message);
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IChannelBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + /// <summary> + /// An interface that must be implemented by message transforms/validators in order + /// to be included in the channel stack. + /// </summary> + public interface IChannelBindingElement { + /// <summary> + /// Gets the protection offered (if any) by this binding element. + /// </summary> + MessageProtections Protection { get; } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False otherwise. + /// </returns> + bool PrepareMessageForSending(IProtocolMessage message); + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False if the operation did not apply to this message. + /// </returns> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + bool PrepareMessageForReceiving(IProtocolMessage message); + } +} diff --git a/src/DotNetOAuth/Messaging/IDirectedProtocolMessage.cs b/src/DotNetOpenAuth/Messaging/IDirectedProtocolMessage.cs index 8479fef..8ba07c0 100644 --- a/src/DotNetOAuth/Messaging/IDirectedProtocolMessage.cs +++ b/src/DotNetOpenAuth/Messaging/IDirectedProtocolMessage.cs @@ -1,20 +1,20 @@ -//-----------------------------------------------------------------------
-// <copyright file="IDirectedProtocolMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
-
- /// <summary>
- /// Implemented by messages that have explicit recipients
- /// (direct requests and all indirect messages).
- /// </summary>
- public interface IDirectedProtocolMessage : IProtocolMessage {
- /// <summary>
- /// Gets the URL of the intended receiver of this message.
- /// </summary>
- Uri Recipient { get; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IDirectedProtocolMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + + /// <summary> + /// Implemented by messages that have explicit recipients + /// (direct requests and all indirect messages). + /// </summary> + public interface IDirectedProtocolMessage : IProtocolMessage { + /// <summary> + /// Gets the URL of the intended receiver of this message. + /// </summary> + Uri Recipient { get; } + } +} diff --git a/src/DotNetOAuth/Messaging/IMessageTypeProvider.cs b/src/DotNetOpenAuth/Messaging/IMessageTypeProvider.cs index afc0b04..ea7fcc7 100644 --- a/src/DotNetOAuth/Messaging/IMessageTypeProvider.cs +++ b/src/DotNetOpenAuth/Messaging/IMessageTypeProvider.cs @@ -1,41 +1,41 @@ -//-----------------------------------------------------------------------
-// <copyright file="IMessageTypeProvider.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Generic;
-
- /// <summary>
- /// A tool to analyze an incoming message to figure out what concrete class
- /// is designed to deserialize it.
- /// </summary>
- public interface IMessageTypeProvider {
- /// <summary>
- /// Analyzes an incoming request message payload to discover what kind of
- /// message is embedded in it and returns the type, or null if no match is found.
- /// </summary>
- /// <param name="fields">The name/value pairs that make up the message payload.</param>
- /// <returns>
- /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can
- /// deserialize to. Null if the request isn't recognized as a valid protocol message.
- /// </returns>
- Type GetRequestMessageType(IDictionary<string, string> fields);
-
- /// <summary>
- /// Analyzes an incoming request message payload to discover what kind of
- /// message is embedded in it and returns the type, or null if no match is found.
- /// </summary>
- /// <param name="request">
- /// The message that was sent as a request that resulted in the response.
- /// </param>
- /// <param name="fields">The name/value pairs that make up the message payload.</param>
- /// <returns>
- /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can
- /// deserialize to. Null if the request isn't recognized as a valid protocol message.
- /// </returns>
- Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields);
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IMessageTypeProvider.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + + /// <summary> + /// A tool to analyze an incoming message to figure out what concrete class + /// is designed to deserialize it. + /// </summary> + public interface IMessageTypeProvider { + /// <summary> + /// Analyzes an incoming request message payload to discover what kind of + /// message is embedded in it and returns the type, or null if no match is found. + /// </summary> + /// <param name="fields">The name/value pairs that make up the message payload.</param> + /// <returns> + /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can + /// deserialize to. Null if the request isn't recognized as a valid protocol message. + /// </returns> + Type GetRequestMessageType(IDictionary<string, string> fields); + + /// <summary> + /// Analyzes an incoming request message payload to discover what kind of + /// message is embedded in it and returns the type, or null if no match is found. + /// </summary> + /// <param name="request"> + /// The message that was sent as a request that resulted in the response. + /// </param> + /// <param name="fields">The name/value pairs that make up the message payload.</param> + /// <returns> + /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can + /// deserialize to. Null if the request isn't recognized as a valid protocol message. + /// </returns> + Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields); + } +} diff --git a/src/DotNetOAuth/Messaging/IProtocolMessage.cs b/src/DotNetOpenAuth/Messaging/IProtocolMessage.cs index 25779f9..1dc20ba 100644 --- a/src/DotNetOAuth/Messaging/IProtocolMessage.cs +++ b/src/DotNetOpenAuth/Messaging/IProtocolMessage.cs @@ -1,54 +1,54 @@ -//-----------------------------------------------------------------------
-// <copyright file="IProtocolMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Text;
-
- /// <summary>
- /// The interface that classes must implement to be serialized/deserialized
- /// as OAuth messages.
- /// </summary>
- public interface IProtocolMessage {
- /// <summary>
- /// Gets the version of the protocol this message is prepared to implement.
- /// </summary>
- Version ProtocolVersion { get; }
-
- /// <summary>
- /// Gets the level of protection this message requires.
- /// </summary>
- MessageProtections RequiredProtection { get; }
-
- /// <summary>
- /// Gets a value indicating whether this is a direct or indirect message.
- /// </summary>
- MessageTransport Transport { get; }
-
- /// <summary>
- /// Gets the extra, non-OAuth parameters included in the message.
- /// </summary>
- /// <remarks>
- /// Implementations of this interface should ensure that this property never returns null.
- /// </remarks>
- IDictionary<string, string> ExtraData { get; }
-
- /// <summary>
- /// Checks the message state for conformity to the protocol specification
- /// and throws an exception if the message is invalid.
- /// </summary>
- /// <remarks>
- /// <para>Some messages have required fields, or combinations of fields that must relate to each other
- /// in specialized ways. After deserializing a message, this method checks the state of the
- /// message to see if it conforms to the protocol.</para>
- /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
- /// outside this scope of this particular message.</para>
- /// </remarks>
- /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
- void EnsureValidMessage();
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IProtocolMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Text; + + /// <summary> + /// The interface that classes must implement to be serialized/deserialized + /// as OAuth messages. + /// </summary> + public interface IProtocolMessage { + /// <summary> + /// Gets the version of the protocol this message is prepared to implement. + /// </summary> + Version ProtocolVersion { get; } + + /// <summary> + /// Gets the level of protection this message requires. + /// </summary> + MessageProtections RequiredProtection { get; } + + /// <summary> + /// Gets a value indicating whether this is a direct or indirect message. + /// </summary> + MessageTransport Transport { get; } + + /// <summary> + /// Gets the extra, non-OAuth parameters included in the message. + /// </summary> + /// <remarks> + /// Implementations of this interface should ensure that this property never returns null. + /// </remarks> + IDictionary<string, string> ExtraData { get; } + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + /// <remarks> + /// <para>Some messages have required fields, or combinations of fields that must relate to each other + /// in specialized ways. After deserializing a message, this method checks the state of the + /// message to see if it conforms to the protocol.</para> + /// <para>Note that this property should <i>not</i> check signatures or perform any state checks + /// outside this scope of this particular message.</para> + /// </remarks> + /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception> + void EnsureValidMessage(); + } +} diff --git a/src/DotNetOAuth/Messaging/ITamperProtectionChannelBindingElement.cs b/src/DotNetOpenAuth/Messaging/ITamperProtectionChannelBindingElement.cs index 03478c3..ba25c12 100644 --- a/src/DotNetOAuth/Messaging/ITamperProtectionChannelBindingElement.cs +++ b/src/DotNetOpenAuth/Messaging/ITamperProtectionChannelBindingElement.cs @@ -1,28 +1,28 @@ -//-----------------------------------------------------------------------
-// <copyright file="ITamperProtectionChannelBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using DotNetOAuth.OAuth.ChannelElements;
-
- /// <summary>
- /// An interface that must be implemented by message transforms/validators in order
- /// to be included in the channel stack.
- /// </summary>
- public interface ITamperProtectionChannelBindingElement : IChannelBindingElement {
- /// <summary>
- /// Gets or sets the delegate that will initialize the non-serialized properties necessary on a
- /// signable message so that its signature can be correctly calculated or verified.
- /// </summary>
- Action<ITamperResistantOAuthMessage> SignatureCallback { get; set; }
-
- /// <summary>
- /// Clones this instance.
- /// </summary>
- /// <returns>The cloned instance.</returns>
- ITamperProtectionChannelBindingElement Clone();
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ITamperProtectionChannelBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using DotNetOpenAuth.OAuth.ChannelElements; + + /// <summary> + /// An interface that must be implemented by message transforms/validators in order + /// to be included in the channel stack. + /// </summary> + public interface ITamperProtectionChannelBindingElement : IChannelBindingElement { + /// <summary> + /// Gets or sets the delegate that will initialize the non-serialized properties necessary on a + /// signable message so that its signature can be correctly calculated or verified. + /// </summary> + Action<ITamperResistantOAuthMessage> SignatureCallback { get; set; } + + /// <summary> + /// Clones this instance. + /// </summary> + /// <returns>The cloned instance.</returns> + ITamperProtectionChannelBindingElement Clone(); + } +} diff --git a/src/DotNetOAuth/Messaging/ITamperResistantProtocolMessage.cs b/src/DotNetOpenAuth/Messaging/ITamperResistantProtocolMessage.cs index 0b6b0d1..0da6303 100644 --- a/src/DotNetOAuth/Messaging/ITamperResistantProtocolMessage.cs +++ b/src/DotNetOpenAuth/Messaging/ITamperResistantProtocolMessage.cs @@ -1,22 +1,22 @@ -//-----------------------------------------------------------------------
-// <copyright file="ITamperResistantProtocolMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- /// <summary>
- /// The contract a message that is signed must implement.
- /// </summary>
- /// <remarks>
- /// This type might have appeared in the DotNetOAuth.Messaging.Bindings namespace since
- /// it is only used by types in that namespace, but all those types are internal and this
- /// is the only one that was public.
- /// </remarks>
- public interface ITamperResistantProtocolMessage : IProtocolMessage {
- /// <summary>
- /// Gets or sets the message signature.
- /// </summary>
- string Signature { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ITamperResistantProtocolMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + /// <summary> + /// The contract a message that is signed must implement. + /// </summary> + /// <remarks> + /// This type might have appeared in the DotNetOpenAuth.Messaging.Bindings namespace since + /// it is only used by types in that namespace, but all those types are internal and this + /// is the only one that was public. + /// </remarks> + public interface ITamperResistantProtocolMessage : IProtocolMessage { + /// <summary> + /// Gets or sets the message signature. + /// </summary> + string Signature { get; set; } + } +} diff --git a/src/DotNetOAuth/Messaging/MessagePartAttribute.cs b/src/DotNetOpenAuth/Messaging/MessagePartAttribute.cs index 2e089c2..8812f38 100644 --- a/src/DotNetOAuth/Messaging/MessagePartAttribute.cs +++ b/src/DotNetOpenAuth/Messaging/MessagePartAttribute.cs @@ -1,57 +1,57 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessagePartAttribute.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Net.Security;
- using System.Reflection;
-
- /// <summary>
- /// Applied to fields and properties that form a key/value in a protocol message.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
- public sealed class MessagePartAttribute : Attribute {
- /// <summary>
- /// The overridden name to use as the serialized name for the property.
- /// </summary>
- private string name;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessagePartAttribute"/> class.
- /// </summary>
- public MessagePartAttribute() {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessagePartAttribute"/> class.
- /// </summary>
- /// <param name="name">
- /// A special name to give the value of this member in the serialized message.
- /// When null or empty, the name of the member will be used in the serialized message.
- /// </param>
- public MessagePartAttribute(string name) {
- this.Name = name;
- }
-
- /// <summary>
- /// Gets the name of the serialized form of this member in the message.
- /// </summary>
- public string Name {
- get { return this.name; }
- private set { this.name = string.IsNullOrEmpty(value) ? null : value; }
- }
-
- /// <summary>
- /// Gets or sets the level of protection required by this member in the serialized message.
- /// </summary>
- public ProtectionLevel RequiredProtection { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this member is a required part of the serialized message.
- /// </summary>
- public bool IsRequired { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessagePartAttribute.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Net.Security; + using System.Reflection; + + /// <summary> + /// Applied to fields and properties that form a key/value in a protocol message. + /// </summary> + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = true, AllowMultiple = false)] + public sealed class MessagePartAttribute : Attribute { + /// <summary> + /// The overridden name to use as the serialized name for the property. + /// </summary> + private string name; + + /// <summary> + /// Initializes a new instance of the <see cref="MessagePartAttribute"/> class. + /// </summary> + public MessagePartAttribute() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="MessagePartAttribute"/> class. + /// </summary> + /// <param name="name"> + /// A special name to give the value of this member in the serialized message. + /// When null or empty, the name of the member will be used in the serialized message. + /// </param> + public MessagePartAttribute(string name) { + this.Name = name; + } + + /// <summary> + /// Gets the name of the serialized form of this member in the message. + /// </summary> + public string Name { + get { return this.name; } + private set { this.name = string.IsNullOrEmpty(value) ? null : value; } + } + + /// <summary> + /// Gets or sets the level of protection required by this member in the serialized message. + /// </summary> + public ProtectionLevel RequiredProtection { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether this member is a required part of the serialized message. + /// </summary> + public bool IsRequired { get; set; } + } +} diff --git a/src/DotNetOAuth/Messaging/MessageProtections.cs b/src/DotNetOpenAuth/Messaging/MessageProtections.cs index 29b60b7..c78c92f 100644 --- a/src/DotNetOAuth/Messaging/MessageProtections.cs +++ b/src/DotNetOpenAuth/Messaging/MessageProtections.cs @@ -1,46 +1,46 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageProtections.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
-
- /// <summary>
- /// Categorizes the various types of channel binding elements so they can be properly ordered.
- /// </summary>
- /// <remarks>
- /// The order of these enum values is significant.
- /// Each successive value requires the protection offered by all the previous values
- /// in order to be reliable. For example, message expiration is meaningless without
- /// tamper protection to prevent a user from changing the timestamp on a message.
- /// </remarks>
- [Flags]
- public enum MessageProtections {
- /// <summary>
- /// No protection.
- /// </summary>
- None = 0x0,
-
- /// <summary>
- /// A binding element that signs a message before sending and validates its signature upon receiving.
- /// </summary>
- TamperProtection = 0x1,
-
- /// <summary>
- /// A binding element that enforces a maximum message age between sending and processing on the receiving side.
- /// </summary>
- Expiration = 0x2,
-
- /// <summary>
- /// A binding element that prepares messages for replay detection and detects replayed messages on the receiving side.
- /// </summary>
- ReplayProtection = 0x4,
-
- /// <summary>
- /// All forms of protection together.
- /// </summary>
- All = TamperProtection | Expiration | ReplayProtection,
- }
+//----------------------------------------------------------------------- +// <copyright file="MessageProtections.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + + /// <summary> + /// Categorizes the various types of channel binding elements so they can be properly ordered. + /// </summary> + /// <remarks> + /// The order of these enum values is significant. + /// Each successive value requires the protection offered by all the previous values + /// in order to be reliable. For example, message expiration is meaningless without + /// tamper protection to prevent a user from changing the timestamp on a message. + /// </remarks> + [Flags] + public enum MessageProtections { + /// <summary> + /// No protection. + /// </summary> + None = 0x0, + + /// <summary> + /// A binding element that signs a message before sending and validates its signature upon receiving. + /// </summary> + TamperProtection = 0x1, + + /// <summary> + /// A binding element that enforces a maximum message age between sending and processing on the receiving side. + /// </summary> + Expiration = 0x2, + + /// <summary> + /// A binding element that prepares messages for replay detection and detects replayed messages on the receiving side. + /// </summary> + ReplayProtection = 0x4, + + /// <summary> + /// All forms of protection together. + /// </summary> + All = TamperProtection | Expiration | ReplayProtection, + } }
\ No newline at end of file diff --git a/src/DotNetOAuth/Messaging/MessageReceivingEndpoint.cs b/src/DotNetOpenAuth/Messaging/MessageReceivingEndpoint.cs index 2236dd1..088f2fd 100644 --- a/src/DotNetOAuth/Messaging/MessageReceivingEndpoint.cs +++ b/src/DotNetOpenAuth/Messaging/MessageReceivingEndpoint.cs @@ -1,54 +1,54 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageReceivingEndpoint.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Diagnostics;
-
- /// <summary>
- /// An immutable description of a URL that receives messages.
- /// </summary>
- [DebuggerDisplay("{AllowedMethods} {Location}")]
- public class MessageReceivingEndpoint {
- /// <summary>
- /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
- /// </summary>
- /// <param name="locationUri">The URL of this endpoint.</param>
- /// <param name="method">The HTTP method(s) allowed.</param>
- public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method)
- : this(new Uri(locationUri), method) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class.
- /// </summary>
- /// <param name="location">The URL of this endpoint.</param>
- /// <param name="method">The HTTP method(s) allowed.</param>
- public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method) {
- if (location == null) {
- throw new ArgumentNullException("location");
- }
- if (method == HttpDeliveryMethods.None) {
- throw new ArgumentOutOfRangeException("method");
- }
- if ((method & (HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.GetRequest)) == 0) {
- throw new ArgumentOutOfRangeException("method", MessagingStrings.GetOrPostFlagsRequired);
- }
-
- this.Location = location;
- this.AllowedMethods = method;
- }
-
- /// <summary>
- /// Gets the URL of this endpoint.
- /// </summary>
- public Uri Location { get; private set; }
-
- /// <summary>
- /// Gets the HTTP method(s) allowed.
- /// </summary>
- public HttpDeliveryMethods AllowedMethods { get; private set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageReceivingEndpoint.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Diagnostics; + + /// <summary> + /// An immutable description of a URL that receives messages. + /// </summary> + [DebuggerDisplay("{AllowedMethods} {Location}")] + public class MessageReceivingEndpoint { + /// <summary> + /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class. + /// </summary> + /// <param name="locationUri">The URL of this endpoint.</param> + /// <param name="method">The HTTP method(s) allowed.</param> + public MessageReceivingEndpoint(string locationUri, HttpDeliveryMethods method) + : this(new Uri(locationUri), method) { } + + /// <summary> + /// Initializes a new instance of the <see cref="MessageReceivingEndpoint"/> class. + /// </summary> + /// <param name="location">The URL of this endpoint.</param> + /// <param name="method">The HTTP method(s) allowed.</param> + public MessageReceivingEndpoint(Uri location, HttpDeliveryMethods method) { + if (location == null) { + throw new ArgumentNullException("location"); + } + if (method == HttpDeliveryMethods.None) { + throw new ArgumentOutOfRangeException("method"); + } + if ((method & (HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.GetRequest)) == 0) { + throw new ArgumentOutOfRangeException("method", MessagingStrings.GetOrPostFlagsRequired); + } + + this.Location = location; + this.AllowedMethods = method; + } + + /// <summary> + /// Gets the URL of this endpoint. + /// </summary> + public Uri Location { get; private set; } + + /// <summary> + /// Gets the HTTP method(s) allowed. + /// </summary> + public HttpDeliveryMethods AllowedMethods { get; private set; } + } +} diff --git a/src/DotNetOAuth/Messaging/MessageSerializer.cs b/src/DotNetOpenAuth/Messaging/MessageSerializer.cs index 837b582..cc26096 100644 --- a/src/DotNetOAuth/Messaging/MessageSerializer.cs +++ b/src/DotNetOpenAuth/Messaging/MessageSerializer.cs @@ -1,136 +1,136 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageSerializer.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.Reflection;
- using DotNetOAuth.Messaging.Reflection;
- using DotNetOAuth.OAuth.ChannelElements;
-
- /// <summary>
- /// Serializes/deserializes OAuth messages for/from transit.
- /// </summary>
- internal class MessageSerializer {
- /// <summary>
- /// The specific <see cref="IProtocolMessage"/>-derived type
- /// that will be serialized and deserialized using this class.
- /// </summary>
- private readonly Type messageType;
-
- /// <summary>
- /// Initializes a new instance of the MessageSerializer class.
- /// </summary>
- /// <param name="messageType">The specific <see cref="IProtocolMessage"/>-derived type
- /// that will be serialized and deserialized using this class.</param>
- private MessageSerializer(Type messageType) {
- Debug.Assert(messageType != null, "messageType == null");
-
- if (!typeof(IProtocolMessage).IsAssignableFrom(messageType)) {
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.UnexpectedType,
- typeof(IProtocolMessage).FullName,
- messageType.FullName),
- "messageType");
- }
-
- this.messageType = messageType;
- }
-
- /// <summary>
- /// Creates or reuses a message serializer for a given message type.
- /// </summary>
- /// <param name="messageType">The type of message that will be serialized/deserialized.</param>
- /// <returns>A message serializer for the given message type.</returns>
- internal static MessageSerializer Get(Type messageType) {
- if (messageType == null) {
- throw new ArgumentNullException("messageType");
- }
-
- return new MessageSerializer(messageType);
- }
-
- /// <summary>
- /// Reads the data from a message instance and returns a series of name=value pairs for the fields that must be included in the message.
- /// </summary>
- /// <param name="message">The message to be serialized.</param>
- /// <returns>The dictionary of values to send for the message.</returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Parallel design with Deserialize method.")]
- internal IDictionary<string, string> Serialize(IProtocolMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- var result = new Reflection.MessageDictionary(message);
-
- return result;
- }
-
- /// <summary>
- /// Reads name=value pairs into an OAuth message.
- /// </summary>
- /// <param name="fields">The name=value pairs that were read in from the transport.</param>
- /// <param name="recipient">The recipient of the message.</param>
- /// <returns>The instantiated and initialized <see cref="IProtocolMessage"/> instance.</returns>
- internal IProtocolMessage Deserialize(IDictionary<string, string> fields, MessageReceivingEndpoint recipient) {
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- // Before we deserialize the message, make sure all the required parts are present.
- MessageDescription.Get(this.messageType).EnsureRequiredMessagePartsArePresent(fields.Keys);
-
- IProtocolMessage result = this.CreateMessage(recipient);
- foreach (var pair in fields) {
- IDictionary<string, string> dictionary = new MessageDictionary(result);
- dictionary[pair.Key] = pair.Value;
- }
- result.EnsureValidMessage();
- return result;
- }
-
- /// <summary>
- /// Instantiates a new message to deserialize data into.
- /// </summary>
- /// <param name="recipient">The recipient this message is directed to, if any.</param>
- /// <returns>The newly created message object.</returns>
- private IProtocolMessage CreateMessage(MessageReceivingEndpoint recipient) {
- IProtocolMessage result;
- BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
- if (typeof(IOAuthDirectedMessage).IsAssignableFrom(this.messageType)) {
- // Some OAuth messages take just the recipient, while others take the whole endpoint
- ConstructorInfo ctor;
- if ((ctor = this.messageType.GetConstructor(bindingFlags, null, new Type[] { typeof(Uri) }, null)) != null) {
- if (recipient == null) {
- // We need a recipient to deserialize directed messages.
- throw new ArgumentNullException("recipient");
- }
-
- result = (IProtocolMessage)ctor.Invoke(new object[] { recipient.Location });
- } else if ((ctor = this.messageType.GetConstructor(bindingFlags, null, new Type[] { typeof(MessageReceivingEndpoint) }, null)) != null) {
- if (recipient == null) {
- // We need a recipient to deserialize directed messages.
- throw new ArgumentNullException("recipient");
- }
-
- result = (IProtocolMessage)ctor.Invoke(new object[] { recipient });
- } else if ((ctor = this.messageType.GetConstructor(bindingFlags, null, new Type[0], null)) != null) {
- result = (IProtocolMessage)ctor.Invoke(new object[0]);
- } else {
- throw new InvalidOperationException("Unrecognized constructor signature on type " + this.messageType);
- }
- } else {
- result = (IProtocolMessage)Activator.CreateInstance(this.messageType, true);
- }
-
- return result;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageSerializer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Reflection; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OAuth.ChannelElements; + + /// <summary> + /// Serializes/deserializes OAuth messages for/from transit. + /// </summary> + internal class MessageSerializer { + /// <summary> + /// The specific <see cref="IProtocolMessage"/>-derived type + /// that will be serialized and deserialized using this class. + /// </summary> + private readonly Type messageType; + + /// <summary> + /// Initializes a new instance of the MessageSerializer class. + /// </summary> + /// <param name="messageType">The specific <see cref="IProtocolMessage"/>-derived type + /// that will be serialized and deserialized using this class.</param> + private MessageSerializer(Type messageType) { + Debug.Assert(messageType != null, "messageType == null"); + + if (!typeof(IProtocolMessage).IsAssignableFrom(messageType)) { + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.UnexpectedType, + typeof(IProtocolMessage).FullName, + messageType.FullName), + "messageType"); + } + + this.messageType = messageType; + } + + /// <summary> + /// Creates or reuses a message serializer for a given message type. + /// </summary> + /// <param name="messageType">The type of message that will be serialized/deserialized.</param> + /// <returns>A message serializer for the given message type.</returns> + internal static MessageSerializer Get(Type messageType) { + if (messageType == null) { + throw new ArgumentNullException("messageType"); + } + + return new MessageSerializer(messageType); + } + + /// <summary> + /// Reads the data from a message instance and returns a series of name=value pairs for the fields that must be included in the message. + /// </summary> + /// <param name="message">The message to be serialized.</param> + /// <returns>The dictionary of values to send for the message.</returns> + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Parallel design with Deserialize method.")] + internal IDictionary<string, string> Serialize(IProtocolMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + var result = new Reflection.MessageDictionary(message); + + return result; + } + + /// <summary> + /// Reads name=value pairs into an OAuth message. + /// </summary> + /// <param name="fields">The name=value pairs that were read in from the transport.</param> + /// <param name="recipient">The recipient of the message.</param> + /// <returns>The instantiated and initialized <see cref="IProtocolMessage"/> instance.</returns> + internal IProtocolMessage Deserialize(IDictionary<string, string> fields, MessageReceivingEndpoint recipient) { + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + // Before we deserialize the message, make sure all the required parts are present. + MessageDescription.Get(this.messageType).EnsureRequiredMessagePartsArePresent(fields.Keys); + + IProtocolMessage result = this.CreateMessage(recipient); + foreach (var pair in fields) { + IDictionary<string, string> dictionary = new MessageDictionary(result); + dictionary[pair.Key] = pair.Value; + } + result.EnsureValidMessage(); + return result; + } + + /// <summary> + /// Instantiates a new message to deserialize data into. + /// </summary> + /// <param name="recipient">The recipient this message is directed to, if any.</param> + /// <returns>The newly created message object.</returns> + private IProtocolMessage CreateMessage(MessageReceivingEndpoint recipient) { + IProtocolMessage result; + BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + if (typeof(IOAuthDirectedMessage).IsAssignableFrom(this.messageType)) { + // Some OAuth messages take just the recipient, while others take the whole endpoint + ConstructorInfo ctor; + if ((ctor = this.messageType.GetConstructor(bindingFlags, null, new Type[] { typeof(Uri) }, null)) != null) { + if (recipient == null) { + // We need a recipient to deserialize directed messages. + throw new ArgumentNullException("recipient"); + } + + result = (IProtocolMessage)ctor.Invoke(new object[] { recipient.Location }); + } else if ((ctor = this.messageType.GetConstructor(bindingFlags, null, new Type[] { typeof(MessageReceivingEndpoint) }, null)) != null) { + if (recipient == null) { + // We need a recipient to deserialize directed messages. + throw new ArgumentNullException("recipient"); + } + + result = (IProtocolMessage)ctor.Invoke(new object[] { recipient }); + } else if ((ctor = this.messageType.GetConstructor(bindingFlags, null, new Type[0], null)) != null) { + result = (IProtocolMessage)ctor.Invoke(new object[0]); + } else { + throw new InvalidOperationException("Unrecognized constructor signature on type " + this.messageType); + } + } else { + result = (IProtocolMessage)Activator.CreateInstance(this.messageType, true); + } + + return result; + } + } +} diff --git a/src/DotNetOAuth/Messaging/MessageTransport.cs b/src/DotNetOpenAuth/Messaging/MessageTransport.cs index 40e6897..ee06c95 100644 --- a/src/DotNetOAuth/Messaging/MessageTransport.cs +++ b/src/DotNetOpenAuth/Messaging/MessageTransport.cs @@ -1,22 +1,22 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageTransport.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- /// <summary>
- /// The type of transport mechanism used for a message: either direct or indirect.
- /// </summary>
- public enum MessageTransport {
- /// <summary>
- /// A message that is sent directly from the Consumer to the Service Provider, or vice versa.
- /// </summary>
- Direct,
-
- /// <summary>
- /// A message that is sent from one party to another via a redirect in the user agent.
- /// </summary>
- Indirect,
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageTransport.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + /// <summary> + /// The type of transport mechanism used for a message: either direct or indirect. + /// </summary> + public enum MessageTransport { + /// <summary> + /// A message that is sent directly from the Consumer to the Service Provider, or vice versa. + /// </summary> + Direct, + + /// <summary> + /// A message that is sent from one party to another via a redirect in the user agent. + /// </summary> + Indirect, + } +} diff --git a/src/DotNetOAuth/Messaging/Messaging.cd b/src/DotNetOpenAuth/Messaging/Messaging.cd index 48106a8..0c22565 100644 --- a/src/DotNetOAuth/Messaging/Messaging.cd +++ b/src/DotNetOpenAuth/Messaging/Messaging.cd @@ -1,62 +1,62 @@ -<?xml version="1.0" encoding="utf-8"?>
-<ClassDiagram MajorVersion="1" MinorVersion="1" GroupingSetting="Access">
- <Class Name="DotNetOAuth.Messaging.Channel">
- <Position X="5.25" Y="0.75" Width="1.75" />
- <Compartments>
- <Compartment Name="Protected" Collapsed="true" />
- <Compartment Name="Internal" Collapsed="true" />
- <Compartment Name="Private" Collapsed="true" />
- <Compartment Name="Fields" Collapsed="true" />
- </Compartments>
- <TypeIdentifier>
- <HashCode>gBgQgAIAAQAEAIgAAEAAAARBIAAQgAAQEEAAAABAMAA=</HashCode>
- <FileName>Messaging\Channel.cs</FileName>
- </TypeIdentifier>
- <ShowAsCollectionAssociation>
- <Property Name="BindingElements" />
- </ShowAsCollectionAssociation>
- </Class>
- <Interface Name="DotNetOAuth.Messaging.IChannelBindingElement">
- <Position X="1.75" Y="1.5" Width="2.25" />
- <TypeIdentifier>
- <HashCode>BAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAEAAAAAAAAA=</HashCode>
- <FileName>Messaging\IChannelBindingElement.cs</FileName>
- </TypeIdentifier>
- <ShowAsAssociation>
- <Property Name="Protection" />
- </ShowAsAssociation>
- </Interface>
- <Interface Name="DotNetOAuth.Messaging.IProtocolMessage">
- <Position X="5.25" Y="3.5" Width="1.75" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAQAAAAAAAAAAAAAYAAAAAAAAAAAACAAAAAAA=</HashCode>
- <FileName>Messaging\IProtocolMessage.cs</FileName>
- </TypeIdentifier>
- <ShowAsAssociation>
- <Property Name="RequiredProtection" />
- <Property Name="Transport" />
- </ShowAsAssociation>
- </Interface>
- <Interface Name="DotNetOAuth.Messaging.IDirectedProtocolMessage">
- <Position X="5" Y="5.25" Width="2.25" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\IDirectedProtocolMessage.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Enum Name="DotNetOAuth.Messaging.MessageProtection">
- <Position X="2" Y="3.5" Width="1.75" />
- <TypeIdentifier>
- <HashCode>AIAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAA=</HashCode>
- <FileName>Messaging\MessageProtection.cs</FileName>
- </TypeIdentifier>
- </Enum>
- <Enum Name="DotNetOAuth.Messaging.MessageTransport">
- <Position X="8" Y="3.5" Width="1.5" />
- <TypeIdentifier>
- <HashCode>AAACAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messaging\MessageTransport.cs</FileName>
- </TypeIdentifier>
- </Enum>
- <Font Name="Segoe UI" Size="9" />
+<?xml version="1.0" encoding="utf-8"?> +<ClassDiagram MajorVersion="1" MinorVersion="1" GroupingSetting="Access"> + <Class Name="DotNetOpenAuth.Messaging.Channel"> + <Position X="5.25" Y="0.75" Width="1.75" /> + <Compartments> + <Compartment Name="Protected" Collapsed="true" /> + <Compartment Name="Internal" Collapsed="true" /> + <Compartment Name="Private" Collapsed="true" /> + <Compartment Name="Fields" Collapsed="true" /> + </Compartments> + <TypeIdentifier> + <HashCode>gBgQgAIAAQAEAIgAAEAAAARBIAAQgAAQEEAAAABAMAA=</HashCode> + <FileName>Messaging\Channel.cs</FileName> + </TypeIdentifier> + <ShowAsCollectionAssociation> + <Property Name="BindingElements" /> + </ShowAsCollectionAssociation> + </Class> + <Interface Name="DotNetOpenAuth.Messaging.IChannelBindingElement"> + <Position X="1.75" Y="1.5" Width="2.25" /> + <TypeIdentifier> + <HashCode>BAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAEAAAAAAAAA=</HashCode> + <FileName>Messaging\IChannelBindingElement.cs</FileName> + </TypeIdentifier> + <ShowAsAssociation> + <Property Name="Protection" /> + </ShowAsAssociation> + </Interface> + <Interface Name="DotNetOpenAuth.Messaging.IProtocolMessage"> + <Position X="5.25" Y="3.5" Width="1.75" /> + <TypeIdentifier> + <HashCode>AAAAAAAAQAAAAAAAAAAAAAYAAAAAAAAAAAACAAAAAAA=</HashCode> + <FileName>Messaging\IProtocolMessage.cs</FileName> + </TypeIdentifier> + <ShowAsAssociation> + <Property Name="RequiredProtection" /> + <Property Name="Transport" /> + </ShowAsAssociation> + </Interface> + <Interface Name="DotNetOpenAuth.Messaging.IDirectedProtocolMessage"> + <Position X="5" Y="5.25" Width="2.25" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\IDirectedProtocolMessage.cs</FileName> + </TypeIdentifier> + </Interface> + <Enum Name="DotNetOpenAuth.Messaging.MessageProtection"> + <Position X="2" Y="3.5" Width="1.75" /> + <TypeIdentifier> + <HashCode>AIAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAA=</HashCode> + <FileName>Messaging\MessageProtection.cs</FileName> + </TypeIdentifier> + </Enum> + <Enum Name="DotNetOpenAuth.Messaging.MessageTransport"> + <Position X="8" Y="3.5" Width="1.5" /> + <TypeIdentifier> + <HashCode>AAACAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messaging\MessageTransport.cs</FileName> + </TypeIdentifier> + </Enum> + <Font Name="Segoe UI" Size="9" /> </ClassDiagram>
\ No newline at end of file diff --git a/src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs index c002ecd..b79b846 100644 --- a/src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs +++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs @@ -1,351 +1,351 @@ -//------------------------------------------------------------------------------
-// <auto-generated>
-// This code was generated by a tool.
-// Runtime Version:2.0.50727.3053
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-// </auto-generated>
-//------------------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
-
-
- /// <summary>
- /// A strongly-typed resource class, for looking up localized strings, etc.
- /// </summary>
- // This class was auto-generated by the StronglyTypedResourceBuilder
- // class via a tool like ResGen or Visual Studio.
- // To add or remove a member, edit your .ResX file then rerun ResGen
- // with the /str option, or rebuild your VS project.
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- internal class MessagingStrings {
-
- private static global::System.Resources.ResourceManager resourceMan;
-
- private static global::System.Globalization.CultureInfo resourceCulture;
-
- [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal MessagingStrings() {
- }
-
- /// <summary>
- /// Returns the cached ResourceManager instance used by this class.
- /// </summary>
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Resources.ResourceManager ResourceManager {
- get {
- if (object.ReferenceEquals(resourceMan, null)) {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DotNetOAuth.Messaging.MessagingStrings", typeof(MessagingStrings).Assembly);
- resourceMan = temp;
- }
- return resourceMan;
- }
- }
-
- /// <summary>
- /// Overrides the current thread's CurrentUICulture property for all
- /// resource lookups using this strongly typed resource class.
- /// </summary>
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Globalization.CultureInfo Culture {
- get {
- return resourceCulture;
- }
- set {
- resourceCulture = value;
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Argument's {0}.{1} property is required but is empty or null..
- /// </summary>
- internal static string ArgumentPropertyMissing {
- get {
- return ResourceManager.GetString("ArgumentPropertyMissing", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to HttpContext.Current is null. There must be an ASP.NET request in process for this operation to succeed..
- /// </summary>
- internal static string CurrentHttpContextRequired {
- get {
- return ResourceManager.GetString("CurrentHttpContextRequired", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to DataContractSerializer could not be initialized on message type {0}. Is it missing a [DataContract] attribute?.
- /// </summary>
- internal static string DataContractMissingFromMessageType {
- get {
- return ResourceManager.GetString("DataContractMissingFromMessageType", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to DataContractSerializer could not be initialized on message type {0} because the DataContractAttribute.Namespace property is not set..
- /// </summary>
- internal static string DataContractMissingNamespace {
- get {
- return ResourceManager.GetString("DataContractMissingNamespace", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to An instance of type {0} was expected, but received unexpected derived type {1}..
- /// </summary>
- internal static string DerivedTypeNotExpected {
- get {
- return ResourceManager.GetString("DerivedTypeNotExpected", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The directed message's Recipient property must not be null..
- /// </summary>
- internal static string DirectedMessageMissingRecipient {
- get {
- return ResourceManager.GetString("DirectedMessageMissingRecipient", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Error occurred while sending a direct message or getting the response..
- /// </summary>
- internal static string ErrorInRequestReplyMessage {
- get {
- return ResourceManager.GetString("ErrorInRequestReplyMessage", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to This exception was not constructed with a root request message that caused it..
- /// </summary>
- internal static string ExceptionNotConstructedForTransit {
- get {
- return ResourceManager.GetString("ExceptionNotConstructedForTransit", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Expected message {0} but received no recognizable message..
- /// </summary>
- internal static string ExpectedMessageNotReceived {
- get {
- return ResourceManager.GetString("ExpectedMessageNotReceived", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The message expired at {0} and it is now {1}..
- /// </summary>
- internal static string ExpiredMessage {
- get {
- return ResourceManager.GetString("ExpiredMessage", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to At least one of GET or POST flags must be present..
- /// </summary>
- internal static string GetOrPostFlagsRequired {
- get {
- return ResourceManager.GetString("GetOrPostFlagsRequired", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to This method requires a current HttpContext. Alternatively, use an overload of this method that allows you to pass in information without an HttpContext..
- /// </summary>
- internal static string HttpContextRequired {
- get {
- return ResourceManager.GetString("HttpContextRequired", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Messages that indicate indirect transport must implement the {0} interface..
- /// </summary>
- internal static string IndirectMessagesMustImplementIDirectedProtocolMessage {
- get {
- return ResourceManager.GetString("IndirectMessagesMustImplementIDirectedProtocolMessage", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The message required protections {0} but the channel could only apply {1}..
- /// </summary>
- internal static string InsufficentMessageProtection {
- get {
- return ResourceManager.GetString("InsufficentMessageProtection", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Some part(s) of the message have invalid values: {0}.
- /// </summary>
- internal static string InvalidMessageParts {
- get {
- return ResourceManager.GetString("InvalidMessageParts", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The incoming message had an invalid or missing nonce..
- /// </summary>
- internal static string InvalidNonceReceived {
- get {
- return ResourceManager.GetString("InvalidNonceReceived", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to An item with the same key has already been added..
- /// </summary>
- internal static string KeyAlreadyExists {
- get {
- return ResourceManager.GetString("KeyAlreadyExists", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to A message response is already queued for sending in the response stream..
- /// </summary>
- internal static string QueuedMessageResponseAlreadyExists {
- get {
- return ResourceManager.GetString("QueuedMessageResponseAlreadyExists", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to This message has already been processed. This could indicate a replay attack in progress..
- /// </summary>
- internal static string ReplayAttackDetected {
- get {
- return ResourceManager.GetString("ReplayAttackDetected", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to This channel does not support replay protection..
- /// </summary>
- internal static string ReplayProtectionNotSupported {
- get {
- return ResourceManager.GetString("ReplayProtectionNotSupported", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The following required parameters were missing from the {0} message: {1}.
- /// </summary>
- internal static string RequiredParametersMissing {
- get {
- return ResourceManager.GetString("RequiredParametersMissing", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The binding element offering the {0} protection requires other protection that is not provided..
- /// </summary>
- internal static string RequiredProtectionMissing {
- get {
- return ResourceManager.GetString("RequiredProtectionMissing", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The list is empty..
- /// </summary>
- internal static string SequenceContainsNoElements {
- get {
- return ResourceManager.GetString("SequenceContainsNoElements", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The list contains a null element..
- /// </summary>
- internal static string SequenceContainsNullElement {
- get {
- return ResourceManager.GetString("SequenceContainsNullElement", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Message signature was incorrect..
- /// </summary>
- internal static string SignatureInvalid {
- get {
- return ResourceManager.GetString("SignatureInvalid", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to This channel does not support signing messages. To support signing messages, a derived Channel type must override the Sign and IsSignatureValid methods..
- /// </summary>
- internal static string SigningNotSupported {
- get {
- return ResourceManager.GetString("SigningNotSupported", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The stream's CanRead property returned false..
- /// </summary>
- internal static string StreamUnreadable {
- get {
- return ResourceManager.GetString("StreamUnreadable", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The stream's CanWrite property returned false..
- /// </summary>
- internal static string StreamUnwritable {
- get {
- return ResourceManager.GetString("StreamUnwritable", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Expected at most 1 binding element offering the {0} protection, but found {1}..
- /// </summary>
- internal static string TooManyBindingsOfferingSameProtection {
- get {
- return ResourceManager.GetString("TooManyBindingsOfferingSameProtection", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Expected message {0} but received {1} instead..
- /// </summary>
- internal static string UnexpectedMessageReceived {
- get {
- return ResourceManager.GetString("UnexpectedMessageReceived", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The type {0} or a derived type was expected, but {1} was given..
- /// </summary>
- internal static string UnexpectedType {
- get {
- return ResourceManager.GetString("UnexpectedType", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to {0} property has unrecognized value {1}..
- /// </summary>
- internal static string UnrecognizedEnumValue {
- get {
- return ResourceManager.GetString("UnrecognizedEnumValue", resourceCulture);
- }
- }
- }
-}
+//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by a tool. +// Runtime Version:2.0.50727.3053 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// </auto-generated> +//------------------------------------------------------------------------------ + +namespace DotNetOpenAuth.Messaging { + using System; + + + /// <summary> + /// A strongly-typed resource class, for looking up localized strings, etc. + /// </summary> + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class MessagingStrings { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal MessagingStrings() { + } + + /// <summary> + /// Returns the cached ResourceManager instance used by this class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DotNetOpenAuth.Messaging.MessagingStrings", typeof(MessagingStrings).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// <summary> + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// <summary> + /// Looks up a localized string similar to Argument's {0}.{1} property is required but is empty or null.. + /// </summary> + internal static string ArgumentPropertyMissing { + get { + return ResourceManager.GetString("ArgumentPropertyMissing", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to HttpContext.Current is null. There must be an ASP.NET request in process for this operation to succeed.. + /// </summary> + internal static string CurrentHttpContextRequired { + get { + return ResourceManager.GetString("CurrentHttpContextRequired", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to DataContractSerializer could not be initialized on message type {0}. Is it missing a [DataContract] attribute?. + /// </summary> + internal static string DataContractMissingFromMessageType { + get { + return ResourceManager.GetString("DataContractMissingFromMessageType", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to DataContractSerializer could not be initialized on message type {0} because the DataContractAttribute.Namespace property is not set.. + /// </summary> + internal static string DataContractMissingNamespace { + get { + return ResourceManager.GetString("DataContractMissingNamespace", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to An instance of type {0} was expected, but received unexpected derived type {1}.. + /// </summary> + internal static string DerivedTypeNotExpected { + get { + return ResourceManager.GetString("DerivedTypeNotExpected", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The directed message's Recipient property must not be null.. + /// </summary> + internal static string DirectedMessageMissingRecipient { + get { + return ResourceManager.GetString("DirectedMessageMissingRecipient", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Error occurred while sending a direct message or getting the response.. + /// </summary> + internal static string ErrorInRequestReplyMessage { + get { + return ResourceManager.GetString("ErrorInRequestReplyMessage", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to This exception was not constructed with a root request message that caused it.. + /// </summary> + internal static string ExceptionNotConstructedForTransit { + get { + return ResourceManager.GetString("ExceptionNotConstructedForTransit", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Expected message {0} but received no recognizable message.. + /// </summary> + internal static string ExpectedMessageNotReceived { + get { + return ResourceManager.GetString("ExpectedMessageNotReceived", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The message expired at {0} and it is now {1}.. + /// </summary> + internal static string ExpiredMessage { + get { + return ResourceManager.GetString("ExpiredMessage", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to At least one of GET or POST flags must be present.. + /// </summary> + internal static string GetOrPostFlagsRequired { + get { + return ResourceManager.GetString("GetOrPostFlagsRequired", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to This method requires a current HttpContext. Alternatively, use an overload of this method that allows you to pass in information without an HttpContext.. + /// </summary> + internal static string HttpContextRequired { + get { + return ResourceManager.GetString("HttpContextRequired", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Messages that indicate indirect transport must implement the {0} interface.. + /// </summary> + internal static string IndirectMessagesMustImplementIDirectedProtocolMessage { + get { + return ResourceManager.GetString("IndirectMessagesMustImplementIDirectedProtocolMessage", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The message required protections {0} but the channel could only apply {1}.. + /// </summary> + internal static string InsufficentMessageProtection { + get { + return ResourceManager.GetString("InsufficentMessageProtection", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Some part(s) of the message have invalid values: {0}. + /// </summary> + internal static string InvalidMessageParts { + get { + return ResourceManager.GetString("InvalidMessageParts", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The incoming message had an invalid or missing nonce.. + /// </summary> + internal static string InvalidNonceReceived { + get { + return ResourceManager.GetString("InvalidNonceReceived", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to An item with the same key has already been added.. + /// </summary> + internal static string KeyAlreadyExists { + get { + return ResourceManager.GetString("KeyAlreadyExists", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to A message response is already queued for sending in the response stream.. + /// </summary> + internal static string QueuedMessageResponseAlreadyExists { + get { + return ResourceManager.GetString("QueuedMessageResponseAlreadyExists", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to This message has already been processed. This could indicate a replay attack in progress.. + /// </summary> + internal static string ReplayAttackDetected { + get { + return ResourceManager.GetString("ReplayAttackDetected", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to This channel does not support replay protection.. + /// </summary> + internal static string ReplayProtectionNotSupported { + get { + return ResourceManager.GetString("ReplayProtectionNotSupported", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The following required parameters were missing from the {0} message: {1}. + /// </summary> + internal static string RequiredParametersMissing { + get { + return ResourceManager.GetString("RequiredParametersMissing", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The binding element offering the {0} protection requires other protection that is not provided.. + /// </summary> + internal static string RequiredProtectionMissing { + get { + return ResourceManager.GetString("RequiredProtectionMissing", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The list is empty.. + /// </summary> + internal static string SequenceContainsNoElements { + get { + return ResourceManager.GetString("SequenceContainsNoElements", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The list contains a null element.. + /// </summary> + internal static string SequenceContainsNullElement { + get { + return ResourceManager.GetString("SequenceContainsNullElement", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Message signature was incorrect.. + /// </summary> + internal static string SignatureInvalid { + get { + return ResourceManager.GetString("SignatureInvalid", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to This channel does not support signing messages. To support signing messages, a derived Channel type must override the Sign and IsSignatureValid methods.. + /// </summary> + internal static string SigningNotSupported { + get { + return ResourceManager.GetString("SigningNotSupported", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The stream's CanRead property returned false.. + /// </summary> + internal static string StreamUnreadable { + get { + return ResourceManager.GetString("StreamUnreadable", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The stream's CanWrite property returned false.. + /// </summary> + internal static string StreamUnwritable { + get { + return ResourceManager.GetString("StreamUnwritable", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Expected at most 1 binding element offering the {0} protection, but found {1}.. + /// </summary> + internal static string TooManyBindingsOfferingSameProtection { + get { + return ResourceManager.GetString("TooManyBindingsOfferingSameProtection", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Expected message {0} but received {1} instead.. + /// </summary> + internal static string UnexpectedMessageReceived { + get { + return ResourceManager.GetString("UnexpectedMessageReceived", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The type {0} or a derived type was expected, but {1} was given.. + /// </summary> + internal static string UnexpectedType { + get { + return ResourceManager.GetString("UnexpectedType", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to {0} property has unrecognized value {1}.. + /// </summary> + internal static string UnrecognizedEnumValue { + get { + return ResourceManager.GetString("UnrecognizedEnumValue", resourceCulture); + } + } + } +} diff --git a/src/DotNetOAuth/Messaging/MessagingStrings.resx b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx index 255938c..5fd4e27 100644 --- a/src/DotNetOAuth/Messaging/MessagingStrings.resx +++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx @@ -1,216 +1,216 @@ -<?xml version="1.0" encoding="utf-8"?>
-<root>
- <!--
- Microsoft ResX Schema
-
- Version 2.0
-
- The primary goals of this format is to allow a simple XML format
- that is mostly human readable. The generation and parsing of the
- various data types are done through the TypeConverter classes
- associated with the data types.
-
- Example:
-
- ... ado.net/XML headers & schema ...
- <resheader name="resmimetype">text/microsoft-resx</resheader>
- <resheader name="version">2.0</resheader>
- <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
- <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
- <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
- <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
- <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
- <value>[base64 mime encoded serialized .NET Framework object]</value>
- </data>
- <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
- <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
- <comment>This is a comment</comment>
- </data>
-
- There are any number of "resheader" rows that contain simple
- name/value pairs.
-
- Each data row contains a name, and value. The row also contains a
- type or mimetype. Type corresponds to a .NET class that support
- text/value conversion through the TypeConverter architecture.
- Classes that don't support this are serialized and stored with the
- mimetype set.
-
- The mimetype is used for serialized objects, and tells the
- ResXResourceReader how to depersist the object. This is currently not
- extensible. For a given mimetype the value must be set accordingly:
-
- Note - application/x-microsoft.net.object.binary.base64 is the format
- that the ResXResourceWriter will generate, however the reader can
- read any of the formats listed below.
-
- mimetype: application/x-microsoft.net.object.binary.base64
- value : The object must be serialized with
- : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
- : and then encoded with base64 encoding.
-
- mimetype: application/x-microsoft.net.object.soap.base64
- value : The object must be serialized with
- : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
- : and then encoded with base64 encoding.
-
- mimetype: application/x-microsoft.net.object.bytearray.base64
- value : The object must be serialized into a byte array
- : using a System.ComponentModel.TypeConverter
- : and then encoded with base64 encoding.
- -->
- <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
- <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
- <xsd:element name="root" msdata:IsDataSet="true">
- <xsd:complexType>
- <xsd:choice maxOccurs="unbounded">
- <xsd:element name="metadata">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element name="value" type="xsd:string" minOccurs="0" />
- </xsd:sequence>
- <xsd:attribute name="name" use="required" type="xsd:string" />
- <xsd:attribute name="type" type="xsd:string" />
- <xsd:attribute name="mimetype" type="xsd:string" />
- <xsd:attribute ref="xml:space" />
- </xsd:complexType>
- </xsd:element>
- <xsd:element name="assembly">
- <xsd:complexType>
- <xsd:attribute name="alias" type="xsd:string" />
- <xsd:attribute name="name" type="xsd:string" />
- </xsd:complexType>
- </xsd:element>
- <xsd:element name="data">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
- <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
- </xsd:sequence>
- <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
- <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
- <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
- <xsd:attribute ref="xml:space" />
- </xsd:complexType>
- </xsd:element>
- <xsd:element name="resheader">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
- </xsd:sequence>
- <xsd:attribute name="name" type="xsd:string" use="required" />
- </xsd:complexType>
- </xsd:element>
- </xsd:choice>
- </xsd:complexType>
- </xsd:element>
- </xsd:schema>
- <resheader name="resmimetype">
- <value>text/microsoft-resx</value>
- </resheader>
- <resheader name="version">
- <value>2.0</value>
- </resheader>
- <resheader name="reader">
- <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
- </resheader>
- <resheader name="writer">
- <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
- </resheader>
- <data name="ArgumentPropertyMissing" xml:space="preserve">
- <value>Argument's {0}.{1} property is required but is empty or null.</value>
- </data>
- <data name="CurrentHttpContextRequired" xml:space="preserve">
- <value>HttpContext.Current is null. There must be an ASP.NET request in process for this operation to succeed.</value>
- </data>
- <data name="DataContractMissingFromMessageType" xml:space="preserve">
- <value>DataContractSerializer could not be initialized on message type {0}. Is it missing a [DataContract] attribute?</value>
- </data>
- <data name="DataContractMissingNamespace" xml:space="preserve">
- <value>DataContractSerializer could not be initialized on message type {0} because the DataContractAttribute.Namespace property is not set.</value>
- </data>
- <data name="DerivedTypeNotExpected" xml:space="preserve">
- <value>An instance of type {0} was expected, but received unexpected derived type {1}.</value>
- </data>
- <data name="DirectedMessageMissingRecipient" xml:space="preserve">
- <value>The directed message's Recipient property must not be null.</value>
- </data>
- <data name="ErrorInRequestReplyMessage" xml:space="preserve">
- <value>Error occurred while sending a direct message or getting the response.</value>
- </data>
- <data name="ExceptionNotConstructedForTransit" xml:space="preserve">
- <value>This exception was not constructed with a root request message that caused it.</value>
- </data>
- <data name="ExpectedMessageNotReceived" xml:space="preserve">
- <value>Expected message {0} but received no recognizable message.</value>
- </data>
- <data name="ExpiredMessage" xml:space="preserve">
- <value>The message expired at {0} and it is now {1}.</value>
- </data>
- <data name="GetOrPostFlagsRequired" xml:space="preserve">
- <value>At least one of GET or POST flags must be present.</value>
- </data>
- <data name="HttpContextRequired" xml:space="preserve">
- <value>This method requires a current HttpContext. Alternatively, use an overload of this method that allows you to pass in information without an HttpContext.</value>
- </data>
- <data name="IndirectMessagesMustImplementIDirectedProtocolMessage" xml:space="preserve">
- <value>Messages that indicate indirect transport must implement the {0} interface.</value>
- </data>
- <data name="InsufficentMessageProtection" xml:space="preserve">
- <value>The message required protections {0} but the channel could only apply {1}.</value>
- </data>
- <data name="InvalidMessageParts" xml:space="preserve">
- <value>Some part(s) of the message have invalid values: {0}</value>
- </data>
- <data name="InvalidNonceReceived" xml:space="preserve">
- <value>The incoming message had an invalid or missing nonce.</value>
- </data>
- <data name="KeyAlreadyExists" xml:space="preserve">
- <value>An item with the same key has already been added.</value>
- </data>
- <data name="QueuedMessageResponseAlreadyExists" xml:space="preserve">
- <value>A message response is already queued for sending in the response stream.</value>
- </data>
- <data name="ReplayAttackDetected" xml:space="preserve">
- <value>This message has already been processed. This could indicate a replay attack in progress.</value>
- </data>
- <data name="ReplayProtectionNotSupported" xml:space="preserve">
- <value>This channel does not support replay protection.</value>
- </data>
- <data name="RequiredParametersMissing" xml:space="preserve">
- <value>The following required parameters were missing from the {0} message: {1}</value>
- </data>
- <data name="RequiredProtectionMissing" xml:space="preserve">
- <value>The binding element offering the {0} protection requires other protection that is not provided.</value>
- </data>
- <data name="SequenceContainsNoElements" xml:space="preserve">
- <value>The list is empty.</value>
- </data>
- <data name="SequenceContainsNullElement" xml:space="preserve">
- <value>The list contains a null element.</value>
- </data>
- <data name="SignatureInvalid" xml:space="preserve">
- <value>Message signature was incorrect.</value>
- </data>
- <data name="SigningNotSupported" xml:space="preserve">
- <value>This channel does not support signing messages. To support signing messages, a derived Channel type must override the Sign and IsSignatureValid methods.</value>
- </data>
- <data name="StreamUnreadable" xml:space="preserve">
- <value>The stream's CanRead property returned false.</value>
- </data>
- <data name="StreamUnwritable" xml:space="preserve">
- <value>The stream's CanWrite property returned false.</value>
- </data>
- <data name="TooManyBindingsOfferingSameProtection" xml:space="preserve">
- <value>Expected at most 1 binding element offering the {0} protection, but found {1}.</value>
- </data>
- <data name="UnexpectedMessageReceived" xml:space="preserve">
- <value>Expected message {0} but received {1} instead.</value>
- </data>
- <data name="UnexpectedType" xml:space="preserve">
- <value>The type {0} or a derived type was expected, but {1} was given.</value>
- </data>
- <data name="UnrecognizedEnumValue" xml:space="preserve">
- <value>{0} property has unrecognized value {1}.</value>
- </data>
+<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <data name="ArgumentPropertyMissing" xml:space="preserve"> + <value>Argument's {0}.{1} property is required but is empty or null.</value> + </data> + <data name="CurrentHttpContextRequired" xml:space="preserve"> + <value>HttpContext.Current is null. There must be an ASP.NET request in process for this operation to succeed.</value> + </data> + <data name="DataContractMissingFromMessageType" xml:space="preserve"> + <value>DataContractSerializer could not be initialized on message type {0}. Is it missing a [DataContract] attribute?</value> + </data> + <data name="DataContractMissingNamespace" xml:space="preserve"> + <value>DataContractSerializer could not be initialized on message type {0} because the DataContractAttribute.Namespace property is not set.</value> + </data> + <data name="DerivedTypeNotExpected" xml:space="preserve"> + <value>An instance of type {0} was expected, but received unexpected derived type {1}.</value> + </data> + <data name="DirectedMessageMissingRecipient" xml:space="preserve"> + <value>The directed message's Recipient property must not be null.</value> + </data> + <data name="ErrorInRequestReplyMessage" xml:space="preserve"> + <value>Error occurred while sending a direct message or getting the response.</value> + </data> + <data name="ExceptionNotConstructedForTransit" xml:space="preserve"> + <value>This exception was not constructed with a root request message that caused it.</value> + </data> + <data name="ExpectedMessageNotReceived" xml:space="preserve"> + <value>Expected message {0} but received no recognizable message.</value> + </data> + <data name="ExpiredMessage" xml:space="preserve"> + <value>The message expired at {0} and it is now {1}.</value> + </data> + <data name="GetOrPostFlagsRequired" xml:space="preserve"> + <value>At least one of GET or POST flags must be present.</value> + </data> + <data name="HttpContextRequired" xml:space="preserve"> + <value>This method requires a current HttpContext. Alternatively, use an overload of this method that allows you to pass in information without an HttpContext.</value> + </data> + <data name="IndirectMessagesMustImplementIDirectedProtocolMessage" xml:space="preserve"> + <value>Messages that indicate indirect transport must implement the {0} interface.</value> + </data> + <data name="InsufficentMessageProtection" xml:space="preserve"> + <value>The message required protections {0} but the channel could only apply {1}.</value> + </data> + <data name="InvalidMessageParts" xml:space="preserve"> + <value>Some part(s) of the message have invalid values: {0}</value> + </data> + <data name="InvalidNonceReceived" xml:space="preserve"> + <value>The incoming message had an invalid or missing nonce.</value> + </data> + <data name="KeyAlreadyExists" xml:space="preserve"> + <value>An item with the same key has already been added.</value> + </data> + <data name="QueuedMessageResponseAlreadyExists" xml:space="preserve"> + <value>A message response is already queued for sending in the response stream.</value> + </data> + <data name="ReplayAttackDetected" xml:space="preserve"> + <value>This message has already been processed. This could indicate a replay attack in progress.</value> + </data> + <data name="ReplayProtectionNotSupported" xml:space="preserve"> + <value>This channel does not support replay protection.</value> + </data> + <data name="RequiredParametersMissing" xml:space="preserve"> + <value>The following required parameters were missing from the {0} message: {1}</value> + </data> + <data name="RequiredProtectionMissing" xml:space="preserve"> + <value>The binding element offering the {0} protection requires other protection that is not provided.</value> + </data> + <data name="SequenceContainsNoElements" xml:space="preserve"> + <value>The list is empty.</value> + </data> + <data name="SequenceContainsNullElement" xml:space="preserve"> + <value>The list contains a null element.</value> + </data> + <data name="SignatureInvalid" xml:space="preserve"> + <value>Message signature was incorrect.</value> + </data> + <data name="SigningNotSupported" xml:space="preserve"> + <value>This channel does not support signing messages. To support signing messages, a derived Channel type must override the Sign and IsSignatureValid methods.</value> + </data> + <data name="StreamUnreadable" xml:space="preserve"> + <value>The stream's CanRead property returned false.</value> + </data> + <data name="StreamUnwritable" xml:space="preserve"> + <value>The stream's CanWrite property returned false.</value> + </data> + <data name="TooManyBindingsOfferingSameProtection" xml:space="preserve"> + <value>Expected at most 1 binding element offering the {0} protection, but found {1}.</value> + </data> + <data name="UnexpectedMessageReceived" xml:space="preserve"> + <value>Expected message {0} but received {1} instead.</value> + </data> + <data name="UnexpectedType" xml:space="preserve"> + <value>The type {0} or a derived type was expected, but {1} was given.</value> + </data> + <data name="UnrecognizedEnumValue" xml:space="preserve"> + <value>{0} property has unrecognized value {1}.</value> + </data> </root>
\ No newline at end of file diff --git a/src/DotNetOAuth/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs index 8a4034e..0efb072 100644 --- a/src/DotNetOAuth/Messaging/MessagingUtilities.cs +++ b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs @@ -1,271 +1,271 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessagingUtilities.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Web;
- using DotNetOAuth.Messaging.Reflection;
-
- /// <summary>
- /// A grab-bag of utility methods useful for the channel stack of the protocol.
- /// </summary>
- public static class MessagingUtilities {
- /// <summary>
- /// Adds a set of HTTP headers to an <see cref="HttpResponse"/> instance,
- /// taking care to set some headers to the appropriate properties of
- /// <see cref="HttpResponse" />
- /// </summary>
- /// <param name="headers">The headers to add.</param>
- /// <param name="response">The <see cref="HttpResponse"/> instance to set the appropriate values to.</param>
- internal static void ApplyHeadersToResponse(WebHeaderCollection headers, HttpResponse response) {
- if (headers == null) {
- throw new ArgumentNullException("headers");
- }
- if (response == null) {
- throw new ArgumentNullException("response");
- }
- foreach (string headerName in headers) {
- switch (headerName) {
- case "Content-Type":
- response.ContentType = headers[HttpResponseHeader.ContentType];
- break;
-
- // Add more special cases here as necessary.
- default:
- response.AddHeader(headerName, headers[headerName]);
- break;
- }
- }
- }
-
- /// <summary>
- /// Copies the contents of one stream to another.
- /// </summary>
- /// <param name="copyFrom">The stream to copy from, at the position where copying should begin.</param>
- /// <param name="copyTo">The stream to copy to, at the position where bytes should be written.</param>
- /// <remarks>
- /// Copying begins at the streams' current positions.
- /// The positions are NOT reset after copying is complete.
- /// </remarks>
- internal static void CopyTo(this Stream copyFrom, Stream copyTo) {
- if (copyFrom == null) {
- throw new ArgumentNullException("copyFrom");
- }
- if (copyTo == null) {
- throw new ArgumentNullException("copyTo");
- }
- if (!copyFrom.CanRead) {
- throw new ArgumentException(MessagingStrings.StreamUnreadable, "copyFrom");
- }
- if (!copyTo.CanWrite) {
- throw new ArgumentException(MessagingStrings.StreamUnwritable, "copyTo");
- }
-
- byte[] buffer = new byte[1024];
- int readBytes;
- while ((readBytes = copyFrom.Read(buffer, 0, 1024)) > 0) {
- copyTo.Write(buffer, 0, readBytes);
- }
- }
-
- /// <summary>
- /// Concatenates a list of name-value pairs as key=value&key=value,
- /// taking care to properly encode each key and value for URL
- /// transmission. No ? is prefixed to the string.
- /// </summary>
- /// <param name="args">The dictionary of key/values to read from.</param>
- /// <returns>The formulated querystring style string.</returns>
- internal static string CreateQueryString(IDictionary<string, string> args) {
- if (args == null) {
- throw new ArgumentNullException("args");
- }
- if (args.Count == 0) {
- return string.Empty;
- }
- StringBuilder sb = new StringBuilder(args.Count * 10);
-
- foreach (var p in args) {
- sb.Append(HttpUtility.UrlEncode(p.Key));
- sb.Append('=');
- sb.Append(HttpUtility.UrlEncode(p.Value));
- sb.Append('&');
- }
- sb.Length--; // remove trailing &
-
- return sb.ToString();
- }
-
- /// <summary>
- /// Adds a set of name-value pairs to the end of a given URL
- /// as part of the querystring piece. Prefixes a ? or & before
- /// first element as necessary.
- /// </summary>
- /// <param name="builder">The UriBuilder to add arguments to.</param>
- /// <param name="args">
- /// The arguments to add to the query.
- /// If null, <paramref name="builder"/> is not changed.
- /// </param>
- internal static void AppendQueryArgs(UriBuilder builder, IDictionary<string, string> args) {
- if (builder == null) {
- throw new ArgumentNullException("builder");
- }
-
- if (args != null && args.Count > 0) {
- StringBuilder sb = new StringBuilder(50 + (args.Count * 10));
- if (!string.IsNullOrEmpty(builder.Query)) {
- sb.Append(builder.Query.Substring(1));
- sb.Append('&');
- }
- sb.Append(CreateQueryString(args));
-
- builder.Query = sb.ToString();
- }
- }
-
- /// <summary>
- /// Gets the original request URL, as seen from the browser before any URL rewrites on the server if any.
- /// Cookieless session directory (if applicable) is also included.
- /// </summary>
- /// <returns>The URL in the user agent's Location bar.</returns>
- public static Uri GetRequestUrlFromContext() {
- HttpContext context = HttpContext.Current;
- if (context == null) {
- throw new InvalidOperationException(MessagingStrings.CurrentHttpContextRequired);
- }
-
- // We use Request.Url for the full path to the server, and modify it
- // with Request.RawUrl to capture both the cookieless session "directory" if it exists
- // and the original path in case URL rewriting is going on. We don't want to be
- // fooled by URL rewriting because we're comparing the actual URL with what's in
- // the return_to parameter in some cases.
- // Response.ApplyAppPathModifier(builder.Path) would have worked for the cookieless
- // session, but not the URL rewriting problem.
- return new Uri(context.Request.Url, context.Request.RawUrl);
- }
-
- /// <summary>
- /// Strips any and all URI query parameters that start with some prefix.
- /// </summary>
- /// <param name="uri">The URI that may have a query with parameters to remove.</param>
- /// <param name="prefix">The prefix for parameters to remove.</param>
- /// <returns>Either a new Uri with the parameters removed if there were any to remove, or the same Uri instance if no parameters needed to be removed.</returns>
- public static Uri StripQueryArgumentsWithPrefix(this Uri uri, string prefix) {
- NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
- var matchingKeys = queryArgs.Keys.OfType<string>().Where(key => key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
- if (matchingKeys.Count > 0) {
- UriBuilder builder = new UriBuilder(uri);
- foreach (string key in matchingKeys) {
- queryArgs.Remove(key);
- }
- builder.Query = CreateQueryString(queryArgs.ToDictionary());
- return builder.Uri;
- } else {
- return uri;
- }
- }
-
- /// <summary>
- /// Extracts the recipient from an HttpRequestInfo.
- /// </summary>
- /// <param name="request">The request to get recipient information from.</param>
- /// <returns>The recipient.</returns>
- internal static MessageReceivingEndpoint GetRecipient(this HttpRequestInfo request) {
- return new MessageReceivingEndpoint(request.Url, request.HttpMethod == "GET" ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest);
- }
-
- /// <summary>
- /// Copies some extra parameters into a message.
- /// </summary>
- /// <param name="message">The message to copy the extra data into.</param>
- /// <param name="extraParameters">The extra data to copy into the message. May be null to do nothing.</param>
- internal static void AddNonOAuthParameters(this IProtocolMessage message, IDictionary<string, string> extraParameters) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- if (extraParameters != null) {
- MessageDictionary messageDictionary = new MessageDictionary(message);
- foreach (var pair in extraParameters) {
- messageDictionary.Add(pair);
- }
- }
- }
-
- /// <summary>
- /// Converts a <see cref="NameValueCollection"/> to an IDictionary<string, string>.
- /// </summary>
- /// <param name="nvc">The NameValueCollection to convert. May be null.</param>
- /// <returns>The generated dictionary, or null if <paramref name="nvc"/> is null.</returns>
- internal static Dictionary<string, string> ToDictionary(this NameValueCollection nvc) {
- if (nvc == null) {
- return null;
- }
-
- var dictionary = new Dictionary<string, string>();
- foreach (string key in nvc) {
- dictionary.Add(key, nvc[key]);
- }
-
- return dictionary;
- }
-
- /// <summary>
- /// Sorts the elements of a sequence in ascending order by using a specified comparer.
- /// </summary>
- /// <typeparam name="TSource">The type of the elements of source.</typeparam>
- /// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
- /// <param name="source">A sequence of values to order.</param>
- /// <param name="keySelector">A function to extract a key from an element.</param>
- /// <param name="comparer">A comparison function to compare keys.</param>
- /// <returns>An System.Linq.IOrderedEnumerable<TElement> whose elements are sorted according to a key.</returns>
- internal static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Comparison<TKey> comparer) {
- return System.Linq.Enumerable.OrderBy<TSource, TKey>(source, keySelector, new ComparisonHelper<TKey>(comparer));
- }
-
- /// <summary>
- /// A class to convert a <see cref="Comparison<T>"/> into an <see cref="IComparer<T>"/>.
- /// </summary>
- /// <typeparam name="T">The type of objects being compared.</typeparam>
- private class ComparisonHelper<T> : IComparer<T> {
- /// <summary>
- /// The comparison method to use.
- /// </summary>
- private Comparison<T> comparison;
-
- /// <summary>
- /// Initializes a new instance of the ComparisonHelper class.
- /// </summary>
- /// <param name="comparison">The comparison method to use.</param>
- internal ComparisonHelper(Comparison<T> comparison) {
- if (comparison == null) {
- throw new ArgumentNullException("comparison");
- }
-
- this.comparison = comparison;
- }
-
- #region IComparer<T> Members
-
- /// <summary>
- /// Compares two instances of <typeparamref name="T"/>.
- /// </summary>
- /// <param name="x">The first object to compare.</param>
- /// <param name="y">The second object to compare.</param>
- /// <returns>Any of -1, 0, or 1 according to standard comparison rules.</returns>
- public int Compare(T x, T y) {
- return this.comparison(x, y);
- }
-
- #endregion
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessagingUtilities.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Web; + using DotNetOpenAuth.Messaging.Reflection; + + /// <summary> + /// A grab-bag of utility methods useful for the channel stack of the protocol. + /// </summary> + public static class MessagingUtilities { + /// <summary> + /// Gets the original request URL, as seen from the browser before any URL rewrites on the server if any. + /// Cookieless session directory (if applicable) is also included. + /// </summary> + /// <returns>The URL in the user agent's Location bar.</returns> + public static Uri GetRequestUrlFromContext() { + HttpContext context = HttpContext.Current; + if (context == null) { + throw new InvalidOperationException(MessagingStrings.CurrentHttpContextRequired); + } + + // We use Request.Url for the full path to the server, and modify it + // with Request.RawUrl to capture both the cookieless session "directory" if it exists + // and the original path in case URL rewriting is going on. We don't want to be + // fooled by URL rewriting because we're comparing the actual URL with what's in + // the return_to parameter in some cases. + // Response.ApplyAppPathModifier(builder.Path) would have worked for the cookieless + // session, but not the URL rewriting problem. + return new Uri(context.Request.Url, context.Request.RawUrl); + } + + /// <summary> + /// Strips any and all URI query parameters that start with some prefix. + /// </summary> + /// <param name="uri">The URI that may have a query with parameters to remove.</param> + /// <param name="prefix">The prefix for parameters to remove.</param> + /// <returns>Either a new Uri with the parameters removed if there were any to remove, or the same Uri instance if no parameters needed to be removed.</returns> + public static Uri StripQueryArgumentsWithPrefix(this Uri uri, string prefix) { + NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query); + var matchingKeys = queryArgs.Keys.OfType<string>().Where(key => key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList(); + if (matchingKeys.Count > 0) { + UriBuilder builder = new UriBuilder(uri); + foreach (string key in matchingKeys) { + queryArgs.Remove(key); + } + builder.Query = CreateQueryString(queryArgs.ToDictionary()); + return builder.Uri; + } else { + return uri; + } + } + + /// <summary> + /// Adds a set of HTTP headers to an <see cref="HttpResponse"/> instance, + /// taking care to set some headers to the appropriate properties of + /// <see cref="HttpResponse" /> + /// </summary> + /// <param name="headers">The headers to add.</param> + /// <param name="response">The <see cref="HttpResponse"/> instance to set the appropriate values to.</param> + internal static void ApplyHeadersToResponse(WebHeaderCollection headers, HttpResponse response) { + if (headers == null) { + throw new ArgumentNullException("headers"); + } + if (response == null) { + throw new ArgumentNullException("response"); + } + foreach (string headerName in headers) { + switch (headerName) { + case "Content-Type": + response.ContentType = headers[HttpResponseHeader.ContentType]; + break; + + // Add more special cases here as necessary. + default: + response.AddHeader(headerName, headers[headerName]); + break; + } + } + } + + /// <summary> + /// Copies the contents of one stream to another. + /// </summary> + /// <param name="copyFrom">The stream to copy from, at the position where copying should begin.</param> + /// <param name="copyTo">The stream to copy to, at the position where bytes should be written.</param> + /// <remarks> + /// Copying begins at the streams' current positions. + /// The positions are NOT reset after copying is complete. + /// </remarks> + internal static void CopyTo(this Stream copyFrom, Stream copyTo) { + if (copyFrom == null) { + throw new ArgumentNullException("copyFrom"); + } + if (copyTo == null) { + throw new ArgumentNullException("copyTo"); + } + if (!copyFrom.CanRead) { + throw new ArgumentException(MessagingStrings.StreamUnreadable, "copyFrom"); + } + if (!copyTo.CanWrite) { + throw new ArgumentException(MessagingStrings.StreamUnwritable, "copyTo"); + } + + byte[] buffer = new byte[1024]; + int readBytes; + while ((readBytes = copyFrom.Read(buffer, 0, 1024)) > 0) { + copyTo.Write(buffer, 0, readBytes); + } + } + + /// <summary> + /// Concatenates a list of name-value pairs as key=value&key=value, + /// taking care to properly encode each key and value for URL + /// transmission. No ? is prefixed to the string. + /// </summary> + /// <param name="args">The dictionary of key/values to read from.</param> + /// <returns>The formulated querystring style string.</returns> + internal static string CreateQueryString(IDictionary<string, string> args) { + if (args == null) { + throw new ArgumentNullException("args"); + } + if (args.Count == 0) { + return string.Empty; + } + StringBuilder sb = new StringBuilder(args.Count * 10); + + foreach (var p in args) { + sb.Append(HttpUtility.UrlEncode(p.Key)); + sb.Append('='); + sb.Append(HttpUtility.UrlEncode(p.Value)); + sb.Append('&'); + } + sb.Length--; // remove trailing & + + return sb.ToString(); + } + + /// <summary> + /// Adds a set of name-value pairs to the end of a given URL + /// as part of the querystring piece. Prefixes a ? or & before + /// first element as necessary. + /// </summary> + /// <param name="builder">The UriBuilder to add arguments to.</param> + /// <param name="args"> + /// The arguments to add to the query. + /// If null, <paramref name="builder"/> is not changed. + /// </param> + internal static void AppendQueryArgs(UriBuilder builder, IDictionary<string, string> args) { + if (builder == null) { + throw new ArgumentNullException("builder"); + } + + if (args != null && args.Count > 0) { + StringBuilder sb = new StringBuilder(50 + (args.Count * 10)); + if (!string.IsNullOrEmpty(builder.Query)) { + sb.Append(builder.Query.Substring(1)); + sb.Append('&'); + } + sb.Append(CreateQueryString(args)); + + builder.Query = sb.ToString(); + } + } + + /// <summary> + /// Extracts the recipient from an HttpRequestInfo. + /// </summary> + /// <param name="request">The request to get recipient information from.</param> + /// <returns>The recipient.</returns> + internal static MessageReceivingEndpoint GetRecipient(this HttpRequestInfo request) { + return new MessageReceivingEndpoint(request.Url, request.HttpMethod == "GET" ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest); + } + + /// <summary> + /// Copies some extra parameters into a message. + /// </summary> + /// <param name="message">The message to copy the extra data into.</param> + /// <param name="extraParameters">The extra data to copy into the message. May be null to do nothing.</param> + internal static void AddNonOAuthParameters(this IProtocolMessage message, IDictionary<string, string> extraParameters) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + if (extraParameters != null) { + MessageDictionary messageDictionary = new MessageDictionary(message); + foreach (var pair in extraParameters) { + messageDictionary.Add(pair); + } + } + } + + /// <summary> + /// Converts a <see cref="NameValueCollection"/> to an IDictionary<string, string>. + /// </summary> + /// <param name="nvc">The NameValueCollection to convert. May be null.</param> + /// <returns>The generated dictionary, or null if <paramref name="nvc"/> is null.</returns> + internal static Dictionary<string, string> ToDictionary(this NameValueCollection nvc) { + if (nvc == null) { + return null; + } + + var dictionary = new Dictionary<string, string>(); + foreach (string key in nvc) { + dictionary.Add(key, nvc[key]); + } + + return dictionary; + } + + /// <summary> + /// Sorts the elements of a sequence in ascending order by using a specified comparer. + /// </summary> + /// <typeparam name="TSource">The type of the elements of source.</typeparam> + /// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam> + /// <param name="source">A sequence of values to order.</param> + /// <param name="keySelector">A function to extract a key from an element.</param> + /// <param name="comparer">A comparison function to compare keys.</param> + /// <returns>An System.Linq.IOrderedEnumerable<TElement> whose elements are sorted according to a key.</returns> + internal static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Comparison<TKey> comparer) { + return System.Linq.Enumerable.OrderBy<TSource, TKey>(source, keySelector, new ComparisonHelper<TKey>(comparer)); + } + + /// <summary> + /// A class to convert a <see cref="Comparison<T>"/> into an <see cref="IComparer<T>"/>. + /// </summary> + /// <typeparam name="T">The type of objects being compared.</typeparam> + private class ComparisonHelper<T> : IComparer<T> { + /// <summary> + /// The comparison method to use. + /// </summary> + private Comparison<T> comparison; + + /// <summary> + /// Initializes a new instance of the ComparisonHelper class. + /// </summary> + /// <param name="comparison">The comparison method to use.</param> + internal ComparisonHelper(Comparison<T> comparison) { + if (comparison == null) { + throw new ArgumentNullException("comparison"); + } + + this.comparison = comparison; + } + + #region IComparer<T> Members + + /// <summary> + /// Compares two instances of <typeparamref name="T"/>. + /// </summary> + /// <param name="x">The first object to compare.</param> + /// <param name="y">The second object to compare.</param> + /// <returns>Any of -1, 0, or 1 according to standard comparison rules.</returns> + public int Compare(T x, T y) { + return this.comparison(x, y); + } + + #endregion + } + } +} diff --git a/src/DotNetOAuth/Messaging/ProtocolException.cs b/src/DotNetOpenAuth/Messaging/ProtocolException.cs index 0c31308..a5ac0c7 100644 --- a/src/DotNetOAuth/Messaging/ProtocolException.cs +++ b/src/DotNetOpenAuth/Messaging/ProtocolException.cs @@ -1,254 +1,254 @@ -//-----------------------------------------------------------------------
-// <copyright file="ProtocolException.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Collections.Generic;
- using System.Security.Permissions;
-
- /// <summary>
- /// An exception to represent errors in the local or remote implementation of the protocol.
- /// </summary>
- [Serializable]
- public class ProtocolException : Exception, IDirectedProtocolMessage {
- /// <summary>
- /// The request message being processed when this exception was generated, if any.
- /// </summary>
- private IProtocolMessage inResponseTo;
-
- /// <summary>
- /// The indirect message receiver this exception should be delivered to, if any.
- /// </summary>
- private Uri recipient;
-
- /// <summary>
- /// A cache for extra name/value pairs tacked on as data when this exception is sent as a message.
- /// </summary>
- private Dictionary<string, string> extraData = new Dictionary<string, string>();
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ProtocolException"/> class.
- /// </summary>
- public ProtocolException() { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ProtocolException"/> class.
- /// </summary>
- /// <param name="message">A message describing the specific error the occurred or was detected.</param>
- public ProtocolException(string message) : base(message) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ProtocolException"/> class.
- /// </summary>
- /// <param name="message">A message describing the specific error the occurred or was detected.</param>
- /// <param name="inner">The inner exception to include.</param>
- public ProtocolException(string message, Exception inner) : base(message, inner) { }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ProtocolException"/> class
- /// such that it can be sent as a protocol message response to a remote caller.
- /// </summary>
- /// <param name="message">The human-readable exception message.</param>
- /// <param name="faultedMessage">The message that was the cause of the exception. May not be null.</param>
- internal ProtocolException(string message, IProtocolMessage faultedMessage)
- : base(message) {
- if (faultedMessage == null) {
- throw new ArgumentNullException("faultedMessage");
- }
-
- this.FaultedMessage = faultedMessage;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ProtocolException"/> class
- /// such that it can be sent as a protocol message response to a remote caller.
- /// </summary>
- /// <param name="message">The human-readable exception message.</param>
- /// <param name="inResponseTo">
- /// If <paramref name="message"/> is a response to an incoming message, this is the incoming message.
- /// This is useful for error scenarios in deciding just how to send the response message.
- /// May be null.
- /// </param>
- /// <param name="remoteIndirectReceiver">
- /// In the case of exceptions that will be sent as indirect messages to the original calling
- /// remote party, this is the URI of that remote site's receiver.
- /// May be null only if the <paramref name="inResponseTo"/> message is a direct request.
- /// </param>
- internal ProtocolException(string message, IProtocolMessage inResponseTo, Uri remoteIndirectReceiver)
- : this(message) {
- if (inResponseTo == null) {
- throw new ArgumentNullException("inResponseTo");
- }
- this.inResponseTo = inResponseTo;
- this.FaultedMessage = inResponseTo;
-
- if (remoteIndirectReceiver == null && inResponseTo.Transport != MessageTransport.Direct) {
- // throw an exception, with ourselves as the inner exception (as fully initialized as we can be).
- throw new ArgumentNullException("remoteIndirectReceiver");
- }
- this.recipient = remoteIndirectReceiver;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ProtocolException"/> class.
- /// </summary>
- /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/>
- /// that holds the serialized object data about the exception being thrown.</param>
- /// <param name="context">The System.Runtime.Serialization.StreamingContext
- /// that contains contextual information about the source or destination.</param>
- protected ProtocolException(
- System.Runtime.Serialization.SerializationInfo info,
- System.Runtime.Serialization.StreamingContext context)
- : base(info, context) {
- throw new NotImplementedException();
- }
-
- #region IProtocolMessage Properties
-
- /// <summary>
- /// Gets the version of the protocol this message is prepared to implement.
- /// </summary>
- Version IProtocolMessage.ProtocolVersion {
- get { return this.ProtocolVersion; }
- }
-
- /// <summary>
- /// Gets the level of protection this exception requires when transmitted as a message.
- /// </summary>
- MessageProtections IProtocolMessage.RequiredProtection {
- get { return RequiredProtection; }
- }
-
- /// <summary>
- /// Gets whether this is a direct or indirect message.
- /// </summary>
- MessageTransport IProtocolMessage.Transport {
- get { return this.Transport; }
- }
-
- #endregion
-
- #region IDirectedProtocolMessage Members
-
- /// <summary>
- /// Gets the URL of the intended receiver of this message.
- /// </summary>
- /// <remarks>
- /// This property should only be called when the error is being sent as an indirect response.
- /// </remarks>
- Uri IDirectedProtocolMessage.Recipient {
- get { return this.Recipient; }
- }
-
- #endregion
-
- /// <summary>
- /// Gets the dictionary of additional name/value fields tacked on to this message.
- /// </summary>
- IDictionary<string, string> IProtocolMessage.ExtraData {
- get { return this.ExtraData; }
- }
-
- /// <summary>
- /// Gets the message that caused the exception.
- /// </summary>
- internal IProtocolMessage FaultedMessage {
- get;
- private set;
- }
-
- /// <summary>
- /// Gets the level of protection this exception requires when transmitted as a message.
- /// </summary>
- protected static MessageProtections RequiredProtection {
- get { return MessageProtections.None; }
- }
-
- /// <summary>
- /// Gets the URL of the intended receiver of this message.
- /// </summary>
- /// <remarks>
- /// This property should only be called when the error is being sent as an indirect response.
- /// </remarks>
- protected Uri Recipient {
- get {
- if (this.inResponseTo == null) {
- throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit);
- }
- return this.recipient;
- }
- }
-
- /// <summary>
- /// Gets the version of the protocol this message is prepared to implement.
- /// </summary>
- protected Version ProtocolVersion {
- get {
- if (this.inResponseTo == null) {
- throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit);
- }
- return this.inResponseTo.ProtocolVersion;
- }
- }
-
- /// <summary>
- /// Gets whether this is a direct or indirect message.
- /// </summary>
- protected MessageTransport Transport {
- get {
- if (this.inResponseTo == null) {
- throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit);
- }
- return this.inResponseTo.Transport;
- }
- }
-
- /// <summary>
- /// Gets the dictionary of additional name/value fields tacked on to this message.
- /// </summary>
- protected IDictionary<string, string> ExtraData {
- get { return this.extraData; }
- }
-
- /// <summary>
- /// When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about the exception.
- /// </summary>
- /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
- /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
- /// <exception cref="T:System.ArgumentNullException">
- /// The <paramref name="info"/> parameter is a null reference (Nothing in Visual Basic).
- /// </exception>
- /// <PermissionSet>
- /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*"/>
- /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter"/>
- /// </PermissionSet>
- [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
- public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) {
- base.GetObjectData(info, context);
- throw new NotImplementedException();
- }
-
- #region IProtocolMessage Methods
-
- /// <summary>
- /// See <see cref="IProtocolMessage.EnsureValidMessage"/>.
- /// </summary>
- void IProtocolMessage.EnsureValidMessage() {
- this.EnsureValidMessage();
- }
-
- /// <summary>
- /// See <see cref="IProtocolMessage.EnsureValidMessage"/>.
- /// </summary>
- protected virtual void EnsureValidMessage() {
- if (this.inResponseTo == null) {
- throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit);
- }
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ProtocolException.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Security.Permissions; + + /// <summary> + /// An exception to represent errors in the local or remote implementation of the protocol. + /// </summary> + [Serializable] + public class ProtocolException : Exception, IDirectedProtocolMessage { + /// <summary> + /// The request message being processed when this exception was generated, if any. + /// </summary> + private IProtocolMessage inResponseTo; + + /// <summary> + /// The indirect message receiver this exception should be delivered to, if any. + /// </summary> + private Uri recipient; + + /// <summary> + /// A cache for extra name/value pairs tacked on as data when this exception is sent as a message. + /// </summary> + private Dictionary<string, string> extraData = new Dictionary<string, string>(); + + /// <summary> + /// Initializes a new instance of the <see cref="ProtocolException"/> class. + /// </summary> + public ProtocolException() { } + + /// <summary> + /// Initializes a new instance of the <see cref="ProtocolException"/> class. + /// </summary> + /// <param name="message">A message describing the specific error the occurred or was detected.</param> + public ProtocolException(string message) : base(message) { } + + /// <summary> + /// Initializes a new instance of the <see cref="ProtocolException"/> class. + /// </summary> + /// <param name="message">A message describing the specific error the occurred or was detected.</param> + /// <param name="inner">The inner exception to include.</param> + public ProtocolException(string message, Exception inner) : base(message, inner) { } + + /// <summary> + /// Initializes a new instance of the <see cref="ProtocolException"/> class + /// such that it can be sent as a protocol message response to a remote caller. + /// </summary> + /// <param name="message">The human-readable exception message.</param> + /// <param name="faultedMessage">The message that was the cause of the exception. May not be null.</param> + internal ProtocolException(string message, IProtocolMessage faultedMessage) + : base(message) { + if (faultedMessage == null) { + throw new ArgumentNullException("faultedMessage"); + } + + this.FaultedMessage = faultedMessage; + } + + /// <summary> + /// Initializes a new instance of the <see cref="ProtocolException"/> class + /// such that it can be sent as a protocol message response to a remote caller. + /// </summary> + /// <param name="message">The human-readable exception message.</param> + /// <param name="inResponseTo"> + /// If <paramref name="message"/> is a response to an incoming message, this is the incoming message. + /// This is useful for error scenarios in deciding just how to send the response message. + /// May be null. + /// </param> + /// <param name="remoteIndirectReceiver"> + /// In the case of exceptions that will be sent as indirect messages to the original calling + /// remote party, this is the URI of that remote site's receiver. + /// May be null only if the <paramref name="inResponseTo"/> message is a direct request. + /// </param> + internal ProtocolException(string message, IProtocolMessage inResponseTo, Uri remoteIndirectReceiver) + : this(message) { + if (inResponseTo == null) { + throw new ArgumentNullException("inResponseTo"); + } + this.inResponseTo = inResponseTo; + this.FaultedMessage = inResponseTo; + + if (remoteIndirectReceiver == null && inResponseTo.Transport != MessageTransport.Direct) { + // throw an exception, with ourselves as the inner exception (as fully initialized as we can be). + throw new ArgumentNullException("remoteIndirectReceiver"); + } + this.recipient = remoteIndirectReceiver; + } + + /// <summary> + /// Initializes a new instance of the <see cref="ProtocolException"/> class. + /// </summary> + /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> + /// that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The System.Runtime.Serialization.StreamingContext + /// that contains contextual information about the source or destination.</param> + protected ProtocolException( + System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) + : base(info, context) { + throw new NotImplementedException(); + } + + #region IProtocolMessage Properties + + /// <summary> + /// Gets the version of the protocol this message is prepared to implement. + /// </summary> + Version IProtocolMessage.ProtocolVersion { + get { return this.ProtocolVersion; } + } + + /// <summary> + /// Gets the level of protection this exception requires when transmitted as a message. + /// </summary> + MessageProtections IProtocolMessage.RequiredProtection { + get { return RequiredProtection; } + } + + /// <summary> + /// Gets whether this is a direct or indirect message. + /// </summary> + MessageTransport IProtocolMessage.Transport { + get { return this.Transport; } + } + + #endregion + + #region IDirectedProtocolMessage Members + + /// <summary> + /// Gets the URL of the intended receiver of this message. + /// </summary> + /// <remarks> + /// This property should only be called when the error is being sent as an indirect response. + /// </remarks> + Uri IDirectedProtocolMessage.Recipient { + get { return this.Recipient; } + } + + #endregion + + /// <summary> + /// Gets the dictionary of additional name/value fields tacked on to this message. + /// </summary> + IDictionary<string, string> IProtocolMessage.ExtraData { + get { return this.ExtraData; } + } + + /// <summary> + /// Gets the message that caused the exception. + /// </summary> + internal IProtocolMessage FaultedMessage { + get; + private set; + } + + /// <summary> + /// Gets the level of protection this exception requires when transmitted as a message. + /// </summary> + protected static MessageProtections RequiredProtection { + get { return MessageProtections.None; } + } + + /// <summary> + /// Gets the URL of the intended receiver of this message. + /// </summary> + /// <remarks> + /// This property should only be called when the error is being sent as an indirect response. + /// </remarks> + protected Uri Recipient { + get { + if (this.inResponseTo == null) { + throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit); + } + return this.recipient; + } + } + + /// <summary> + /// Gets the version of the protocol this message is prepared to implement. + /// </summary> + protected Version ProtocolVersion { + get { + if (this.inResponseTo == null) { + throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit); + } + return this.inResponseTo.ProtocolVersion; + } + } + + /// <summary> + /// Gets whether this is a direct or indirect message. + /// </summary> + protected MessageTransport Transport { + get { + if (this.inResponseTo == null) { + throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit); + } + return this.inResponseTo.Transport; + } + } + + /// <summary> + /// Gets the dictionary of additional name/value fields tacked on to this message. + /// </summary> + protected IDictionary<string, string> ExtraData { + get { return this.extraData; } + } + + /// <summary> + /// When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about the exception. + /// </summary> + /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param> + /// <exception cref="T:System.ArgumentNullException"> + /// The <paramref name="info"/> parameter is a null reference (Nothing in Visual Basic). + /// </exception> + /// <PermissionSet> + /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*"/> + /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter"/> + /// </PermissionSet> + [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] + public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { + base.GetObjectData(info, context); + throw new NotImplementedException(); + } + + #region IProtocolMessage Methods + + /// <summary> + /// See <see cref="IProtocolMessage.EnsureValidMessage"/>. + /// </summary> + void IProtocolMessage.EnsureValidMessage() { + this.EnsureValidMessage(); + } + + /// <summary> + /// See <see cref="IProtocolMessage.EnsureValidMessage"/>. + /// </summary> + protected virtual void EnsureValidMessage() { + if (this.inResponseTo == null) { + throw new InvalidOperationException(MessagingStrings.ExceptionNotConstructedForTransit); + } + } + + #endregion + } +} diff --git a/src/DotNetOAuth/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs index 0f180c9..3c668c5 100644 --- a/src/DotNetOAuth/Messaging/Reflection/MessageDescription.cs +++ b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs @@ -1,128 +1,128 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageDescription.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Reflection {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.Linq;
- using System.Reflection;
-
- /// <summary>
- /// A mapping between serialized key names and <see cref="MessagePart"/> instances describing
- /// those key/values pairs.
- /// </summary>
- internal class MessageDescription {
- /// <summary>
- /// A dictionary of reflected message types and the generated reflection information.
- /// </summary>
- private static Dictionary<Type, MessageDescription> reflectedMessageTypes = new Dictionary<Type, MessageDescription>();
-
- /// <summary>
- /// The type of message this instance was generated from.
- /// </summary>
- private Type messageType;
-
- /// <summary>
- /// A mapping between the serialized key names and their
- /// describing <see cref="MessagePart"/> instances.
- /// </summary>
- private Dictionary<string, MessagePart> mapping;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessageDescription"/> class.
- /// </summary>
- /// <param name="messageType">The type of message to reflect over.</param>
- private MessageDescription(Type messageType) {
- Debug.Assert(messageType != null, "messageType == null");
-
- if (!typeof(IProtocolMessage).IsAssignableFrom(messageType)) {
- throw new ArgumentException(string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.UnexpectedType,
- typeof(IProtocolMessage),
- messageType));
- }
-
- this.messageType = messageType;
- this.ReflectMessageType();
- }
-
- /// <summary>
- /// Gets the mapping between the serialized key names and their describing
- /// <see cref="MessagePart"/> instances.
- /// </summary>
- internal IDictionary<string, MessagePart> Mapping {
- get { return this.mapping; }
- }
-
- /// <summary>
- /// Gets a <see cref="MessageDescription"/> instance prepared for the
- /// given message type.
- /// </summary>
- /// <param name="messageType">A type that implements <see cref="IProtocolMessage"/>.</param>
- /// <returns>A <see cref="MessageDescription"/> instance.</returns>
- internal static MessageDescription Get(Type messageType) {
- if (messageType == null) {
- throw new ArgumentNullException("messageType");
- }
-
- MessageDescription result;
- if (!reflectedMessageTypes.TryGetValue(messageType, out result)) {
- lock (reflectedMessageTypes) {
- if (!reflectedMessageTypes.TryGetValue(messageType, out result)) {
- reflectedMessageTypes[messageType] = result = new MessageDescription(messageType);
- }
- }
- }
-
- return result;
- }
-
- /// <summary>
- /// Reflects over some <see cref="IProtocolMessage"/>-implementing type
- /// and prepares to serialize/deserialize instances of that type.
- /// </summary>
- internal void ReflectMessageType() {
- this.mapping = new Dictionary<string, MessagePart>();
-
- Type currentType = this.messageType;
- do {
- foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
- if (member is PropertyInfo || member is FieldInfo) {
- MessagePartAttribute partAttribute = member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>().FirstOrDefault();
- if (partAttribute != null) {
- MessagePart part = new MessagePart(member, partAttribute);
- this.mapping.Add(part.Name, part);
- }
- }
- }
- currentType = currentType.BaseType;
- } while (currentType != null);
- }
-
- /// <summary>
- /// Verifies that a given set of keys include all the required parameters
- /// for this message type or throws an exception.
- /// </summary>
- /// <param name="keys">The names of all parameters included in a message.</param>
- /// <exception cref="ProtocolException">Thrown when required parts of a message are not in <paramref name="keys"/></exception>
- internal void EnsureRequiredMessagePartsArePresent(IEnumerable<string> keys) {
- var missingKeys = (from part in Mapping.Values
- where part.IsRequired && !keys.Contains(part.Name)
- select part.Name).ToArray();
- if (missingKeys.Length > 0) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.RequiredParametersMissing,
- this.messageType.FullName,
- string.Join(", ", missingKeys)));
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Reflection { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Linq; + using System.Reflection; + + /// <summary> + /// A mapping between serialized key names and <see cref="MessagePart"/> instances describing + /// those key/values pairs. + /// </summary> + internal class MessageDescription { + /// <summary> + /// A dictionary of reflected message types and the generated reflection information. + /// </summary> + private static Dictionary<Type, MessageDescription> reflectedMessageTypes = new Dictionary<Type, MessageDescription>(); + + /// <summary> + /// The type of message this instance was generated from. + /// </summary> + private Type messageType; + + /// <summary> + /// A mapping between the serialized key names and their + /// describing <see cref="MessagePart"/> instances. + /// </summary> + private Dictionary<string, MessagePart> mapping; + + /// <summary> + /// Initializes a new instance of the <see cref="MessageDescription"/> class. + /// </summary> + /// <param name="messageType">The type of message to reflect over.</param> + private MessageDescription(Type messageType) { + Debug.Assert(messageType != null, "messageType == null"); + + if (!typeof(IProtocolMessage).IsAssignableFrom(messageType)) { + throw new ArgumentException(string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.UnexpectedType, + typeof(IProtocolMessage), + messageType)); + } + + this.messageType = messageType; + this.ReflectMessageType(); + } + + /// <summary> + /// Gets the mapping between the serialized key names and their describing + /// <see cref="MessagePart"/> instances. + /// </summary> + internal IDictionary<string, MessagePart> Mapping { + get { return this.mapping; } + } + + /// <summary> + /// Gets a <see cref="MessageDescription"/> instance prepared for the + /// given message type. + /// </summary> + /// <param name="messageType">A type that implements <see cref="IProtocolMessage"/>.</param> + /// <returns>A <see cref="MessageDescription"/> instance.</returns> + internal static MessageDescription Get(Type messageType) { + if (messageType == null) { + throw new ArgumentNullException("messageType"); + } + + MessageDescription result; + if (!reflectedMessageTypes.TryGetValue(messageType, out result)) { + lock (reflectedMessageTypes) { + if (!reflectedMessageTypes.TryGetValue(messageType, out result)) { + reflectedMessageTypes[messageType] = result = new MessageDescription(messageType); + } + } + } + + return result; + } + + /// <summary> + /// Reflects over some <see cref="IProtocolMessage"/>-implementing type + /// and prepares to serialize/deserialize instances of that type. + /// </summary> + internal void ReflectMessageType() { + this.mapping = new Dictionary<string, MessagePart>(); + + Type currentType = this.messageType; + do { + foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) { + if (member is PropertyInfo || member is FieldInfo) { + MessagePartAttribute partAttribute = member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>().FirstOrDefault(); + if (partAttribute != null) { + MessagePart part = new MessagePart(member, partAttribute); + this.mapping.Add(part.Name, part); + } + } + } + currentType = currentType.BaseType; + } while (currentType != null); + } + + /// <summary> + /// Verifies that a given set of keys include all the required parameters + /// for this message type or throws an exception. + /// </summary> + /// <param name="keys">The names of all parameters included in a message.</param> + /// <exception cref="ProtocolException">Thrown when required parts of a message are not in <paramref name="keys"/></exception> + internal void EnsureRequiredMessagePartsArePresent(IEnumerable<string> keys) { + var missingKeys = (from part in Mapping.Values + where part.IsRequired && !keys.Contains(part.Name) + select part.Name).ToArray(); + if (missingKeys.Length > 0) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.RequiredParametersMissing, + this.messageType.FullName, + string.Join(", ", missingKeys))); + } + } + } +} diff --git a/src/DotNetOAuth/Messaging/Reflection/MessageDictionary.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessageDictionary.cs index 5416e5f..923c772 100644 --- a/src/DotNetOAuth/Messaging/Reflection/MessageDictionary.cs +++ b/src/DotNetOpenAuth/Messaging/Reflection/MessageDictionary.cs @@ -1,320 +1,320 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageDictionary.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Reflection {
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
-
- /// <summary>
- /// Wraps an <see cref="IProtocolMessage"/> instance in a dictionary that
- /// provides access to both well-defined message properties and "extra"
- /// name/value pairs that have no properties associated with them.
- /// </summary>
- internal class MessageDictionary : IDictionary<string, string> {
- /// <summary>
- /// The <see cref="IProtocolMessage"/> instance manipulated by this dictionary.
- /// </summary>
- private IProtocolMessage message;
-
- /// <summary>
- /// The <see cref="MessageDescription"/> instance that describes the message type.
- /// </summary>
- private MessageDescription description;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessageDictionary"/> class.
- /// </summary>
- /// <param name="message">The message instance whose values will be manipulated by this dictionary.</param>
- internal MessageDictionary(IProtocolMessage message) {
- if (message == null) {
- throw new ArgumentNullException("message");
- }
-
- this.message = message;
- this.description = MessageDescription.Get(message.GetType());
- }
-
- #region ICollection<KeyValuePair<string,string>> Properties
-
- /// <summary>
- /// Gets the number of explicitly set values in the message.
- /// </summary>
- public int Count {
- get { return this.Keys.Count; }
- }
-
- /// <summary>
- /// Gets a value indicating whether this message is read only.
- /// </summary>
- bool ICollection<KeyValuePair<string, string>>.IsReadOnly {
- get { return false; }
- }
-
- #endregion
-
- #region IDictionary<string,string> Properties
-
- /// <summary>
- /// Gets all the keys that have values associated with them.
- /// </summary>
- public ICollection<string> Keys {
- get {
- List<string> keys = new List<string>(this.message.ExtraData.Count + this.description.Mapping.Count);
- keys.AddRange(this.DeclaredKeys);
- keys.AddRange(this.AdditionalKeys);
- return keys.AsReadOnly();
- }
- }
-
- /// <summary>
- /// Gets the set of official OAuth keys that have non-null values associated with them.
- /// </summary>
- public ICollection<string> DeclaredKeys {
- get {
- List<string> keys = new List<string>(this.description.Mapping.Count);
- foreach (var pair in this.description.Mapping) {
- // Don't include keys with null values, but default values for structs is ok
- if (pair.Value.GetValue(this.message) != null) {
- keys.Add(pair.Key);
- }
- }
-
- return keys.AsReadOnly();
- }
- }
-
- /// <summary>
- /// Gets the keys that are in the message but not declared as official OAuth properties.
- /// </summary>
- public ICollection<string> AdditionalKeys {
- get { return this.message.ExtraData.Keys; }
- }
-
- /// <summary>
- /// Gets all the values.
- /// </summary>
- public ICollection<string> Values {
- get {
- List<string> values = new List<string>(this.message.ExtraData.Count + this.description.Mapping.Count);
- foreach (MessagePart part in this.description.Mapping.Values) {
- if (part.GetValue(this.message) != null) {
- values.Add(part.GetValue(this.message));
- }
- }
-
- foreach (string value in this.message.ExtraData.Values) {
- Debug.Assert(value != null, "Null values should never be allowed in the extra data dictionary.");
- values.Add(value);
- }
-
- return values.AsReadOnly();
- }
- }
-
- /// <summary>
- /// Gets or sets a value for some named value.
- /// </summary>
- /// <param name="key">The serialized form of a name for the value to read or write.</param>
- /// <returns>The named value.</returns>
- /// <remarks>
- /// If the key matches a declared property or field on the message type,
- /// that type member is set. Otherwise the key/value is stored in a
- /// dictionary for extra (weakly typed) strings.
- /// </remarks>
- public string this[string key] {
- get {
- MessagePart part;
- if (this.description.Mapping.TryGetValue(key, out part)) {
- // Never throw KeyNotFoundException for declared properties.
- return part.GetValue(this.message);
- } else {
- return this.message.ExtraData[key];
- }
- }
-
- set {
- MessagePart part;
- if (this.description.Mapping.TryGetValue(key, out part)) {
- part.SetValue(this.message, value);
- } else {
- if (value == null) {
- this.message.ExtraData.Remove(key);
- } else {
- this.message.ExtraData[key] = value;
- }
- }
- }
- }
-
- #endregion
-
- #region IDictionary<string,string> Methods
-
- /// <summary>
- /// Adds a named value to the message.
- /// </summary>
- /// <param name="key">The serialized form of the name whose value is being set.</param>
- /// <param name="value">The serialized form of the value.</param>
- /// <exception cref="ArgumentException">
- /// Thrown if <paramref name="key"/> already has a set value in this message.
- /// </exception>
- /// <exception cref="ArgumentNullException">
- /// Thrown if <paramref name="value"/> is null.
- /// </exception>
- public void Add(string key, string value) {
- if (value == null) {
- throw new ArgumentNullException("value");
- }
-
- MessagePart part;
- if (this.description.Mapping.TryGetValue(key, out part)) {
- if (part.IsNondefaultValueSet(this.message)) {
- throw new ArgumentException(MessagingStrings.KeyAlreadyExists);
- }
- part.SetValue(this.message, value);
- } else {
- this.message.ExtraData.Add(key, value);
- }
- }
-
- /// <summary>
- /// Checks whether some named parameter has a value set in the message.
- /// </summary>
- /// <param name="key">The serialized form of the message part's name.</param>
- /// <returns>True if the parameter by the given name has a set value. False otherwise.</returns>
- public bool ContainsKey(string key) {
- return this.message.ExtraData.ContainsKey(key) ||
- (this.description.Mapping.ContainsKey(key) && this.description.Mapping[key].GetValue(this.message) != null);
- }
-
- /// <summary>
- /// Removes a name and value from the message given its name.
- /// </summary>
- /// <param name="key">The serialized form of the name to remove.</param>
- /// <returns>True if a message part by the given name was found and removed. False otherwise.</returns>
- public bool Remove(string key) {
- if (this.message.ExtraData.Remove(key)) {
- return true;
- } else {
- MessagePart part;
- if (this.description.Mapping.TryGetValue(key, out part)) {
- if (part.GetValue(this.message) != null) {
- part.SetValue(this.message, null);
- return true;
- }
- }
- return false;
- }
- }
-
- /// <summary>
- /// Gets some named value if the key has a value.
- /// </summary>
- /// <param name="key">The name (in serialized form) of the value being sought.</param>
- /// <param name="value">The variable where the value will be set.</param>
- /// <returns>True if the key was found and <paramref name="value"/> was set. False otherwise.</returns>
- public bool TryGetValue(string key, out string value) {
- MessagePart part;
- if (this.description.Mapping.TryGetValue(key, out part)) {
- value = part.GetValue(this.message);
- return true;
- }
- return this.message.ExtraData.TryGetValue(key, out value);
- }
-
- #endregion
-
- #region ICollection<KeyValuePair<string,string>> Methods
-
- /// <summary>
- /// Sets a named value in the message.
- /// </summary>
- /// <param name="item">The name-value pair to add. The name is the serialized form of the key.</param>
- public void Add(KeyValuePair<string, string> item) {
- this.Add(item.Key, item.Value);
- }
-
- /// <summary>
- /// Removes all values in the message.
- /// </summary>
- public void Clear() {
- foreach (string key in this.Keys) {
- this.Remove(key);
- }
- }
-
- /// <summary>
- /// Checks whether a named value has been set on the message.
- /// </summary>
- /// <param name="item">The name/value pair.</param>
- /// <returns>True if the key exists and has the given value. False otherwise.</returns>
- public bool Contains(KeyValuePair<string, string> item) {
- MessagePart part;
- if (this.description.Mapping.TryGetValue(item.Key, out part)) {
- return string.Equals(part.GetValue(this.message), item.Value, StringComparison.Ordinal);
- } else {
- return this.message.ExtraData.Contains(item);
- }
- }
-
- /// <summary>
- /// Copies all the serializable data from the message to a key/value array.
- /// </summary>
- /// <param name="array">The array to copy to.</param>
- /// <param name="arrayIndex">The index in the <paramref name="array"/> to begin copying to.</param>
- void ICollection<KeyValuePair<string, string>>.CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) {
- foreach (var pair in (IDictionary<string, string>)this) {
- array[arrayIndex++] = pair;
- }
- }
-
- /// <summary>
- /// Removes a named value from the message if it exists.
- /// </summary>
- /// <param name="item">The serialized form of the name and value to remove.</param>
- /// <returns>True if the name/value was found and removed. False otherwise.</returns>
- public bool Remove(KeyValuePair<string, string> item) {
- // We use contains because that checks that the value is equal as well.
- if (((ICollection<KeyValuePair<string, string>>)this).Contains(item)) {
- ((IDictionary<string, string>)this).Remove(item.Key);
- return true;
- }
- return false;
- }
-
- #endregion
-
- #region IEnumerable<KeyValuePair<string,string>> Members
-
- /// <summary>
- /// Gets an enumerator that generates KeyValuePair<string, string> instances
- /// for all the key/value pairs that are set in the message.
- /// </summary>
- /// <returns>The enumerator that can generate the name/value pairs.</returns>
- public IEnumerator<KeyValuePair<string, string>> GetEnumerator() {
- foreach (string key in this.Keys) {
- yield return new KeyValuePair<string, string>(key, this[key]);
- }
- }
-
- #endregion
-
- #region IEnumerable Members
-
- /// <summary>
- /// Gets an enumerator that generates KeyValuePair<string, string> instances
- /// for all the key/value pairs that are set in the message.
- /// </summary>
- /// <returns>The enumerator that can generate the name/value pairs.</returns>
- IEnumerator System.Collections.IEnumerable.GetEnumerator() {
- return ((IEnumerable<KeyValuePair<string, string>>)this).GetEnumerator();
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageDictionary.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Reflection { + using System; + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + + /// <summary> + /// Wraps an <see cref="IProtocolMessage"/> instance in a dictionary that + /// provides access to both well-defined message properties and "extra" + /// name/value pairs that have no properties associated with them. + /// </summary> + internal class MessageDictionary : IDictionary<string, string> { + /// <summary> + /// The <see cref="IProtocolMessage"/> instance manipulated by this dictionary. + /// </summary> + private IProtocolMessage message; + + /// <summary> + /// The <see cref="MessageDescription"/> instance that describes the message type. + /// </summary> + private MessageDescription description; + + /// <summary> + /// Initializes a new instance of the <see cref="MessageDictionary"/> class. + /// </summary> + /// <param name="message">The message instance whose values will be manipulated by this dictionary.</param> + internal MessageDictionary(IProtocolMessage message) { + if (message == null) { + throw new ArgumentNullException("message"); + } + + this.message = message; + this.description = MessageDescription.Get(message.GetType()); + } + + #region ICollection<KeyValuePair<string,string>> Properties + + /// <summary> + /// Gets the number of explicitly set values in the message. + /// </summary> + public int Count { + get { return this.Keys.Count; } + } + + /// <summary> + /// Gets a value indicating whether this message is read only. + /// </summary> + bool ICollection<KeyValuePair<string, string>>.IsReadOnly { + get { return false; } + } + + #endregion + + #region IDictionary<string,string> Properties + + /// <summary> + /// Gets all the keys that have values associated with them. + /// </summary> + public ICollection<string> Keys { + get { + List<string> keys = new List<string>(this.message.ExtraData.Count + this.description.Mapping.Count); + keys.AddRange(this.DeclaredKeys); + keys.AddRange(this.AdditionalKeys); + return keys.AsReadOnly(); + } + } + + /// <summary> + /// Gets the set of official OAuth keys that have non-null values associated with them. + /// </summary> + public ICollection<string> DeclaredKeys { + get { + List<string> keys = new List<string>(this.description.Mapping.Count); + foreach (var pair in this.description.Mapping) { + // Don't include keys with null values, but default values for structs is ok + if (pair.Value.GetValue(this.message) != null) { + keys.Add(pair.Key); + } + } + + return keys.AsReadOnly(); + } + } + + /// <summary> + /// Gets the keys that are in the message but not declared as official OAuth properties. + /// </summary> + public ICollection<string> AdditionalKeys { + get { return this.message.ExtraData.Keys; } + } + + /// <summary> + /// Gets all the values. + /// </summary> + public ICollection<string> Values { + get { + List<string> values = new List<string>(this.message.ExtraData.Count + this.description.Mapping.Count); + foreach (MessagePart part in this.description.Mapping.Values) { + if (part.GetValue(this.message) != null) { + values.Add(part.GetValue(this.message)); + } + } + + foreach (string value in this.message.ExtraData.Values) { + Debug.Assert(value != null, "Null values should never be allowed in the extra data dictionary."); + values.Add(value); + } + + return values.AsReadOnly(); + } + } + + /// <summary> + /// Gets or sets a value for some named value. + /// </summary> + /// <param name="key">The serialized form of a name for the value to read or write.</param> + /// <returns>The named value.</returns> + /// <remarks> + /// If the key matches a declared property or field on the message type, + /// that type member is set. Otherwise the key/value is stored in a + /// dictionary for extra (weakly typed) strings. + /// </remarks> + public string this[string key] { + get { + MessagePart part; + if (this.description.Mapping.TryGetValue(key, out part)) { + // Never throw KeyNotFoundException for declared properties. + return part.GetValue(this.message); + } else { + return this.message.ExtraData[key]; + } + } + + set { + MessagePart part; + if (this.description.Mapping.TryGetValue(key, out part)) { + part.SetValue(this.message, value); + } else { + if (value == null) { + this.message.ExtraData.Remove(key); + } else { + this.message.ExtraData[key] = value; + } + } + } + } + + #endregion + + #region IDictionary<string,string> Methods + + /// <summary> + /// Adds a named value to the message. + /// </summary> + /// <param name="key">The serialized form of the name whose value is being set.</param> + /// <param name="value">The serialized form of the value.</param> + /// <exception cref="ArgumentException"> + /// Thrown if <paramref name="key"/> already has a set value in this message. + /// </exception> + /// <exception cref="ArgumentNullException"> + /// Thrown if <paramref name="value"/> is null. + /// </exception> + public void Add(string key, string value) { + if (value == null) { + throw new ArgumentNullException("value"); + } + + MessagePart part; + if (this.description.Mapping.TryGetValue(key, out part)) { + if (part.IsNondefaultValueSet(this.message)) { + throw new ArgumentException(MessagingStrings.KeyAlreadyExists); + } + part.SetValue(this.message, value); + } else { + this.message.ExtraData.Add(key, value); + } + } + + /// <summary> + /// Checks whether some named parameter has a value set in the message. + /// </summary> + /// <param name="key">The serialized form of the message part's name.</param> + /// <returns>True if the parameter by the given name has a set value. False otherwise.</returns> + public bool ContainsKey(string key) { + return this.message.ExtraData.ContainsKey(key) || + (this.description.Mapping.ContainsKey(key) && this.description.Mapping[key].GetValue(this.message) != null); + } + + /// <summary> + /// Removes a name and value from the message given its name. + /// </summary> + /// <param name="key">The serialized form of the name to remove.</param> + /// <returns>True if a message part by the given name was found and removed. False otherwise.</returns> + public bool Remove(string key) { + if (this.message.ExtraData.Remove(key)) { + return true; + } else { + MessagePart part; + if (this.description.Mapping.TryGetValue(key, out part)) { + if (part.GetValue(this.message) != null) { + part.SetValue(this.message, null); + return true; + } + } + return false; + } + } + + /// <summary> + /// Gets some named value if the key has a value. + /// </summary> + /// <param name="key">The name (in serialized form) of the value being sought.</param> + /// <param name="value">The variable where the value will be set.</param> + /// <returns>True if the key was found and <paramref name="value"/> was set. False otherwise.</returns> + public bool TryGetValue(string key, out string value) { + MessagePart part; + if (this.description.Mapping.TryGetValue(key, out part)) { + value = part.GetValue(this.message); + return true; + } + return this.message.ExtraData.TryGetValue(key, out value); + } + + #endregion + + #region ICollection<KeyValuePair<string,string>> Methods + + /// <summary> + /// Sets a named value in the message. + /// </summary> + /// <param name="item">The name-value pair to add. The name is the serialized form of the key.</param> + public void Add(KeyValuePair<string, string> item) { + this.Add(item.Key, item.Value); + } + + /// <summary> + /// Removes all values in the message. + /// </summary> + public void Clear() { + foreach (string key in this.Keys) { + this.Remove(key); + } + } + + /// <summary> + /// Checks whether a named value has been set on the message. + /// </summary> + /// <param name="item">The name/value pair.</param> + /// <returns>True if the key exists and has the given value. False otherwise.</returns> + public bool Contains(KeyValuePair<string, string> item) { + MessagePart part; + if (this.description.Mapping.TryGetValue(item.Key, out part)) { + return string.Equals(part.GetValue(this.message), item.Value, StringComparison.Ordinal); + } else { + return this.message.ExtraData.Contains(item); + } + } + + /// <summary> + /// Copies all the serializable data from the message to a key/value array. + /// </summary> + /// <param name="array">The array to copy to.</param> + /// <param name="arrayIndex">The index in the <paramref name="array"/> to begin copying to.</param> + void ICollection<KeyValuePair<string, string>>.CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) { + foreach (var pair in (IDictionary<string, string>)this) { + array[arrayIndex++] = pair; + } + } + + /// <summary> + /// Removes a named value from the message if it exists. + /// </summary> + /// <param name="item">The serialized form of the name and value to remove.</param> + /// <returns>True if the name/value was found and removed. False otherwise.</returns> + public bool Remove(KeyValuePair<string, string> item) { + // We use contains because that checks that the value is equal as well. + if (((ICollection<KeyValuePair<string, string>>)this).Contains(item)) { + ((IDictionary<string, string>)this).Remove(item.Key); + return true; + } + return false; + } + + #endregion + + #region IEnumerable<KeyValuePair<string,string>> Members + + /// <summary> + /// Gets an enumerator that generates KeyValuePair<string, string> instances + /// for all the key/value pairs that are set in the message. + /// </summary> + /// <returns>The enumerator that can generate the name/value pairs.</returns> + public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { + foreach (string key in this.Keys) { + yield return new KeyValuePair<string, string>(key, this[key]); + } + } + + #endregion + + #region IEnumerable Members + + /// <summary> + /// Gets an enumerator that generates KeyValuePair<string, string> instances + /// for all the key/value pairs that are set in the message. + /// </summary> + /// <returns>The enumerator that can generate the name/value pairs.</returns> + IEnumerator System.Collections.IEnumerable.GetEnumerator() { + return ((IEnumerable<KeyValuePair<string, string>>)this).GetEnumerator(); + } + + #endregion + } +} diff --git a/src/DotNetOAuth/Messaging/Reflection/MessagePart.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs index 8d409d4..d662b25 100644 --- a/src/DotNetOAuth/Messaging/Reflection/MessagePart.cs +++ b/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs @@ -1,251 +1,251 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessagePart.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Reflection {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using System.Globalization;
- using System.Net.Security;
- using System.Reflection;
- using System.Xml;
-
- /// <summary>
- /// Describes an individual member of a message and assists in its serialization.
- /// </summary>
- internal class MessagePart {
- /// <summary>
- /// A map of converters that help serialize custom objects to string values and back again.
- /// </summary>
- private static readonly Dictionary<Type, ValueMapping> converters = new Dictionary<Type, ValueMapping>();
-
- /// <summary>
- /// The string-object conversion routines to use for this individual message part.
- /// </summary>
- private ValueMapping converter;
-
- /// <summary>
- /// The property that this message part is associated with, if aplicable.
- /// </summary>
- private PropertyInfo property;
-
- /// <summary>
- /// The field that this message part is associated with, if aplicable.
- /// </summary>
- private FieldInfo field;
-
- /// <summary>
- /// The type of the message part. (Not the type of the message itself).
- /// </summary>
- private Type memberDeclaredType;
-
- /// <summary>
- /// The default (uninitialized) value of the member inherent in its type.
- /// </summary>
- private object defaultMemberValue;
-
- /// <summary>
- /// Initializes static members of the <see cref="MessagePart"/> class.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Much more efficient initialization when we can call methods.")]
- static MessagePart() {
- Map<Uri>(uri => uri.AbsoluteUri, str => new Uri(str));
- Map<DateTime>(dt => XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc), str => XmlConvert.ToDateTime(str, XmlDateTimeSerializationMode.Utc));
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessagePart"/> class.
- /// </summary>
- /// <param name="member">
- /// A property or field of an <see cref="IProtocolMessage"/> implementing type
- /// that has a <see cref="MessagePartAttribute"/> attached to it.
- /// </param>
- /// <param name="attribute">
- /// The attribute discovered on <paramref name="member"/> that describes the
- /// serialization requirements of the message part.
- /// </param>
- internal MessagePart(MemberInfo member, MessagePartAttribute attribute) {
- if (member == null) {
- throw new ArgumentNullException("member");
- }
-
- this.field = member as FieldInfo;
- this.property = member as PropertyInfo;
- if (this.field == null && this.property == null) {
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.UnexpectedType,
- typeof(FieldInfo).Name + ", " + typeof(PropertyInfo).Name,
- member.GetType().Name),
- "member");
- }
-
- if (attribute == null) {
- throw new ArgumentNullException("attribute");
- }
-
- this.Name = attribute.Name ?? member.Name;
- this.RequiredProtection = attribute.RequiredProtection;
- this.IsRequired = attribute.IsRequired;
- this.memberDeclaredType = (this.field != null) ? this.field.FieldType : this.property.PropertyType;
- this.defaultMemberValue = DeriveDefaultValue(this.memberDeclaredType);
-
- if (!converters.TryGetValue(this.memberDeclaredType, out this.converter)) {
- this.converter = new ValueMapping(
- obj => obj != null ? obj.ToString() : null,
- str => str != null ? Convert.ChangeType(str, this.memberDeclaredType, CultureInfo.InvariantCulture) : null);
- }
-
- // Validate a sane combination of settings
- this.ValidateSettings();
- }
-
- /// <summary>
- /// Gets or sets the name to use when serializing or deserializing this parameter in a message.
- /// </summary>
- internal string Name { get; set; }
-
- /// <summary>
- /// Gets or sets whether this message part must be signed.
- /// </summary>
- internal ProtectionLevel RequiredProtection { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether this message part is required for the
- /// containing message to be valid.
- /// </summary>
- internal bool IsRequired { get; set; }
-
- /// <summary>
- /// Sets the member of a given message to some given value.
- /// Used in deserialization.
- /// </summary>
- /// <param name="message">The message instance containing the member whose value should be set.</param>
- /// <param name="value">The string representation of the value to set.</param>
- internal void SetValue(IProtocolMessage message, string value) {
- if (this.property != null) {
- this.property.SetValue(message, this.ToValue(value), null);
- } else {
- this.field.SetValue(message, this.ToValue(value));
- }
- }
-
- /// <summary>
- /// Gets the value of a member of a given message.
- /// Used in serialization.
- /// </summary>
- /// <param name="message">The message instance to read the value from.</param>
- /// <returns>The string representation of the member's value.</returns>
- internal string GetValue(IProtocolMessage message) {
- return this.ToString(this.GetValueAsObject(message));
- }
-
- /// <summary>
- /// Gets whether the value has been set to something other than its CLR type default value.
- /// </summary>
- /// <param name="message">The message instance to check the value on.</param>
- /// <returns>True if the value is not the CLR default value.</returns>
- internal bool IsNondefaultValueSet(IProtocolMessage message) {
- if (this.memberDeclaredType.IsValueType) {
- return !this.GetValueAsObject(message).Equals(this.defaultMemberValue);
- } else {
- return this.defaultMemberValue != this.GetValueAsObject(message);
- }
- }
-
- /// <summary>
- /// Figures out the CLR default value for a given type.
- /// </summary>
- /// <param name="type">The type whose default value is being sought.</param>
- /// <returns>Either null, or some default value like 0 or 0.0.</returns>
- private static object DeriveDefaultValue(Type type) {
- if (type.IsValueType) {
- return Activator.CreateInstance(type);
- } else {
- return null;
- }
- }
-
- /// <summary>
- /// Adds a pair of type conversion functions to the static converstion map.
- /// </summary>
- /// <typeparam name="T">The custom type to convert to and from strings.</typeparam>
- /// <param name="toString">The function to convert the custom type to a string.</param>
- /// <param name="toValue">The function to convert a string to the custom type.</param>
- private static void Map<T>(Func<T, string> toString, Func<string, T> toValue) {
- Func<object, string> safeToString = obj => obj != null ? toString((T)obj) : null;
- Func<string, object> safeToT = str => str != null ? toValue(str) : default(T);
- converters.Add(typeof(T), new ValueMapping(safeToString, safeToT));
- }
-
- /// <summary>
- /// Checks whether a type is a nullable value type (i.e. int?)
- /// </summary>
- /// <param name="type">The type in question.</param>
- /// <returns>True if this is a nullable value type.</returns>
- private static bool IsNonNullableValueType(Type type) {
- if (!type.IsValueType) {
- return false;
- }
-
- if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {
- return false;
- }
-
- return true;
- }
-
- /// <summary>
- /// Converts a string representation of the member's value to the appropriate type.
- /// </summary>
- /// <param name="value">The string representation of the member's value.</param>
- /// <returns>An instance of the appropriate type for setting the member.</returns>
- private object ToValue(string value) {
- return this.converter.StringToValue(value);
- }
-
- /// <summary>
- /// Converts the member's value to its string representation.
- /// </summary>
- /// <param name="value">The value of the member.</param>
- /// <returns>The string representation of the member's value.</returns>
- private string ToString(object value) {
- return this.converter.ValueToString(value);
- }
-
- /// <summary>
- /// Gets the value of the message part, without converting it to/from a string.
- /// </summary>
- /// <param name="message">The message instance to read from.</param>
- /// <returns>The value of the member.</returns>
- private object GetValueAsObject(IProtocolMessage message) {
- if (this.property != null) {
- return this.property.GetValue(message, null);
- } else {
- return this.field.GetValue(message);
- }
- }
-
- /// <summary>
- /// Validates that the message part and its attribute have agreeable settings.
- /// </summary>
- /// <exception cref="ArgumentException">
- /// Thrown when a non-nullable value type is set as optional.
- /// </exception>
- private void ValidateSettings() {
- if (!this.IsRequired && IsNonNullableValueType(this.memberDeclaredType)) {
- MemberInfo member = (MemberInfo)this.field ?? this.property;
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- "Invalid combination: {0} on message type {1} is a non-nullable value type but is marked as optional.",
- member.Name,
- member.DeclaringType));
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessagePart.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Reflection { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Globalization; + using System.Net.Security; + using System.Reflection; + using System.Xml; + + /// <summary> + /// Describes an individual member of a message and assists in its serialization. + /// </summary> + internal class MessagePart { + /// <summary> + /// A map of converters that help serialize custom objects to string values and back again. + /// </summary> + private static readonly Dictionary<Type, ValueMapping> converters = new Dictionary<Type, ValueMapping>(); + + /// <summary> + /// The string-object conversion routines to use for this individual message part. + /// </summary> + private ValueMapping converter; + + /// <summary> + /// The property that this message part is associated with, if aplicable. + /// </summary> + private PropertyInfo property; + + /// <summary> + /// The field that this message part is associated with, if aplicable. + /// </summary> + private FieldInfo field; + + /// <summary> + /// The type of the message part. (Not the type of the message itself). + /// </summary> + private Type memberDeclaredType; + + /// <summary> + /// The default (uninitialized) value of the member inherent in its type. + /// </summary> + private object defaultMemberValue; + + /// <summary> + /// Initializes static members of the <see cref="MessagePart"/> class. + /// </summary> + [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Much more efficient initialization when we can call methods.")] + static MessagePart() { + Map<Uri>(uri => uri.AbsoluteUri, str => new Uri(str)); + Map<DateTime>(dt => XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc), str => XmlConvert.ToDateTime(str, XmlDateTimeSerializationMode.Utc)); + } + + /// <summary> + /// Initializes a new instance of the <see cref="MessagePart"/> class. + /// </summary> + /// <param name="member"> + /// A property or field of an <see cref="IProtocolMessage"/> implementing type + /// that has a <see cref="MessagePartAttribute"/> attached to it. + /// </param> + /// <param name="attribute"> + /// The attribute discovered on <paramref name="member"/> that describes the + /// serialization requirements of the message part. + /// </param> + internal MessagePart(MemberInfo member, MessagePartAttribute attribute) { + if (member == null) { + throw new ArgumentNullException("member"); + } + + this.field = member as FieldInfo; + this.property = member as PropertyInfo; + if (this.field == null && this.property == null) { + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.UnexpectedType, + typeof(FieldInfo).Name + ", " + typeof(PropertyInfo).Name, + member.GetType().Name), + "member"); + } + + if (attribute == null) { + throw new ArgumentNullException("attribute"); + } + + this.Name = attribute.Name ?? member.Name; + this.RequiredProtection = attribute.RequiredProtection; + this.IsRequired = attribute.IsRequired; + this.memberDeclaredType = (this.field != null) ? this.field.FieldType : this.property.PropertyType; + this.defaultMemberValue = DeriveDefaultValue(this.memberDeclaredType); + + if (!converters.TryGetValue(this.memberDeclaredType, out this.converter)) { + this.converter = new ValueMapping( + obj => obj != null ? obj.ToString() : null, + str => str != null ? Convert.ChangeType(str, this.memberDeclaredType, CultureInfo.InvariantCulture) : null); + } + + // Validate a sane combination of settings + this.ValidateSettings(); + } + + /// <summary> + /// Gets or sets the name to use when serializing or deserializing this parameter in a message. + /// </summary> + internal string Name { get; set; } + + /// <summary> + /// Gets or sets whether this message part must be signed. + /// </summary> + internal ProtectionLevel RequiredProtection { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether this message part is required for the + /// containing message to be valid. + /// </summary> + internal bool IsRequired { get; set; } + + /// <summary> + /// Sets the member of a given message to some given value. + /// Used in deserialization. + /// </summary> + /// <param name="message">The message instance containing the member whose value should be set.</param> + /// <param name="value">The string representation of the value to set.</param> + internal void SetValue(IProtocolMessage message, string value) { + if (this.property != null) { + this.property.SetValue(message, this.ToValue(value), null); + } else { + this.field.SetValue(message, this.ToValue(value)); + } + } + + /// <summary> + /// Gets the value of a member of a given message. + /// Used in serialization. + /// </summary> + /// <param name="message">The message instance to read the value from.</param> + /// <returns>The string representation of the member's value.</returns> + internal string GetValue(IProtocolMessage message) { + return this.ToString(this.GetValueAsObject(message)); + } + + /// <summary> + /// Gets whether the value has been set to something other than its CLR type default value. + /// </summary> + /// <param name="message">The message instance to check the value on.</param> + /// <returns>True if the value is not the CLR default value.</returns> + internal bool IsNondefaultValueSet(IProtocolMessage message) { + if (this.memberDeclaredType.IsValueType) { + return !this.GetValueAsObject(message).Equals(this.defaultMemberValue); + } else { + return this.defaultMemberValue != this.GetValueAsObject(message); + } + } + + /// <summary> + /// Figures out the CLR default value for a given type. + /// </summary> + /// <param name="type">The type whose default value is being sought.</param> + /// <returns>Either null, or some default value like 0 or 0.0.</returns> + private static object DeriveDefaultValue(Type type) { + if (type.IsValueType) { + return Activator.CreateInstance(type); + } else { + return null; + } + } + + /// <summary> + /// Adds a pair of type conversion functions to the static converstion map. + /// </summary> + /// <typeparam name="T">The custom type to convert to and from strings.</typeparam> + /// <param name="toString">The function to convert the custom type to a string.</param> + /// <param name="toValue">The function to convert a string to the custom type.</param> + private static void Map<T>(Func<T, string> toString, Func<string, T> toValue) { + Func<object, string> safeToString = obj => obj != null ? toString((T)obj) : null; + Func<string, object> safeToT = str => str != null ? toValue(str) : default(T); + converters.Add(typeof(T), new ValueMapping(safeToString, safeToT)); + } + + /// <summary> + /// Checks whether a type is a nullable value type (i.e. int?) + /// </summary> + /// <param name="type">The type in question.</param> + /// <returns>True if this is a nullable value type.</returns> + private static bool IsNonNullableValueType(Type type) { + if (!type.IsValueType) { + return false; + } + + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { + return false; + } + + return true; + } + + /// <summary> + /// Converts a string representation of the member's value to the appropriate type. + /// </summary> + /// <param name="value">The string representation of the member's value.</param> + /// <returns>An instance of the appropriate type for setting the member.</returns> + private object ToValue(string value) { + return this.converter.StringToValue(value); + } + + /// <summary> + /// Converts the member's value to its string representation. + /// </summary> + /// <param name="value">The value of the member.</param> + /// <returns>The string representation of the member's value.</returns> + private string ToString(object value) { + return this.converter.ValueToString(value); + } + + /// <summary> + /// Gets the value of the message part, without converting it to/from a string. + /// </summary> + /// <param name="message">The message instance to read from.</param> + /// <returns>The value of the member.</returns> + private object GetValueAsObject(IProtocolMessage message) { + if (this.property != null) { + return this.property.GetValue(message, null); + } else { + return this.field.GetValue(message); + } + } + + /// <summary> + /// Validates that the message part and its attribute have agreeable settings. + /// </summary> + /// <exception cref="ArgumentException"> + /// Thrown when a non-nullable value type is set as optional. + /// </exception> + private void ValidateSettings() { + if (!this.IsRequired && IsNonNullableValueType(this.memberDeclaredType)) { + MemberInfo member = (MemberInfo)this.field ?? this.property; + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + "Invalid combination: {0} on message type {1} is a non-nullable value type but is marked as optional.", + member.Name, + member.DeclaringType)); + } + } + } +} diff --git a/src/DotNetOAuth/Messaging/Reflection/ValueMapping.cs b/src/DotNetOpenAuth/Messaging/Reflection/ValueMapping.cs index e2d869b..bdc2d7f 100644 --- a/src/DotNetOAuth/Messaging/Reflection/ValueMapping.cs +++ b/src/DotNetOpenAuth/Messaging/Reflection/ValueMapping.cs @@ -1,42 +1,42 @@ -//-----------------------------------------------------------------------
-// <copyright file="ValueMapping.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging.Reflection {
- using System;
-
- /// <summary>
- /// A pair of conversion functions to map some type to a string and back again.
- /// </summary>
- internal struct ValueMapping {
- /// <summary>
- /// The mapping function that converts some custom type to a string.
- /// </summary>
- internal Func<object, string> ValueToString;
-
- /// <summary>
- /// The mapping function that converts a string to some custom type.
- /// </summary>
- internal Func<string, object> StringToValue;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueMapping"/> struct.
- /// </summary>
- /// <param name="toString">The mapping function that converts some custom type to a string.</param>
- /// <param name="toValue">The mapping function that converts a string to some custom type.</param>
- internal ValueMapping(Func<object, string> toString, Func<string, object> toValue) {
- if (toString == null) {
- throw new ArgumentNullException("toString");
- }
-
- if (toValue == null) {
- throw new ArgumentNullException("toValue");
- }
-
- this.ValueToString = toString;
- this.StringToValue = toValue;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ValueMapping.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Reflection { + using System; + + /// <summary> + /// A pair of conversion functions to map some type to a string and back again. + /// </summary> + internal struct ValueMapping { + /// <summary> + /// The mapping function that converts some custom type to a string. + /// </summary> + internal Func<object, string> ValueToString; + + /// <summary> + /// The mapping function that converts a string to some custom type. + /// </summary> + internal Func<string, object> StringToValue; + + /// <summary> + /// Initializes a new instance of the <see cref="ValueMapping"/> struct. + /// </summary> + /// <param name="toString">The mapping function that converts some custom type to a string.</param> + /// <param name="toValue">The mapping function that converts a string to some custom type.</param> + internal ValueMapping(Func<object, string> toString, Func<string, object> toValue) { + if (toString == null) { + throw new ArgumentNullException("toString"); + } + + if (toValue == null) { + throw new ArgumentNullException("toValue"); + } + + this.ValueToString = toString; + this.StringToValue = toValue; + } + } +} diff --git a/src/DotNetOAuth/Messaging/Response.cs b/src/DotNetOpenAuth/Messaging/Response.cs index 2bce887..02a4a0e 100644 --- a/src/DotNetOAuth/Messaging/Response.cs +++ b/src/DotNetOpenAuth/Messaging/Response.cs @@ -1,178 +1,178 @@ -//-----------------------------------------------------------------------
-// <copyright file="Response.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Diagnostics.CodeAnalysis;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Web;
-
- /// <summary>
- /// A protocol message (request or response) that passes between Consumer and Service Provider
- /// via the user agent using a redirect or form POST submission,
- /// OR a direct message response.
- /// </summary>
- /// <remarks>
- /// <para>An instance of this type describes the HTTP response that must be sent
- /// in response to the current HTTP request.</para>
- /// <para>It is important that this response make up the entire HTTP response.
- /// A hosting ASPX page should not be allowed to render its normal HTML output
- /// after this response is sent. The normal rendered output of an ASPX page
- /// can be canceled by calling <see cref="HttpResponse.End"/> after this message
- /// is sent on the response stream.</para>
- /// </remarks>
- public class Response {
- /// <summary>
- /// Initializes a new instance of the <see cref="Response"/> class.
- /// </summary>
- internal Response() {
- this.Status = HttpStatusCode.OK;
- this.Headers = new WebHeaderCollection();
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="Response"/> class
- /// based on the contents of an <see cref="HttpWebResponse"/>.
- /// </summary>
- /// <param name="response">The <see cref="HttpWebResponse"/> to clone.</param>
- internal Response(HttpWebResponse response) {
- this.Status = response.StatusCode;
- this.Headers = response.Headers;
- this.ResponseStream = new MemoryStream();
- using (Stream responseStream = response.GetResponseStream()) {
- responseStream.CopyTo(this.ResponseStream);
- this.ResponseStream.Seek(0, SeekOrigin.Begin);
- }
- }
-
- /// <summary>
- /// Gets the headers that must be included in the response to the user agent.
- /// </summary>
- /// <remarks>
- /// The headers in this collection are not meant to be a comprehensive list
- /// of exactly what should be sent, but are meant to augment whatever headers
- /// are generally included in a typical response.
- /// </remarks>
- public WebHeaderCollection Headers { get; internal set; }
-
- /// <summary>
- /// Gets the body of the HTTP response.
- /// </summary>
- public Stream ResponseStream { get; internal set; }
-
- /// <summary>
- /// Gets a value indicating whether the response stream is incomplete due
- /// to a length limitation imposed by the HttpWebRequest or calling method.
- /// </summary>
- public bool IsResponseTruncated { get; internal set; }
-
- /// <summary>
- /// Gets or sets the body of the response as a string.
- /// </summary>
- public string Body {
- get { return this.ResponseStream != null ? this.GetResponseReader().ReadToEnd() : null; }
- set { this.SetResponse(value); }
- }
-
- /// <summary>
- /// Gets the HTTP status code to use in the HTTP response.
- /// </summary>
- public HttpStatusCode Status { get; internal set; }
-
- /// <summary>
- /// Gets or sets a reference to the actual protocol message that
- /// is being sent via the user agent.
- /// </summary>
- internal IProtocolMessage OriginalMessage { get; set; }
-
- /// <summary>
- /// Gets the URI that, when requested with an HTTP GET request,
- /// would transmit the message that normally would be transmitted via a user agent redirect.
- /// </summary>
- /// <remarks>
- /// This is useful for desktop applications that will spawn a user agent to transmit the message
- /// rather than cause a redirect.
- /// </remarks>
- internal Uri DirectUriRequest {
- get {
- var message = this.OriginalMessage as IDirectedProtocolMessage;
- if (message == null) {
- throw new InvalidOperationException(); // this only makes sense for directed messages (indirect responses)
- }
-
- var serializer = MessageSerializer.Get(message.GetType());
- var fields = serializer.Serialize(message);
- UriBuilder builder = new UriBuilder(message.Recipient);
- MessagingUtilities.AppendQueryArgs(builder, fields);
- return builder.Uri;
- }
- }
-
- /// <summary>
- /// Creates a text reader for the response stream.
- /// </summary>
- /// <returns>The text reader, initialized for the proper encoding.</returns>
- [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Costly operation")]
- public StreamReader GetResponseReader() {
- this.ResponseStream.Seek(0, SeekOrigin.Begin);
- string contentEncoding = this.Headers[HttpResponseHeader.ContentEncoding];
- if (string.IsNullOrEmpty(contentEncoding)) {
- return new StreamReader(this.ResponseStream);
- } else {
- return new StreamReader(this.ResponseStream, Encoding.GetEncoding(contentEncoding));
- }
- }
-
- /// <summary>
- /// Automatically sends the appropriate response to the user agent.
- /// Requires a current HttpContext.
- /// </summary>
- public void Send() {
- if (HttpContext.Current == null) {
- throw new InvalidOperationException(MessagingStrings.CurrentHttpContextRequired);
- }
-
- HttpContext.Current.Response.Clear();
- HttpContext.Current.Response.StatusCode = (int)this.Status;
- MessagingUtilities.ApplyHeadersToResponse(this.Headers, HttpContext.Current.Response);
- if (this.ResponseStream != null) {
- try {
- this.ResponseStream.CopyTo(HttpContext.Current.Response.OutputStream);
- } catch (HttpException ex) {
- if (ex.ErrorCode == -2147467259 && HttpContext.Current.Response.Output != null) {
- // Test scenarios can generate this, since the stream is being spoofed:
- // System.Web.HttpException: OutputStream is not available when a custom TextWriter is used.
- HttpContext.Current.Response.Output.Write(this.Body);
- } else {
- throw;
- }
- }
- }
- HttpContext.Current.Response.End();
- }
-
- /// <summary>
- /// Sets the response to some string, encoded as UTF-8.
- /// </summary>
- /// <param name="body">The string to set the response to.</param>
- internal void SetResponse(string body) {
- if (body == null) {
- this.ResponseStream = null;
- return;
- }
-
- Encoding encoding = Encoding.UTF8;
- this.Headers[HttpResponseHeader.ContentEncoding] = encoding.HeaderName;
- this.ResponseStream = new MemoryStream();
- StreamWriter writer = new StreamWriter(this.ResponseStream, encoding);
- writer.Write(body);
- writer.Flush();
- this.ResponseStream.Seek(0, SeekOrigin.Begin);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="Response.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Diagnostics.CodeAnalysis; + using System.IO; + using System.Net; + using System.Text; + using System.Web; + + /// <summary> + /// A protocol message (request or response) that passes between Consumer and Service Provider + /// via the user agent using a redirect or form POST submission, + /// OR a direct message response. + /// </summary> + /// <remarks> + /// <para>An instance of this type describes the HTTP response that must be sent + /// in response to the current HTTP request.</para> + /// <para>It is important that this response make up the entire HTTP response. + /// A hosting ASPX page should not be allowed to render its normal HTML output + /// after this response is sent. The normal rendered output of an ASPX page + /// can be canceled by calling <see cref="HttpResponse.End"/> after this message + /// is sent on the response stream.</para> + /// </remarks> + public class Response { + /// <summary> + /// Initializes a new instance of the <see cref="Response"/> class. + /// </summary> + internal Response() { + this.Status = HttpStatusCode.OK; + this.Headers = new WebHeaderCollection(); + } + + /// <summary> + /// Initializes a new instance of the <see cref="Response"/> class + /// based on the contents of an <see cref="HttpWebResponse"/>. + /// </summary> + /// <param name="response">The <see cref="HttpWebResponse"/> to clone.</param> + internal Response(HttpWebResponse response) { + this.Status = response.StatusCode; + this.Headers = response.Headers; + this.ResponseStream = new MemoryStream(); + using (Stream responseStream = response.GetResponseStream()) { + responseStream.CopyTo(this.ResponseStream); + this.ResponseStream.Seek(0, SeekOrigin.Begin); + } + } + + /// <summary> + /// Gets the headers that must be included in the response to the user agent. + /// </summary> + /// <remarks> + /// The headers in this collection are not meant to be a comprehensive list + /// of exactly what should be sent, but are meant to augment whatever headers + /// are generally included in a typical response. + /// </remarks> + public WebHeaderCollection Headers { get; internal set; } + + /// <summary> + /// Gets the body of the HTTP response. + /// </summary> + public Stream ResponseStream { get; internal set; } + + /// <summary> + /// Gets a value indicating whether the response stream is incomplete due + /// to a length limitation imposed by the HttpWebRequest or calling method. + /// </summary> + public bool IsResponseTruncated { get; internal set; } + + /// <summary> + /// Gets or sets the body of the response as a string. + /// </summary> + public string Body { + get { return this.ResponseStream != null ? this.GetResponseReader().ReadToEnd() : null; } + set { this.SetResponse(value); } + } + + /// <summary> + /// Gets the HTTP status code to use in the HTTP response. + /// </summary> + public HttpStatusCode Status { get; internal set; } + + /// <summary> + /// Gets or sets a reference to the actual protocol message that + /// is being sent via the user agent. + /// </summary> + internal IProtocolMessage OriginalMessage { get; set; } + + /// <summary> + /// Gets the URI that, when requested with an HTTP GET request, + /// would transmit the message that normally would be transmitted via a user agent redirect. + /// </summary> + /// <remarks> + /// This is useful for desktop applications that will spawn a user agent to transmit the message + /// rather than cause a redirect. + /// </remarks> + internal Uri DirectUriRequest { + get { + var message = this.OriginalMessage as IDirectedProtocolMessage; + if (message == null) { + throw new InvalidOperationException(); // this only makes sense for directed messages (indirect responses) + } + + var serializer = MessageSerializer.Get(message.GetType()); + var fields = serializer.Serialize(message); + UriBuilder builder = new UriBuilder(message.Recipient); + MessagingUtilities.AppendQueryArgs(builder, fields); + return builder.Uri; + } + } + + /// <summary> + /// Creates a text reader for the response stream. + /// </summary> + /// <returns>The text reader, initialized for the proper encoding.</returns> + [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Costly operation")] + public StreamReader GetResponseReader() { + this.ResponseStream.Seek(0, SeekOrigin.Begin); + string contentEncoding = this.Headers[HttpResponseHeader.ContentEncoding]; + if (string.IsNullOrEmpty(contentEncoding)) { + return new StreamReader(this.ResponseStream); + } else { + return new StreamReader(this.ResponseStream, Encoding.GetEncoding(contentEncoding)); + } + } + + /// <summary> + /// Automatically sends the appropriate response to the user agent. + /// Requires a current HttpContext. + /// </summary> + public void Send() { + if (HttpContext.Current == null) { + throw new InvalidOperationException(MessagingStrings.CurrentHttpContextRequired); + } + + HttpContext.Current.Response.Clear(); + HttpContext.Current.Response.StatusCode = (int)this.Status; + MessagingUtilities.ApplyHeadersToResponse(this.Headers, HttpContext.Current.Response); + if (this.ResponseStream != null) { + try { + this.ResponseStream.CopyTo(HttpContext.Current.Response.OutputStream); + } catch (HttpException ex) { + if (ex.ErrorCode == -2147467259 && HttpContext.Current.Response.Output != null) { + // Test scenarios can generate this, since the stream is being spoofed: + // System.Web.HttpException: OutputStream is not available when a custom TextWriter is used. + HttpContext.Current.Response.Output.Write(this.Body); + } else { + throw; + } + } + } + HttpContext.Current.Response.End(); + } + + /// <summary> + /// Sets the response to some string, encoded as UTF-8. + /// </summary> + /// <param name="body">The string to set the response to.</param> + internal void SetResponse(string body) { + if (body == null) { + this.ResponseStream = null; + return; + } + + Encoding encoding = Encoding.UTF8; + this.Headers[HttpResponseHeader.ContentEncoding] = encoding.HeaderName; + this.ResponseStream = new MemoryStream(); + StreamWriter writer = new StreamWriter(this.ResponseStream, encoding); + writer.Write(body); + writer.Flush(); + this.ResponseStream.Seek(0, SeekOrigin.Begin); + } + } +} diff --git a/src/DotNetOAuth/Messaging/UnprotectedMessageException.cs b/src/DotNetOpenAuth/Messaging/UnprotectedMessageException.cs index 3e824f2..9d04cd8 100644 --- a/src/DotNetOAuth/Messaging/UnprotectedMessageException.cs +++ b/src/DotNetOpenAuth/Messaging/UnprotectedMessageException.cs @@ -1,37 +1,37 @@ -//-----------------------------------------------------------------------
-// <copyright file="UnprotectedMessageException.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.Messaging {
- using System;
- using System.Globalization;
-
- /// <summary>
- /// An exception thrown when messages cannot receive all the protections they require.
- /// </summary>
- [Serializable]
- internal class UnprotectedMessageException : ProtocolException {
- /// <summary>
- /// Initializes a new instance of the <see cref="UnprotectedMessageException"/> class.
- /// </summary>
- /// <param name="faultedMessage">The message whose protection requirements could not be met.</param>
- /// <param name="appliedProtection">The protection requirements that were fulfilled.</param>
- internal UnprotectedMessageException(IProtocolMessage faultedMessage, MessageProtections appliedProtection)
- : base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.InsufficentMessageProtection, faultedMessage.RequiredProtection, appliedProtection), faultedMessage) {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="UnprotectedMessageException"/> class.
- /// </summary>
- /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/>
- /// that holds the serialized object data about the exception being thrown.</param>
- /// <param name="context">The System.Runtime.Serialization.StreamingContext
- /// that contains contextual information about the source or destination.</param>
- protected UnprotectedMessageException(
- System.Runtime.Serialization.SerializationInfo info,
- System.Runtime.Serialization.StreamingContext context)
- : base(info, context) { }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="UnprotectedMessageException.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Globalization; + + /// <summary> + /// An exception thrown when messages cannot receive all the protections they require. + /// </summary> + [Serializable] + internal class UnprotectedMessageException : ProtocolException { + /// <summary> + /// Initializes a new instance of the <see cref="UnprotectedMessageException"/> class. + /// </summary> + /// <param name="faultedMessage">The message whose protection requirements could not be met.</param> + /// <param name="appliedProtection">The protection requirements that were fulfilled.</param> + internal UnprotectedMessageException(IProtocolMessage faultedMessage, MessageProtections appliedProtection) + : base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.InsufficentMessageProtection, faultedMessage.RequiredProtection, appliedProtection), faultedMessage) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="UnprotectedMessageException"/> class. + /// </summary> + /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/> + /// that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The System.Runtime.Serialization.StreamingContext + /// that contains contextual information about the source or destination.</param> + protected UnprotectedMessageException( + System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) + : base(info, context) { } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs index a0878aa..604450f 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/HmacSha1SigningBindingElement.cs @@ -1,48 +1,48 @@ -//-----------------------------------------------------------------------
-// <copyright file="HmacSha1SigningBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Security.Cryptography;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A binding element that signs outgoing messages and verifies the signature on incoming messages.
- /// </summary>
- public class HmacSha1SigningBindingElement : SigningBindingElementBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="HmacSha1SigningBindingElement"/> class
- /// </summary>
- public HmacSha1SigningBindingElement()
- : base("HMAC-SHA1") {
- }
-
- /// <summary>
- /// Calculates a signature for a given message.
- /// </summary>
- /// <param name="message">The message to sign.</param>
- /// <returns>The signature for the message.</returns>
- /// <remarks>
- /// This method signs the message per OAuth 1.0 section 9.2.
- /// </remarks>
- protected override string GetSignature(ITamperResistantOAuthMessage message) {
- string key = GetConsumerAndTokenSecretString(message);
- HashAlgorithm hasher = new HMACSHA1(Encoding.ASCII.GetBytes(key));
- string baseString = ConstructSignatureBaseString(message);
- byte[] digest = hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString));
- return Convert.ToBase64String(digest);
- }
-
- /// <summary>
- /// Clones this instance.
- /// </summary>
- /// <returns>A new instance of the binding element.</returns>
- protected override ITamperProtectionChannelBindingElement Clone() {
- return new HmacSha1SigningBindingElement();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="HmacSha1SigningBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Security.Cryptography; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A binding element that signs outgoing messages and verifies the signature on incoming messages. + /// </summary> + public class HmacSha1SigningBindingElement : SigningBindingElementBase { + /// <summary> + /// Initializes a new instance of the <see cref="HmacSha1SigningBindingElement"/> class + /// </summary> + public HmacSha1SigningBindingElement() + : base("HMAC-SHA1") { + } + + /// <summary> + /// Calculates a signature for a given message. + /// </summary> + /// <param name="message">The message to sign.</param> + /// <returns>The signature for the message.</returns> + /// <remarks> + /// This method signs the message per OAuth 1.0 section 9.2. + /// </remarks> + protected override string GetSignature(ITamperResistantOAuthMessage message) { + string key = GetConsumerAndTokenSecretString(message); + HashAlgorithm hasher = new HMACSHA1(Encoding.ASCII.GetBytes(key)); + string baseString = ConstructSignatureBaseString(message); + byte[] digest = hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString)); + return Convert.ToBase64String(digest); + } + + /// <summary> + /// Clones this instance. + /// </summary> + /// <returns>A new instance of the binding element.</returns> + protected override ITamperProtectionChannelBindingElement Clone() { + return new HmacSha1SigningBindingElement(); + } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/IOAuthDirectedMessage.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/IOAuthDirectedMessage.cs index 9151464..5e4475b 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/IOAuthDirectedMessage.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/IOAuthDirectedMessage.cs @@ -1,25 +1,25 @@ -//-----------------------------------------------------------------------
-// <copyright file="IOAuthDirectedMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// Additional properties that apply specifically to OAuth messages.
- /// </summary>
- public interface IOAuthDirectedMessage : IDirectedProtocolMessage {
- /// <summary>
- /// Gets the preferred method of transport for the message.
- /// </summary>
- HttpDeliveryMethods HttpMethods { get; }
-
- /// <summary>
- /// Gets or sets the URL of the intended receiver of this message.
- /// </summary>
- new Uri Recipient { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IOAuthDirectedMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// Additional properties that apply specifically to OAuth messages. + /// </summary> + public interface IOAuthDirectedMessage : IDirectedProtocolMessage { + /// <summary> + /// Gets the preferred method of transport for the message. + /// </summary> + HttpDeliveryMethods HttpMethods { get; } + + /// <summary> + /// Gets or sets the URL of the intended receiver of this message. + /// </summary> + new Uri Recipient { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs index aaba53b..45402b8 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs @@ -1,41 +1,41 @@ -//-----------------------------------------------------------------------
-// <copyright file="ITamperResistantOAuthMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System.Collections.Generic;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
-
- /// <summary>
- /// An interface that OAuth messages implement to support signing.
- /// </summary>
- public interface ITamperResistantOAuthMessage : IOAuthDirectedMessage, ITamperResistantProtocolMessage {
- /// <summary>
- /// Gets or sets the method used to sign the message.
- /// </summary>
- string SignatureMethod { get; set; }
-
- /// <summary>
- /// Gets or sets the Token Secret used to sign the message.
- /// </summary>
- string TokenSecret { get; set; }
-
- /// <summary>
- /// Gets or sets the Consumer key.
- /// </summary>
- string ConsumerKey { get; set; }
-
- /// <summary>
- /// Gets or sets the Consumer Secret used to sign the message.
- /// </summary>
- string ConsumerSecret { get; set; }
-
- /// <summary>
- /// Gets or sets the HTTP method that will be used to transmit the message.
- /// </summary>
- string HttpMethod { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ITamperResistantOAuthMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System.Collections.Generic; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + + /// <summary> + /// An interface that OAuth messages implement to support signing. + /// </summary> + public interface ITamperResistantOAuthMessage : IOAuthDirectedMessage, ITamperResistantProtocolMessage { + /// <summary> + /// Gets or sets the method used to sign the message. + /// </summary> + string SignatureMethod { get; set; } + + /// <summary> + /// Gets or sets the Token Secret used to sign the message. + /// </summary> + string TokenSecret { get; set; } + + /// <summary> + /// Gets or sets the Consumer key. + /// </summary> + string ConsumerKey { get; set; } + + /// <summary> + /// Gets or sets the Consumer Secret used to sign the message. + /// </summary> + string ConsumerSecret { get; set; } + + /// <summary> + /// Gets or sets the HTTP method that will be used to transmit the message. + /// </summary> + string HttpMethod { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/ITokenGenerator.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenGenerator.cs index 888ba05..ce22479 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/ITokenGenerator.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenGenerator.cs @@ -1,40 +1,40 @@ -//-----------------------------------------------------------------------
-// <copyright file="ITokenGenerator.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- /// <summary>
- /// An interface allowing OAuth hosts to inject their own algorithm for generating tokens and secrets.
- /// </summary>
- public interface ITokenGenerator {
- /// <summary>
- /// Generates a new token to represent a not-yet-authorized request to access protected resources.
- /// </summary>
- /// <param name="consumerKey">The consumer that requested this token.</param>
- /// <returns>The newly generated token.</returns>
- /// <remarks>
- /// This method should not store the newly generated token in any persistent store.
- /// This will be done in <see cref="ITokenManager.StoreNewRequestToken"/>.
- /// </remarks>
- string GenerateRequestToken(string consumerKey);
-
- /// <summary>
- /// Generates a new token to represent an authorized request to access protected resources.
- /// </summary>
- /// <param name="consumerKey">The consumer that requested this token.</param>
- /// <returns>The newly generated token.</returns>
- /// <remarks>
- /// This method should not store the newly generated token in any persistent store.
- /// This will be done in <see cref="ITokenManager.ExpireRequestTokenAndStoreNewAccessToken"/>.
- /// </remarks>
- string GenerateAccessToken(string consumerKey);
-
- /// <summary>
- /// Returns a cryptographically strong random string for use as a token secret.
- /// </summary>
- /// <returns>The generated string.</returns>
- string GenerateSecret();
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ITokenGenerator.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + /// <summary> + /// An interface allowing OAuth hosts to inject their own algorithm for generating tokens and secrets. + /// </summary> + public interface ITokenGenerator { + /// <summary> + /// Generates a new token to represent a not-yet-authorized request to access protected resources. + /// </summary> + /// <param name="consumerKey">The consumer that requested this token.</param> + /// <returns>The newly generated token.</returns> + /// <remarks> + /// This method should not store the newly generated token in any persistent store. + /// This will be done in <see cref="ITokenManager.StoreNewRequestToken"/>. + /// </remarks> + string GenerateRequestToken(string consumerKey); + + /// <summary> + /// Generates a new token to represent an authorized request to access protected resources. + /// </summary> + /// <param name="consumerKey">The consumer that requested this token.</param> + /// <returns>The newly generated token.</returns> + /// <remarks> + /// This method should not store the newly generated token in any persistent store. + /// This will be done in <see cref="ITokenManager.ExpireRequestTokenAndStoreNewAccessToken"/>. + /// </remarks> + string GenerateAccessToken(string consumerKey); + + /// <summary> + /// Returns a cryptographically strong random string for use as a token secret. + /// </summary> + /// <returns>The generated string.</returns> + string GenerateSecret(); + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/ITokenManager.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenManager.cs index 257e44e..14ba89a 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/ITokenManager.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/ITokenManager.cs @@ -1,80 +1,80 @@ -//-----------------------------------------------------------------------
-// <copyright file="ITokenManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// An interface OAuth hosts must implement for persistent storage and recall of tokens and secrets.
- /// </summary>
- public interface ITokenManager {
- /// <summary>
- /// Gets the Consumer Secret given a Consumer Key.
- /// </summary>
- /// <param name="consumerKey">The Consumer Key.</param>
- /// <returns>The Consumer Secret.</returns>
- /// <exception cref="ArgumentException">Thrown if the consumer key cannot be found.</exception>
- /// <remarks>
- /// TODO: In the case of RSA hashing, the consumer may not have a secret
- /// like this. What to do in that case?
- /// </remarks>
- string GetConsumerSecret(string consumerKey);
-
- /// <summary>
- /// Gets the Token Secret given a request or access token.
- /// </summary>
- /// <param name="token">The request or access token.</param>
- /// <returns>The secret associated with the given token.</returns>
- /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception>
- string GetTokenSecret(string token);
-
- /// <summary>
- /// Stores a newly generated unauthorized request token, secret, and optional
- /// application-specific parameters for later recall.
- /// </summary>
- /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param>
- /// <param name="response">The response message that includes the unauthorized request token.</param>
- /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception>
- void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response);
-
- /// <summary>
- /// Checks whether a given request token has already been authorized
- /// by some user for use by the Consumer that requested it.
- /// </summary>
- /// <param name="requestToken">The Consumer's request token.</param>
- /// <returns>
- /// True if the request token has already been fully authorized by the user
- /// who owns the relevant protected resources. False if the token has not yet
- /// been authorized, has expired or does not exist.
- /// </returns>
- bool IsRequestTokenAuthorized(string requestToken);
-
- /// <summary>
- /// Deletes a request token and its associated secret and stores a new access token and secret.
- /// </summary>
- /// <param name="consumerKey">The Consumer that is exchanging its request token for an access token.</param>
- /// <param name="requestToken">The Consumer's request token that should be deleted/expired.</param>
- /// <param name="accessToken">The new access token that is being issued to the Consumer.</param>
- /// <param name="accessTokenSecret">The secret associated with the newly issued access token.</param>
- /// <remarks>
- /// Any scope of granted privileges associated with the request token from the
- /// original call to <see cref="StoreNewRequestToken"/> should be carried over
- /// to the new Access Token.
- /// </remarks>
- void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret);
-
- /// <summary>
- /// Classifies a token as a request token or an access token.
- /// </summary>
- /// <param name="token">The token to classify.</param>
- /// <returns>Request or Access token, or invalid if the token is not recognized.</returns>
- TokenType GetTokenType(string token);
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ITokenManager.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// An interface OAuth hosts must implement for persistent storage and recall of tokens and secrets. + /// </summary> + public interface ITokenManager { + /// <summary> + /// Gets the Consumer Secret given a Consumer Key. + /// </summary> + /// <param name="consumerKey">The Consumer Key.</param> + /// <returns>The Consumer Secret.</returns> + /// <exception cref="ArgumentException">Thrown if the consumer key cannot be found.</exception> + /// <remarks> + /// TODO: In the case of RSA hashing, the consumer may not have a secret + /// like this. What to do in that case? + /// </remarks> + string GetConsumerSecret(string consumerKey); + + /// <summary> + /// Gets the Token Secret given a request or access token. + /// </summary> + /// <param name="token">The request or access token.</param> + /// <returns>The secret associated with the given token.</returns> + /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception> + string GetTokenSecret(string token); + + /// <summary> + /// Stores a newly generated unauthorized request token, secret, and optional + /// application-specific parameters for later recall. + /// </summary> + /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param> + /// <param name="response">The response message that includes the unauthorized request token.</param> + /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception> + void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response); + + /// <summary> + /// Checks whether a given request token has already been authorized + /// by some user for use by the Consumer that requested it. + /// </summary> + /// <param name="requestToken">The Consumer's request token.</param> + /// <returns> + /// True if the request token has already been fully authorized by the user + /// who owns the relevant protected resources. False if the token has not yet + /// been authorized, has expired or does not exist. + /// </returns> + bool IsRequestTokenAuthorized(string requestToken); + + /// <summary> + /// Deletes a request token and its associated secret and stores a new access token and secret. + /// </summary> + /// <param name="consumerKey">The Consumer that is exchanging its request token for an access token.</param> + /// <param name="requestToken">The Consumer's request token that should be deleted/expired.</param> + /// <param name="accessToken">The new access token that is being issued to the Consumer.</param> + /// <param name="accessTokenSecret">The secret associated with the newly issued access token.</param> + /// <remarks> + /// Any scope of granted privileges associated with the request token from the + /// original call to <see cref="StoreNewRequestToken"/> should be carried over + /// to the new Access Token. + /// </remarks> + void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret); + + /// <summary> + /// Classifies a token as a request token or an access token. + /// </summary> + /// <param name="token">The token to classify.</param> + /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> + TokenType GetTokenType(string token); + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/IWebRequestHandler.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/IWebRequestHandler.cs index d4a56f3..9767875 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/IWebRequestHandler.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/IWebRequestHandler.cs @@ -1,31 +1,31 @@ -//-----------------------------------------------------------------------
-// <copyright file="IWebRequestHandler.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System.IO;
- using System.Net;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A contract for <see cref="HttpWebRequest"/> handling.
- /// </summary>
- internal interface IWebRequestHandler {
- /// <summary>
- /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
- /// </summary>
- /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
- /// <returns>The writer the caller should write out the entity data to.</returns>
- TextWriter GetRequestStream(HttpWebRequest request);
-
- /// <summary>
- /// Processes an <see cref="HttpWebRequest"/> and converts the
- /// <see cref="HttpWebResponse"/> to a <see cref="Response"/> instance.
- /// </summary>
- /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
- /// <returns>An instance of <see cref="Response"/> describing the response.</returns>
- Response GetResponse(HttpWebRequest request);
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="IWebRequestHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System.IO; + using System.Net; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A contract for <see cref="HttpWebRequest"/> handling. + /// </summary> + internal interface IWebRequestHandler { + /// <summary> + /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. + /// </summary> + /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> + /// <returns>The writer the caller should write out the entity data to.</returns> + TextWriter GetRequestStream(HttpWebRequest request); + + /// <summary> + /// Processes an <see cref="HttpWebRequest"/> and converts the + /// <see cref="HttpWebResponse"/> to a <see cref="Response"/> instance. + /// </summary> + /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> + /// <returns>An instance of <see cref="Response"/> describing the response.</returns> + Response GetResponse(HttpWebRequest request); + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/OAuthChannel.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs index 4be38a0..736594e 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/OAuthChannel.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs @@ -1,397 +1,397 @@ -//-----------------------------------------------------------------------
-// <copyright file="OAuthChannel.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Web;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.Messaging.Reflection;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// An OAuth-specific implementation of the <see cref="Channel"/> class.
- /// </summary>
- internal class OAuthChannel : Channel {
- /// <summary>
- /// The object that will transmit <see cref="HttpWebRequest"/> instances
- /// and return their responses.
- /// </summary>
- private IWebRequestHandler webRequestHandler;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthChannel"/> class.
- /// </summary>
- /// <param name="signingBindingElement">The binding element to use for signing.</param>
- /// <param name="store">The web application store to use for nonces.</param>
- /// <param name="tokenManager">The token manager instance to use.</param>
- /// <param name="isConsumer">A value indicating whether this channel is being constructed for a Consumer (as opposed to a Service Provider).</param>
- internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, bool isConsumer)
- : this(
- signingBindingElement,
- store,
- tokenManager,
- isConsumer ? (IMessageTypeProvider)new OAuthConsumerMessageTypeProvider() : new OAuthServiceProviderMessageTypeProvider(tokenManager),
- new StandardWebRequestHandler()) {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthChannel"/> class.
- /// </summary>
- /// <param name="signingBindingElement">The binding element to use for signing.</param>
- /// <param name="store">The web application store to use for nonces.</param>
- /// <param name="tokenManager">The ITokenManager instance to use.</param>
- /// <param name="messageTypeProvider">
- /// An injected message type provider instance.
- /// Except for mock testing, this should always be one of
- /// <see cref="OAuthConsumerMessageTypeProvider"/> or <see cref="OAuthServiceProviderMessageTypeProvider"/>.
- /// </param>
- /// <param name="webRequestHandler">
- /// An instance to a <see cref="IWebRequestHandler"/> that will be used when submitting HTTP
- /// requests and waiting for responses.
- /// </param>
- /// <remarks>
- /// This overload for testing purposes only.
- /// </remarks>
- internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, IMessageTypeProvider messageTypeProvider, IWebRequestHandler webRequestHandler)
- : base(messageTypeProvider, new OAuthHttpMethodBindingElement(), signingBindingElement, new StandardExpirationBindingElement(), new StandardReplayProtectionBindingElement(store)) {
- if (tokenManager == null) {
- throw new ArgumentNullException("tokenManager");
- }
- if (webRequestHandler == null) {
- throw new ArgumentNullException("webRequestHandler");
- }
-
- this.webRequestHandler = webRequestHandler;
- this.TokenManager = tokenManager;
- if (signingBindingElement.SignatureCallback != null) {
- throw new ArgumentException(Strings.SigningElementAlreadyAssociatedWithChannel, "signingBindingElement");
- }
-
- signingBindingElement.SignatureCallback = this.SignatureCallback;
- }
-
- /// <summary>
- /// Gets or sets the Consumer web application path.
- /// </summary>
- internal Uri Realm { get; set; }
-
- /// <summary>
- /// Gets the token manager being used.
- /// </summary>
- protected internal ITokenManager TokenManager { get; private set; }
-
- /// <summary>
- /// Encodes the names and values that are part of the message per OAuth 1.0 section 5.1.
- /// </summary>
- /// <param name="message">The message with data to encode.</param>
- /// <returns>A dictionary of name-value pairs with their strings encoded.</returns>
- internal static IDictionary<string, string> GetEncodedParameters(IProtocolMessage message) {
- var encodedDictionary = new Dictionary<string, string>();
- EncodeParameters(new MessageDictionary(message), encodedDictionary);
- return encodedDictionary;
- }
-
- /// <summary>
- /// Encodes the names and values in a dictionary per OAuth 1.0 section 5.1.
- /// </summary>
- /// <param name="source">The dictionary with names and values to encode.</param>
- /// <param name="destination">The dictionary to add the encoded pairs to.</param>
- internal static void EncodeParameters(IDictionary<string, string> source, IDictionary<string, string> destination) {
- if (source == null) {
- throw new ArgumentNullException("source");
- }
- if (destination == null) {
- throw new ArgumentNullException("destination");
- }
-
- foreach (var pair in source) {
- var key = Uri.EscapeDataString(pair.Key);
- var value = Uri.EscapeDataString(pair.Value);
- destination.Add(key, value);
- }
- }
-
- /// <summary>
- /// Initializes a web request for sending by attaching a message to it.
- /// Use this method to prepare a protected resource request that you do NOT
- /// expect an OAuth message response to.
- /// </summary>
- /// <param name="request">The message to attach.</param>
- /// <returns>The initialized web request.</returns>
- internal HttpWebRequest InitializeRequest(IDirectedProtocolMessage request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- PrepareMessageForSending(request);
- return this.InitializeRequestInternal(request);
- }
-
- /// <summary>
- /// Searches an incoming HTTP request for data that could be used to assemble
- /// a protocol request message.
- /// </summary>
- /// <param name="request">The HTTP request to search.</param>
- /// <returns>A dictionary of data in the request. Should never be null, but may be empty.</returns>
- protected override IProtocolMessage ReadFromRequestInternal(HttpRequestInfo request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- // First search the Authorization header. Use it exclusively if it's present.
- string authorization = request.Headers[HttpRequestHeader.Authorization];
- if (authorization != null) {
- string[] authorizationSections = authorization.Split(';'); // TODO: is this the right delimiter?
- string oauthPrefix = Protocol.Default.AuthorizationHeaderScheme + " ";
-
- // The Authorization header may have multiple uses, and OAuth may be just one of them.
- // Go through each one looking for an OAuth one.
- foreach (string auth in authorizationSections) {
- string trimmedAuth = auth.Trim();
- if (trimmedAuth.StartsWith(oauthPrefix, StringComparison.Ordinal)) {
- // We found an Authorization: OAuth header.
- // Parse it according to the rules in section 5.4.1 of the V1.0 spec.
- var fields = new Dictionary<string, string>();
- foreach (string stringPair in trimmedAuth.Substring(oauthPrefix.Length).Split(',')) {
- string[] keyValueStringPair = stringPair.Trim().Split('=');
- string key = Uri.UnescapeDataString(keyValueStringPair[0]);
- string value = Uri.UnescapeDataString(keyValueStringPair[1].Trim('"'));
- fields.Add(key, value);
- }
-
- return this.Receive(fields, request.GetRecipient());
- }
- }
- }
-
- // We didn't find an OAuth authorization header. Revert to other payload methods.
- IProtocolMessage message = base.ReadFromRequestInternal(request);
-
- // Add receiving HTTP transport information required for signature generation.
- var signedMessage = message as ITamperResistantOAuthMessage;
- if (signedMessage != null) {
- signedMessage.Recipient = request.Url;
- signedMessage.HttpMethod = request.HttpMethod;
- }
-
- return message;
- }
-
- /// <summary>
- /// Gets the protocol message that may be in the given HTTP response stream.
- /// </summary>
- /// <param name="responseStream">The response that is anticipated to contain an OAuth message.</param>
- /// <returns>The deserialized message, if one is found. Null otherwise.</returns>
- protected override IProtocolMessage ReadFromResponseInternal(Stream responseStream) {
- if (responseStream == null) {
- throw new ArgumentNullException("responseStream");
- }
-
- using (StreamReader reader = new StreamReader(responseStream)) {
- string response = reader.ReadToEnd();
- var fields = HttpUtility.ParseQueryString(response).ToDictionary();
- return Receive(fields, null);
- }
- }
-
- /// <summary>
- /// Sends a direct message to a remote party and waits for the response.
- /// </summary>
- /// <param name="request">The message to send.</param>
- /// <returns>The remote party's response.</returns>
- protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) {
- HttpWebRequest httpRequest = this.InitializeRequestInternal(request);
-
- Response response = this.webRequestHandler.GetResponse(httpRequest);
- if (response.ResponseStream == null) {
- return null;
- }
- var responseFields = HttpUtility.ParseQueryString(response.Body).ToDictionary();
- Type messageType = this.MessageTypeProvider.GetResponseMessageType(request, responseFields);
- if (messageType == null) {
- return null;
- }
- var responseSerialize = MessageSerializer.Get(messageType);
- var responseMessage = responseSerialize.Deserialize(responseFields, null);
-
- return responseMessage;
- }
-
- /// <summary>
- /// Queues a message for sending in the response stream where the fields
- /// are sent in the response stream in querystring style.
- /// </summary>
- /// <param name="response">The message to send as a response.</param>
- /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
- /// <remarks>
- /// This method implements spec V1.0 section 5.3.
- /// </remarks>
- protected override Response SendDirectMessageResponse(IProtocolMessage response) {
- if (response == null) {
- throw new ArgumentNullException("response");
- }
-
- MessageSerializer serializer = MessageSerializer.Get(response.GetType());
- var fields = serializer.Serialize(response);
- string responseBody = MessagingUtilities.CreateQueryString(fields);
-
- Response encodedResponse = new Response {
- Body = responseBody,
- OriginalMessage = response,
- Status = HttpStatusCode.OK,
- Headers = new System.Net.WebHeaderCollection(),
- };
- return encodedResponse;
- }
-
- /// <summary>
- /// Prepares to send a request to the Service Provider as the query string in a GET request.
- /// </summary>
- /// <param name="requestMessage">The message to be transmitted to the ServiceProvider.</param>
- /// <returns>The web request ready to send.</returns>
- /// <remarks>
- /// This method implements OAuth 1.0 section 5.2, item #3.
- /// </remarks>
- private static HttpWebRequest InitializeRequestAsGet(IDirectedProtocolMessage requestMessage) {
- var serializer = MessageSerializer.Get(requestMessage.GetType());
- var fields = serializer.Serialize(requestMessage);
-
- UriBuilder builder = new UriBuilder(requestMessage.Recipient);
- MessagingUtilities.AppendQueryArgs(builder, fields);
- HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(builder.Uri);
-
- return httpRequest;
- }
-
- /// <summary>
- /// Initializes a web request by attaching a message to it.
- /// </summary>
- /// <param name="request">The message to attach.</param>
- /// <returns>The initialized web request.</returns>
- private HttpWebRequest InitializeRequestInternal(IDirectedProtocolMessage request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
- if (request.Recipient == null) {
- throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "request");
- }
- IOAuthDirectedMessage oauthRequest = request as IOAuthDirectedMessage;
- if (oauthRequest == null) {
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.UnexpectedType,
- typeof(IOAuthDirectedMessage),
- request.GetType()));
- }
-
- HttpWebRequest httpRequest;
-
- HttpDeliveryMethods transmissionMethod = oauthRequest.HttpMethods;
- if ((transmissionMethod & HttpDeliveryMethods.AuthorizationHeaderRequest) != 0) {
- httpRequest = this.InitializeRequestAsAuthHeader(request);
- } else if ((transmissionMethod & HttpDeliveryMethods.PostRequest) != 0) {
- httpRequest = this.InitializeRequestAsPost(request);
- } else if ((transmissionMethod & HttpDeliveryMethods.GetRequest) != 0) {
- httpRequest = InitializeRequestAsGet(request);
- } else {
- throw new NotSupportedException();
- }
- return httpRequest;
- }
-
- /// <summary>
- /// Prepares to send a request to the Service Provider via the Authorization header.
- /// </summary>
- /// <param name="requestMessage">The message to be transmitted to the ServiceProvider.</param>
- /// <returns>The web request ready to send.</returns>
- /// <remarks>
- /// This method implements OAuth 1.0 section 5.2, item #1 (described in section 5.4).
- /// </remarks>
- private HttpWebRequest InitializeRequestAsAuthHeader(IDirectedProtocolMessage requestMessage) {
- var protocol = Protocol.Lookup(requestMessage.ProtocolVersion);
- var dictionary = new MessageDictionary(requestMessage);
-
- // copy so as to not modify original
- var fields = new Dictionary<string, string>();
- foreach (string key in dictionary.DeclaredKeys) {
- fields.Add(key, dictionary[key]);
- }
- if (this.Realm != null) {
- fields.Add("realm", this.Realm.AbsoluteUri);
- }
-
- UriBuilder builder = new UriBuilder(requestMessage.Recipient);
- MessagingUtilities.AppendQueryArgs(builder, requestMessage.ExtraData);
- HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(builder.Uri);
-
- StringBuilder authorization = new StringBuilder();
- authorization.Append(protocol.AuthorizationHeaderScheme);
- authorization.Append(" ");
- foreach (var pair in fields) {
- string key = Uri.EscapeDataString(pair.Key);
- string value = Uri.EscapeDataString(pair.Value);
- authorization.Append(key);
- authorization.Append("=\"");
- authorization.Append(value);
- authorization.Append("\",");
- }
- authorization.Length--; // remove trailing comma
-
- httpRequest.Headers.Add(HttpRequestHeader.Authorization, authorization.ToString());
-
- return httpRequest;
- }
-
- /// <summary>
- /// Prepares to send a request to the Service Provider as the payload of a POST request.
- /// </summary>
- /// <param name="requestMessage">The message to be transmitted to the ServiceProvider.</param>
- /// <returns>The web request ready to send.</returns>
- /// <remarks>
- /// This method implements OAuth 1.0 section 5.2, item #2.
- /// </remarks>
- private HttpWebRequest InitializeRequestAsPost(IDirectedProtocolMessage requestMessage) {
- var serializer = MessageSerializer.Get(requestMessage.GetType());
- var fields = serializer.Serialize(requestMessage);
-
- HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestMessage.Recipient);
- httpRequest.Method = "POST";
- httpRequest.ContentType = "application/x-www-form-urlencoded";
- string requestBody = MessagingUtilities.CreateQueryString(fields);
- httpRequest.ContentLength = requestBody.Length;
- using (TextWriter writer = this.webRequestHandler.GetRequestStream(httpRequest)) {
- writer.Write(requestBody);
- }
-
- return httpRequest;
- }
-
- /// <summary>
- /// Fills out the secrets in a message so that signing/verification can be performed.
- /// </summary>
- /// <param name="message">The message about to be signed or whose signature is about to be verified.</param>
- private void SignatureCallback(ITamperResistantOAuthMessage message) {
- try {
- Logger.Debug("Applying secrets to message to prepare for signing or signature verification.");
- message.ConsumerSecret = this.TokenManager.GetConsumerSecret(message.ConsumerKey);
-
- var tokenMessage = message as ITokenContainingMessage;
- if (tokenMessage != null) {
- message.TokenSecret = this.TokenManager.GetTokenSecret(tokenMessage.Token);
- }
- } catch (KeyNotFoundException ex) {
- throw new ProtocolException(Strings.ConsumerOrTokenSecretNotFound, ex);
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="OAuthChannel.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Net; + using System.Text; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// An OAuth-specific implementation of the <see cref="Channel"/> class. + /// </summary> + internal class OAuthChannel : Channel { + /// <summary> + /// The object that will transmit <see cref="HttpWebRequest"/> instances + /// and return their responses. + /// </summary> + private IWebRequestHandler webRequestHandler; + + /// <summary> + /// Initializes a new instance of the <see cref="OAuthChannel"/> class. + /// </summary> + /// <param name="signingBindingElement">The binding element to use for signing.</param> + /// <param name="store">The web application store to use for nonces.</param> + /// <param name="tokenManager">The token manager instance to use.</param> + /// <param name="isConsumer">A value indicating whether this channel is being constructed for a Consumer (as opposed to a Service Provider).</param> + internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, bool isConsumer) + : this( + signingBindingElement, + store, + tokenManager, + isConsumer ? (IMessageTypeProvider)new OAuthConsumerMessageTypeProvider() : new OAuthServiceProviderMessageTypeProvider(tokenManager), + new StandardWebRequestHandler()) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="OAuthChannel"/> class. + /// </summary> + /// <param name="signingBindingElement">The binding element to use for signing.</param> + /// <param name="store">The web application store to use for nonces.</param> + /// <param name="tokenManager">The ITokenManager instance to use.</param> + /// <param name="messageTypeProvider"> + /// An injected message type provider instance. + /// Except for mock testing, this should always be one of + /// <see cref="OAuthConsumerMessageTypeProvider"/> or <see cref="OAuthServiceProviderMessageTypeProvider"/>. + /// </param> + /// <param name="webRequestHandler"> + /// An instance to a <see cref="IWebRequestHandler"/> that will be used when submitting HTTP + /// requests and waiting for responses. + /// </param> + /// <remarks> + /// This overload for testing purposes only. + /// </remarks> + internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, IMessageTypeProvider messageTypeProvider, IWebRequestHandler webRequestHandler) + : base(messageTypeProvider, new OAuthHttpMethodBindingElement(), signingBindingElement, new StandardExpirationBindingElement(), new StandardReplayProtectionBindingElement(store)) { + if (tokenManager == null) { + throw new ArgumentNullException("tokenManager"); + } + if (webRequestHandler == null) { + throw new ArgumentNullException("webRequestHandler"); + } + + this.webRequestHandler = webRequestHandler; + this.TokenManager = tokenManager; + if (signingBindingElement.SignatureCallback != null) { + throw new ArgumentException(Strings.SigningElementAlreadyAssociatedWithChannel, "signingBindingElement"); + } + + signingBindingElement.SignatureCallback = this.SignatureCallback; + } + + /// <summary> + /// Gets or sets the Consumer web application path. + /// </summary> + internal Uri Realm { get; set; } + + /// <summary> + /// Gets the token manager being used. + /// </summary> + protected internal ITokenManager TokenManager { get; private set; } + + /// <summary> + /// Encodes the names and values that are part of the message per OAuth 1.0 section 5.1. + /// </summary> + /// <param name="message">The message with data to encode.</param> + /// <returns>A dictionary of name-value pairs with their strings encoded.</returns> + internal static IDictionary<string, string> GetEncodedParameters(IProtocolMessage message) { + var encodedDictionary = new Dictionary<string, string>(); + EncodeParameters(new MessageDictionary(message), encodedDictionary); + return encodedDictionary; + } + + /// <summary> + /// Encodes the names and values in a dictionary per OAuth 1.0 section 5.1. + /// </summary> + /// <param name="source">The dictionary with names and values to encode.</param> + /// <param name="destination">The dictionary to add the encoded pairs to.</param> + internal static void EncodeParameters(IDictionary<string, string> source, IDictionary<string, string> destination) { + if (source == null) { + throw new ArgumentNullException("source"); + } + if (destination == null) { + throw new ArgumentNullException("destination"); + } + + foreach (var pair in source) { + var key = Uri.EscapeDataString(pair.Key); + var value = Uri.EscapeDataString(pair.Value); + destination.Add(key, value); + } + } + + /// <summary> + /// Initializes a web request for sending by attaching a message to it. + /// Use this method to prepare a protected resource request that you do NOT + /// expect an OAuth message response to. + /// </summary> + /// <param name="request">The message to attach.</param> + /// <returns>The initialized web request.</returns> + internal HttpWebRequest InitializeRequest(IDirectedProtocolMessage request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + PrepareMessageForSending(request); + return this.InitializeRequestInternal(request); + } + + /// <summary> + /// Searches an incoming HTTP request for data that could be used to assemble + /// a protocol request message. + /// </summary> + /// <param name="request">The HTTP request to search.</param> + /// <returns>A dictionary of data in the request. Should never be null, but may be empty.</returns> + protected override IProtocolMessage ReadFromRequestInternal(HttpRequestInfo request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + // First search the Authorization header. Use it exclusively if it's present. + string authorization = request.Headers[HttpRequestHeader.Authorization]; + if (authorization != null) { + string[] authorizationSections = authorization.Split(';'); // TODO: is this the right delimiter? + string oauthPrefix = Protocol.Default.AuthorizationHeaderScheme + " "; + + // The Authorization header may have multiple uses, and OAuth may be just one of them. + // Go through each one looking for an OAuth one. + foreach (string auth in authorizationSections) { + string trimmedAuth = auth.Trim(); + if (trimmedAuth.StartsWith(oauthPrefix, StringComparison.Ordinal)) { + // We found an Authorization: OAuth header. + // Parse it according to the rules in section 5.4.1 of the V1.0 spec. + var fields = new Dictionary<string, string>(); + foreach (string stringPair in trimmedAuth.Substring(oauthPrefix.Length).Split(',')) { + string[] keyValueStringPair = stringPair.Trim().Split('='); + string key = Uri.UnescapeDataString(keyValueStringPair[0]); + string value = Uri.UnescapeDataString(keyValueStringPair[1].Trim('"')); + fields.Add(key, value); + } + + return this.Receive(fields, request.GetRecipient()); + } + } + } + + // We didn't find an OAuth authorization header. Revert to other payload methods. + IProtocolMessage message = base.ReadFromRequestInternal(request); + + // Add receiving HTTP transport information required for signature generation. + var signedMessage = message as ITamperResistantOAuthMessage; + if (signedMessage != null) { + signedMessage.Recipient = request.Url; + signedMessage.HttpMethod = request.HttpMethod; + } + + return message; + } + + /// <summary> + /// Gets the protocol message that may be in the given HTTP response stream. + /// </summary> + /// <param name="responseStream">The response that is anticipated to contain an OAuth message.</param> + /// <returns>The deserialized message, if one is found. Null otherwise.</returns> + protected override IProtocolMessage ReadFromResponseInternal(Stream responseStream) { + if (responseStream == null) { + throw new ArgumentNullException("responseStream"); + } + + using (StreamReader reader = new StreamReader(responseStream)) { + string response = reader.ReadToEnd(); + var fields = HttpUtility.ParseQueryString(response).ToDictionary(); + return Receive(fields, null); + } + } + + /// <summary> + /// Sends a direct message to a remote party and waits for the response. + /// </summary> + /// <param name="request">The message to send.</param> + /// <returns>The remote party's response.</returns> + protected override IProtocolMessage RequestInternal(IDirectedProtocolMessage request) { + HttpWebRequest httpRequest = this.InitializeRequestInternal(request); + + Response response = this.webRequestHandler.GetResponse(httpRequest); + if (response.ResponseStream == null) { + return null; + } + var responseFields = HttpUtility.ParseQueryString(response.Body).ToDictionary(); + Type messageType = this.MessageTypeProvider.GetResponseMessageType(request, responseFields); + if (messageType == null) { + return null; + } + var responseSerialize = MessageSerializer.Get(messageType); + var responseMessage = responseSerialize.Deserialize(responseFields, null); + + return responseMessage; + } + + /// <summary> + /// Queues a message for sending in the response stream where the fields + /// are sent in the response stream in querystring style. + /// </summary> + /// <param name="response">The message to send as a response.</param> + /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> + /// <remarks> + /// This method implements spec V1.0 section 5.3. + /// </remarks> + protected override Response SendDirectMessageResponse(IProtocolMessage response) { + if (response == null) { + throw new ArgumentNullException("response"); + } + + MessageSerializer serializer = MessageSerializer.Get(response.GetType()); + var fields = serializer.Serialize(response); + string responseBody = MessagingUtilities.CreateQueryString(fields); + + Response encodedResponse = new Response { + Body = responseBody, + OriginalMessage = response, + Status = HttpStatusCode.OK, + Headers = new System.Net.WebHeaderCollection(), + }; + return encodedResponse; + } + + /// <summary> + /// Prepares to send a request to the Service Provider as the query string in a GET request. + /// </summary> + /// <param name="requestMessage">The message to be transmitted to the ServiceProvider.</param> + /// <returns>The web request ready to send.</returns> + /// <remarks> + /// This method implements OAuth 1.0 section 5.2, item #3. + /// </remarks> + private static HttpWebRequest InitializeRequestAsGet(IDirectedProtocolMessage requestMessage) { + var serializer = MessageSerializer.Get(requestMessage.GetType()); + var fields = serializer.Serialize(requestMessage); + + UriBuilder builder = new UriBuilder(requestMessage.Recipient); + MessagingUtilities.AppendQueryArgs(builder, fields); + HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(builder.Uri); + + return httpRequest; + } + + /// <summary> + /// Initializes a web request by attaching a message to it. + /// </summary> + /// <param name="request">The message to attach.</param> + /// <returns>The initialized web request.</returns> + private HttpWebRequest InitializeRequestInternal(IDirectedProtocolMessage request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + if (request.Recipient == null) { + throw new ArgumentException(MessagingStrings.DirectedMessageMissingRecipient, "request"); + } + IOAuthDirectedMessage oauthRequest = request as IOAuthDirectedMessage; + if (oauthRequest == null) { + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.UnexpectedType, + typeof(IOAuthDirectedMessage), + request.GetType())); + } + + HttpWebRequest httpRequest; + + HttpDeliveryMethods transmissionMethod = oauthRequest.HttpMethods; + if ((transmissionMethod & HttpDeliveryMethods.AuthorizationHeaderRequest) != 0) { + httpRequest = this.InitializeRequestAsAuthHeader(request); + } else if ((transmissionMethod & HttpDeliveryMethods.PostRequest) != 0) { + httpRequest = this.InitializeRequestAsPost(request); + } else if ((transmissionMethod & HttpDeliveryMethods.GetRequest) != 0) { + httpRequest = InitializeRequestAsGet(request); + } else { + throw new NotSupportedException(); + } + return httpRequest; + } + + /// <summary> + /// Prepares to send a request to the Service Provider via the Authorization header. + /// </summary> + /// <param name="requestMessage">The message to be transmitted to the ServiceProvider.</param> + /// <returns>The web request ready to send.</returns> + /// <remarks> + /// This method implements OAuth 1.0 section 5.2, item #1 (described in section 5.4). + /// </remarks> + private HttpWebRequest InitializeRequestAsAuthHeader(IDirectedProtocolMessage requestMessage) { + var protocol = Protocol.Lookup(requestMessage.ProtocolVersion); + var dictionary = new MessageDictionary(requestMessage); + + // copy so as to not modify original + var fields = new Dictionary<string, string>(); + foreach (string key in dictionary.DeclaredKeys) { + fields.Add(key, dictionary[key]); + } + if (this.Realm != null) { + fields.Add("realm", this.Realm.AbsoluteUri); + } + + UriBuilder builder = new UriBuilder(requestMessage.Recipient); + MessagingUtilities.AppendQueryArgs(builder, requestMessage.ExtraData); + HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(builder.Uri); + + StringBuilder authorization = new StringBuilder(); + authorization.Append(protocol.AuthorizationHeaderScheme); + authorization.Append(" "); + foreach (var pair in fields) { + string key = Uri.EscapeDataString(pair.Key); + string value = Uri.EscapeDataString(pair.Value); + authorization.Append(key); + authorization.Append("=\""); + authorization.Append(value); + authorization.Append("\","); + } + authorization.Length--; // remove trailing comma + + httpRequest.Headers.Add(HttpRequestHeader.Authorization, authorization.ToString()); + + return httpRequest; + } + + /// <summary> + /// Prepares to send a request to the Service Provider as the payload of a POST request. + /// </summary> + /// <param name="requestMessage">The message to be transmitted to the ServiceProvider.</param> + /// <returns>The web request ready to send.</returns> + /// <remarks> + /// This method implements OAuth 1.0 section 5.2, item #2. + /// </remarks> + private HttpWebRequest InitializeRequestAsPost(IDirectedProtocolMessage requestMessage) { + var serializer = MessageSerializer.Get(requestMessage.GetType()); + var fields = serializer.Serialize(requestMessage); + + HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestMessage.Recipient); + httpRequest.Method = "POST"; + httpRequest.ContentType = "application/x-www-form-urlencoded"; + string requestBody = MessagingUtilities.CreateQueryString(fields); + httpRequest.ContentLength = requestBody.Length; + using (TextWriter writer = this.webRequestHandler.GetRequestStream(httpRequest)) { + writer.Write(requestBody); + } + + return httpRequest; + } + + /// <summary> + /// Fills out the secrets in a message so that signing/verification can be performed. + /// </summary> + /// <param name="message">The message about to be signed or whose signature is about to be verified.</param> + private void SignatureCallback(ITamperResistantOAuthMessage message) { + try { + Logger.Debug("Applying secrets to message to prepare for signing or signature verification."); + message.ConsumerSecret = this.TokenManager.GetConsumerSecret(message.ConsumerKey); + + var tokenMessage = message as ITokenContainingMessage; + if (tokenMessage != null) { + message.TokenSecret = this.TokenManager.GetTokenSecret(tokenMessage.Token); + } + } catch (KeyNotFoundException ex) { + throw new ProtocolException(Strings.ConsumerOrTokenSecretNotFound, ex); + } + } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/OAuthConsumerMessageTypeProvider.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthConsumerMessageTypeProvider.cs index 123d657..292c3b0 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/OAuthConsumerMessageTypeProvider.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthConsumerMessageTypeProvider.cs @@ -1,97 +1,97 @@ -//-----------------------------------------------------------------------
-// <copyright file="OAuthConsumerMessageTypeProvider.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// An OAuth-protocol specific implementation of the <see cref="IMessageTypeProvider"/>
- /// interface.
- /// </summary>
- public class OAuthConsumerMessageTypeProvider : IMessageTypeProvider {
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthConsumerMessageTypeProvider"/> class.
- /// </summary>
- protected internal OAuthConsumerMessageTypeProvider() {
- }
-
- #region IMessageTypeProvider Members
-
- /// <summary>
- /// Analyzes an incoming request message payload to discover what kind of
- /// message is embedded in it and returns the type, or null if no match is found.
- /// </summary>
- /// <param name="fields">The name/value pairs that make up the message payload.</param>
- /// <remarks>
- /// The request messages are:
- /// UserAuthorizationResponse
- /// </remarks>
- /// <returns>
- /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can
- /// deserialize to. Null if the request isn't recognized as a valid protocol message.
- /// </returns>
- public virtual Type GetRequestMessageType(IDictionary<string, string> fields) {
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- if (fields.ContainsKey("oauth_token")) {
- return typeof(UserAuthorizationResponse);
- }
-
- return null;
- }
-
- /// <summary>
- /// Analyzes an incoming request message payload to discover what kind of
- /// message is embedded in it and returns the type, or null if no match is found.
- /// </summary>
- /// <param name="request">
- /// The message that was sent as a request that resulted in the response.
- /// Null on a Consumer site that is receiving an indirect message from the Service Provider.
- /// </param>
- /// <param name="fields">The name/value pairs that make up the message payload.</param>
- /// <returns>
- /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can
- /// deserialize to. Null if the request isn't recognized as a valid protocol message.
- /// </returns>
- /// <remarks>
- /// The response messages are:
- /// UnauthorizedTokenResponse
- /// AuthorizedTokenResponse
- /// </remarks>
- public virtual Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields) {
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- // All response messages have the oauth_token field.
- if (!fields.ContainsKey("oauth_token")) {
- return null;
- }
-
- // All direct message responses should have the oauth_token_secret field.
- if (!fields.ContainsKey("oauth_token_secret")) {
- Logger.Error("An OAuth message was expected to contain an oauth_token_secret but didn't.");
- return null;
- }
-
- if (request is UnauthorizedTokenRequest) {
- return typeof(UnauthorizedTokenResponse);
- } else if (request is AuthorizedTokenRequest) {
- return typeof(AuthorizedTokenResponse);
- } else {
- Logger.ErrorFormat("Unexpected response message given the request type {0}", request.GetType().Name);
- throw new ProtocolException(Strings.InvalidIncomingMessage);
- }
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="OAuthConsumerMessageTypeProvider.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// An OAuth-protocol specific implementation of the <see cref="IMessageTypeProvider"/> + /// interface. + /// </summary> + public class OAuthConsumerMessageTypeProvider : IMessageTypeProvider { + /// <summary> + /// Initializes a new instance of the <see cref="OAuthConsumerMessageTypeProvider"/> class. + /// </summary> + protected internal OAuthConsumerMessageTypeProvider() { + } + + #region IMessageTypeProvider Members + + /// <summary> + /// Analyzes an incoming request message payload to discover what kind of + /// message is embedded in it and returns the type, or null if no match is found. + /// </summary> + /// <param name="fields">The name/value pairs that make up the message payload.</param> + /// <remarks> + /// The request messages are: + /// UserAuthorizationResponse + /// </remarks> + /// <returns> + /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can + /// deserialize to. Null if the request isn't recognized as a valid protocol message. + /// </returns> + public virtual Type GetRequestMessageType(IDictionary<string, string> fields) { + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + if (fields.ContainsKey("oauth_token")) { + return typeof(UserAuthorizationResponse); + } + + return null; + } + + /// <summary> + /// Analyzes an incoming request message payload to discover what kind of + /// message is embedded in it and returns the type, or null if no match is found. + /// </summary> + /// <param name="request"> + /// The message that was sent as a request that resulted in the response. + /// Null on a Consumer site that is receiving an indirect message from the Service Provider. + /// </param> + /// <param name="fields">The name/value pairs that make up the message payload.</param> + /// <returns> + /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can + /// deserialize to. Null if the request isn't recognized as a valid protocol message. + /// </returns> + /// <remarks> + /// The response messages are: + /// UnauthorizedTokenResponse + /// AuthorizedTokenResponse + /// </remarks> + public virtual Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields) { + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + // All response messages have the oauth_token field. + if (!fields.ContainsKey("oauth_token")) { + return null; + } + + // All direct message responses should have the oauth_token_secret field. + if (!fields.ContainsKey("oauth_token_secret")) { + Logger.Error("An OAuth message was expected to contain an oauth_token_secret but didn't."); + return null; + } + + if (request is UnauthorizedTokenRequest) { + return typeof(UnauthorizedTokenResponse); + } else if (request is AuthorizedTokenRequest) { + return typeof(AuthorizedTokenResponse); + } else { + Logger.ErrorFormat("Unexpected response message given the request type {0}", request.GetType().Name); + throw new ProtocolException(Strings.InvalidIncomingMessage); + } + } + + #endregion + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs index e026c02..a34f455 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs @@ -1,73 +1,73 @@ -//-----------------------------------------------------------------------
-// <copyright file="OAuthHttpMethodBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// Sets the HTTP Method property on a signed message before the signing module gets to it.
- /// </summary>
- internal class OAuthHttpMethodBindingElement : IChannelBindingElement {
- #region IChannelBindingElement Members
-
- /// <summary>
- /// Gets the protection offered (if any) by this binding element.
- /// </summary>
- public MessageProtections Protection {
- get { return MessageProtections.None; }
- }
-
- /// <summary>
- /// Prepares a message for sending based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The message to prepare for sending.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False otherwise.
- /// </returns>
- public bool PrepareMessageForSending(IProtocolMessage message) {
- var oauthMessage = message as ITamperResistantOAuthMessage;
-
- if (oauthMessage != null) {
- HttpDeliveryMethods transmissionMethod = oauthMessage.HttpMethods;
- if ((transmissionMethod & HttpDeliveryMethods.PostRequest) != 0) {
- oauthMessage.HttpMethod = "POST";
- } else if ((transmissionMethod & HttpDeliveryMethods.GetRequest) != 0) {
- oauthMessage.HttpMethod = "GET";
- } else {
- return false;
- }
-
- return true;
- } else {
- return false;
- }
- }
-
- /// <summary>
- /// Performs any transformation on an incoming message that may be necessary and/or
- /// validates an incoming message based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The incoming message to process.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False if the operation did not apply to this message.
- /// </returns>
- /// <exception cref="ProtocolException">
- /// Thrown when the binding element rules indicate that this message is invalid and should
- /// NOT be processed.
- /// </exception>
- public bool PrepareMessageForReceiving(IProtocolMessage message) {
- return false;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="OAuthHttpMethodBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// Sets the HTTP Method property on a signed message before the signing module gets to it. + /// </summary> + internal class OAuthHttpMethodBindingElement : IChannelBindingElement { + #region IChannelBindingElement Members + + /// <summary> + /// Gets the protection offered (if any) by this binding element. + /// </summary> + public MessageProtections Protection { + get { return MessageProtections.None; } + } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False otherwise. + /// </returns> + public bool PrepareMessageForSending(IProtocolMessage message) { + var oauthMessage = message as ITamperResistantOAuthMessage; + + if (oauthMessage != null) { + HttpDeliveryMethods transmissionMethod = oauthMessage.HttpMethods; + if ((transmissionMethod & HttpDeliveryMethods.PostRequest) != 0) { + oauthMessage.HttpMethod = "POST"; + } else if ((transmissionMethod & HttpDeliveryMethods.GetRequest) != 0) { + oauthMessage.HttpMethod = "GET"; + } else { + return false; + } + + return true; + } else { + return false; + } + } + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False if the operation did not apply to this message. + /// </returns> + /// <exception cref="ProtocolException"> + /// Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed. + /// </exception> + public bool PrepareMessageForReceiving(IProtocolMessage message) { + return false; + } + + #endregion + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/OAuthServiceProviderMessageTypeProvider.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthServiceProviderMessageTypeProvider.cs index 570cdc1..ee509c6 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/OAuthServiceProviderMessageTypeProvider.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthServiceProviderMessageTypeProvider.cs @@ -1,106 +1,106 @@ -//-----------------------------------------------------------------------
-// <copyright file="OAuthServiceProviderMessageTypeProvider.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// An OAuth-protocol specific implementation of the <see cref="IMessageTypeProvider"/>
- /// interface.
- /// </summary>
- public class OAuthServiceProviderMessageTypeProvider : IMessageTypeProvider {
- /// <summary>
- /// The token manager to use for discerning between request and access tokens.
- /// </summary>
- private ITokenManager tokenManager;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="OAuthServiceProviderMessageTypeProvider"/> class.
- /// </summary>
- /// <param name="tokenManager">The token manager instance to use.</param>
- protected internal OAuthServiceProviderMessageTypeProvider(ITokenManager tokenManager) {
- if (tokenManager == null) {
- throw new ArgumentNullException("tokenManager");
- }
-
- this.tokenManager = tokenManager;
- }
-
- #region IMessageTypeProvider Members
-
- /// <summary>
- /// Analyzes an incoming request message payload to discover what kind of
- /// message is embedded in it and returns the type, or null if no match is found.
- /// </summary>
- /// <param name="fields">The name/value pairs that make up the message payload.</param>
- /// <remarks>
- /// The request messages are:
- /// UnauthorizedTokenRequest
- /// AuthorizedTokenRequest
- /// UserAuthorizationRequest
- /// AccessProtectedResourceRequest
- /// </remarks>
- /// <returns>
- /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can
- /// deserialize to. Null if the request isn't recognized as a valid protocol message.
- /// </returns>
- public virtual Type GetRequestMessageType(IDictionary<string, string> fields) {
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- if (fields.ContainsKey("oauth_consumer_key") &&
- !fields.ContainsKey("oauth_token")) {
- return typeof(UnauthorizedTokenRequest);
- }
-
- if (fields.ContainsKey("oauth_consumer_key") &&
- fields.ContainsKey("oauth_token")) {
- // Discern between RequestAccessToken and AccessProtectedResources,
- // which have all the same parameters, by figuring out what type of token
- // is in the token parameter.
- bool tokenTypeIsAccessToken = this.tokenManager.GetTokenType(fields["oauth_token"]) == TokenType.AccessToken;
-
- return tokenTypeIsAccessToken ? typeof(AccessProtectedResourceRequest) :
- typeof(AuthorizedTokenRequest);
- }
-
- // fail over to the message with no required fields at all.
- return typeof(UserAuthorizationRequest);
- }
-
- /// <summary>
- /// Analyzes an incoming request message payload to discover what kind of
- /// message is embedded in it and returns the type, or null if no match is found.
- /// </summary>
- /// <param name="request">
- /// The message that was sent as a request that resulted in the response.
- /// Null on a Consumer site that is receiving an indirect message from the Service Provider.
- /// </param>
- /// <param name="fields">The name/value pairs that make up the message payload.</param>
- /// <returns>
- /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can
- /// deserialize to. Null if the request isn't recognized as a valid protocol message.
- /// </returns>
- /// <remarks>
- /// The response messages are:
- /// None.
- /// </remarks>
- public virtual Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields) {
- if (fields == null) {
- throw new ArgumentNullException("fields");
- }
-
- Logger.Error("Service Providers are not expected to ever receive responses.");
- return null;
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="OAuthServiceProviderMessageTypeProvider.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// An OAuth-protocol specific implementation of the <see cref="IMessageTypeProvider"/> + /// interface. + /// </summary> + public class OAuthServiceProviderMessageTypeProvider : IMessageTypeProvider { + /// <summary> + /// The token manager to use for discerning between request and access tokens. + /// </summary> + private ITokenManager tokenManager; + + /// <summary> + /// Initializes a new instance of the <see cref="OAuthServiceProviderMessageTypeProvider"/> class. + /// </summary> + /// <param name="tokenManager">The token manager instance to use.</param> + protected internal OAuthServiceProviderMessageTypeProvider(ITokenManager tokenManager) { + if (tokenManager == null) { + throw new ArgumentNullException("tokenManager"); + } + + this.tokenManager = tokenManager; + } + + #region IMessageTypeProvider Members + + /// <summary> + /// Analyzes an incoming request message payload to discover what kind of + /// message is embedded in it and returns the type, or null if no match is found. + /// </summary> + /// <param name="fields">The name/value pairs that make up the message payload.</param> + /// <remarks> + /// The request messages are: + /// UnauthorizedTokenRequest + /// AuthorizedTokenRequest + /// UserAuthorizationRequest + /// AccessProtectedResourceRequest + /// </remarks> + /// <returns> + /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can + /// deserialize to. Null if the request isn't recognized as a valid protocol message. + /// </returns> + public virtual Type GetRequestMessageType(IDictionary<string, string> fields) { + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + if (fields.ContainsKey("oauth_consumer_key") && + !fields.ContainsKey("oauth_token")) { + return typeof(UnauthorizedTokenRequest); + } + + if (fields.ContainsKey("oauth_consumer_key") && + fields.ContainsKey("oauth_token")) { + // Discern between RequestAccessToken and AccessProtectedResources, + // which have all the same parameters, by figuring out what type of token + // is in the token parameter. + bool tokenTypeIsAccessToken = this.tokenManager.GetTokenType(fields["oauth_token"]) == TokenType.AccessToken; + + return tokenTypeIsAccessToken ? typeof(AccessProtectedResourceRequest) : + typeof(AuthorizedTokenRequest); + } + + // fail over to the message with no required fields at all. + return typeof(UserAuthorizationRequest); + } + + /// <summary> + /// Analyzes an incoming request message payload to discover what kind of + /// message is embedded in it and returns the type, or null if no match is found. + /// </summary> + /// <param name="request"> + /// The message that was sent as a request that resulted in the response. + /// Null on a Consumer site that is receiving an indirect message from the Service Provider. + /// </param> + /// <param name="fields">The name/value pairs that make up the message payload.</param> + /// <returns> + /// The <see cref="IProtocolMessage"/>-derived concrete class that this message can + /// deserialize to. Null if the request isn't recognized as a valid protocol message. + /// </returns> + /// <remarks> + /// The response messages are: + /// None. + /// </remarks> + public virtual Type GetResponseMessageType(IProtocolMessage request, IDictionary<string, string> fields) { + if (fields == null) { + throw new ArgumentNullException("fields"); + } + + Logger.Error("Service Providers are not expected to ever receive responses."); + return null; + } + + #endregion + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs index e7d44d2..9f99066 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/PlaintextSigningBindingElement.cs @@ -1,55 +1,55 @@ -//-----------------------------------------------------------------------
-// <copyright file="PlaintextSigningBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
-
- /// <summary>
- /// A binding element that signs outgoing messages and verifies the signature on incoming messages.
- /// </summary>
- public class PlaintextSigningBindingElement : SigningBindingElementBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="PlaintextSigningBindingElement"/> class.
- /// </summary>
- public PlaintextSigningBindingElement()
- : base("PLAINTEXT") {
- }
-
- /// <summary>
- /// Calculates a signature for a given message.
- /// </summary>
- /// <param name="message">The message to sign.</param>
- /// <returns>The signature for the message.</returns>
- /// <remarks>
- /// This method signs the message according to OAuth 1.0 section 9.4.1.
- /// </remarks>
- protected override string GetSignature(ITamperResistantOAuthMessage message) {
- return GetConsumerAndTokenSecretString(message);
- }
-
- /// <summary>
- /// Checks whether this binding element applies to this message.
- /// </summary>
- /// <param name="message">The message that needs to be signed.</param>
- /// <returns>True if this binding element can be used to sign the message. False otherwise.</returns>
- protected override bool IsMessageApplicable(ITamperResistantOAuthMessage message) {
- return string.Equals(message.Recipient.Scheme, "https", StringComparison.OrdinalIgnoreCase);
- }
-
- /// <summary>
- /// Clones this instance.
- /// </summary>
- /// <returns>A new instance of the binding element.</returns>
- protected override ITamperProtectionChannelBindingElement Clone() {
- return new PlaintextSigningBindingElement();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="PlaintextSigningBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + + /// <summary> + /// A binding element that signs outgoing messages and verifies the signature on incoming messages. + /// </summary> + public class PlaintextSigningBindingElement : SigningBindingElementBase { + /// <summary> + /// Initializes a new instance of the <see cref="PlaintextSigningBindingElement"/> class. + /// </summary> + public PlaintextSigningBindingElement() + : base("PLAINTEXT") { + } + + /// <summary> + /// Calculates a signature for a given message. + /// </summary> + /// <param name="message">The message to sign.</param> + /// <returns>The signature for the message.</returns> + /// <remarks> + /// This method signs the message according to OAuth 1.0 section 9.4.1. + /// </remarks> + protected override string GetSignature(ITamperResistantOAuthMessage message) { + return GetConsumerAndTokenSecretString(message); + } + + /// <summary> + /// Checks whether this binding element applies to this message. + /// </summary> + /// <param name="message">The message that needs to be signed.</param> + /// <returns>True if this binding element can be used to sign the message. False otherwise.</returns> + protected override bool IsMessageApplicable(ITamperResistantOAuthMessage message) { + return string.Equals(message.Recipient.Scheme, "https", StringComparison.OrdinalIgnoreCase); + } + + /// <summary> + /// Clones this instance. + /// </summary> + /// <returns>A new instance of the binding element.</returns> + protected override ITamperProtectionChannelBindingElement Clone() { + return new PlaintextSigningBindingElement(); + } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs index 07a72f3..058ce39 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/RsaSha1SigningBindingElement.cs @@ -1,48 +1,48 @@ -//-----------------------------------------------------------------------
-// <copyright file="RsaSha1SigningBindingElement.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Security.Cryptography;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A binding element that signs outgoing messages and verifies the signature on incoming messages.
- /// </summary>
- public class RsaSha1SigningBindingElement : SigningBindingElementBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="RsaSha1SigningBindingElement"/> class.
- /// </summary>
- internal RsaSha1SigningBindingElement()
- : base("RSA-SHA1") {
- }
-
- /// <summary>
- /// Calculates a signature for a given message.
- /// </summary>
- /// <param name="message">The message to sign.</param>
- /// <returns>The signature for the message.</returns>
- /// <remarks>
- /// This method signs the message per OAuth 1.0 section 9.3.
- /// </remarks>
- protected override string GetSignature(ITamperResistantOAuthMessage message) {
- AsymmetricAlgorithm provider = new RSACryptoServiceProvider();
- AsymmetricSignatureFormatter hasher = new RSAPKCS1SignatureFormatter(provider);
- hasher.SetHashAlgorithm("SHA1");
- byte[] digest = hasher.CreateSignature(Encoding.ASCII.GetBytes(ConstructSignatureBaseString(message)));
- return Convert.ToBase64String(digest);
- }
-
- /// <summary>
- /// Clones this instance.
- /// </summary>
- /// <returns>A new instance of the binding element.</returns>
- protected override ITamperProtectionChannelBindingElement Clone() {
- return new RsaSha1SigningBindingElement();
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="RsaSha1SigningBindingElement.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Security.Cryptography; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A binding element that signs outgoing messages and verifies the signature on incoming messages. + /// </summary> + public class RsaSha1SigningBindingElement : SigningBindingElementBase { + /// <summary> + /// Initializes a new instance of the <see cref="RsaSha1SigningBindingElement"/> class. + /// </summary> + internal RsaSha1SigningBindingElement() + : base("RSA-SHA1") { + } + + /// <summary> + /// Calculates a signature for a given message. + /// </summary> + /// <param name="message">The message to sign.</param> + /// <returns>The signature for the message.</returns> + /// <remarks> + /// This method signs the message per OAuth 1.0 section 9.3. + /// </remarks> + protected override string GetSignature(ITamperResistantOAuthMessage message) { + AsymmetricAlgorithm provider = new RSACryptoServiceProvider(); + AsymmetricSignatureFormatter hasher = new RSAPKCS1SignatureFormatter(provider); + hasher.SetHashAlgorithm("SHA1"); + byte[] digest = hasher.CreateSignature(Encoding.ASCII.GetBytes(ConstructSignatureBaseString(message))); + return Convert.ToBase64String(digest); + } + + /// <summary> + /// Clones this instance. + /// </summary> + /// <returns>A new instance of the binding element.</returns> + protected override ITamperProtectionChannelBindingElement Clone() { + return new RsaSha1SigningBindingElement(); + } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/SigningBindingElementBase.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBase.cs index fb3ca45..704a362 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/SigningBindingElementBase.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementBase.cs @@ -1,242 +1,242 @@ -//-----------------------------------------------------------------------
-// <copyright file="SigningBindingElementBase.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Text;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
-
- /// <summary>
- /// A binding element that signs outgoing messages and verifies the signature on incoming messages.
- /// </summary>
- public abstract class SigningBindingElementBase : ITamperProtectionChannelBindingElement {
- /// <summary>
- /// The signature method this binding element uses.
- /// </summary>
- private string signatureMethod;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SigningBindingElementBase"/> class.
- /// </summary>
- /// <param name="signatureMethod">The OAuth signature method that the binding element uses.</param>
- internal SigningBindingElementBase(string signatureMethod) {
- this.signatureMethod = signatureMethod;
- }
-
- #region IChannelBindingElement Properties
-
- /// <summary>
- /// Gets the message protection provided by this binding element.
- /// </summary>
- public MessageProtections Protection {
- get { return MessageProtections.TamperProtection; }
- }
-
- #endregion
-
- #region ITamperProtectionChannelBindingElement members
-
- /// <summary>
- /// Gets or sets the delegate that will initialize the non-serialized properties necessary on a signed
- /// message so that its signature can be correctly calculated for verification.
- /// </summary>
- public Action<ITamperResistantOAuthMessage> SignatureCallback { get; set; }
-
- /// <summary>
- /// Creates a new object that is a copy of the current instance.
- /// </summary>
- /// <returns>
- /// A new object that is a copy of this instance.
- /// </returns>
- ITamperProtectionChannelBindingElement ITamperProtectionChannelBindingElement.Clone() {
- ITamperProtectionChannelBindingElement clone = this.Clone();
- clone.SignatureCallback = this.SignatureCallback;
- return clone;
- }
-
- #endregion
-
- #region IChannelBindingElement Methods
-
- /// <summary>
- /// Signs the outgoing message.
- /// </summary>
- /// <param name="message">The message to sign.</param>
- /// <returns>True if the message was signed. False otherwise.</returns>
- public bool PrepareMessageForSending(IProtocolMessage message) {
- var signedMessage = message as ITamperResistantOAuthMessage;
- if (signedMessage != null && this.IsMessageApplicable(signedMessage)) {
- if (this.SignatureCallback != null) {
- this.SignatureCallback(signedMessage);
- } else {
- Logger.Warn("Signing required, but callback delegate was not provided to provide additional data for signing.");
- }
-
- signedMessage.SignatureMethod = this.signatureMethod;
- Logger.DebugFormat("Signing {0} message using {1}.", message.GetType().Name, this.signatureMethod);
- signedMessage.Signature = this.GetSignature(signedMessage);
- return true;
- }
-
- return false;
- }
-
- /// <summary>
- /// Verifies the signature on an incoming message.
- /// </summary>
- /// <param name="message">The message whose signature should be verified.</param>
- /// <returns>True if the signature was verified. False if the message had no signature.</returns>
- /// <exception cref="InvalidSignatureException">Thrown if the signature is invalid.</exception>
- public bool PrepareMessageForReceiving(IProtocolMessage message) {
- var signedMessage = message as ITamperResistantOAuthMessage;
- if (signedMessage != null && this.IsMessageApplicable(signedMessage)) {
- Logger.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature);
-
- if (!string.Equals(signedMessage.SignatureMethod, this.signatureMethod, StringComparison.Ordinal)) {
- Logger.WarnFormat("Expected signature method '{0}' but received message with a signature method of '{1}'.", this.signatureMethod, signedMessage.SignatureMethod);
- return false;
- }
-
- if (this.SignatureCallback != null) {
- this.SignatureCallback(signedMessage);
- } else {
- Logger.Warn("Signature verification required, but callback delegate was not provided to provide additional data for signing.");
- }
-
- string signature = this.GetSignature(signedMessage);
- if (signedMessage.Signature != signature) {
- Logger.Error("Signature verification failed.");
- throw new InvalidSignatureException(message);
- }
-
- return true;
- }
-
- return false;
- }
-
- #endregion
-
- /// <summary>
- /// Constructs the OAuth Signature Base String and returns the result.
- /// </summary>
- /// <param name="message">The message to derive the signature base string from.</param>
- /// <returns>The signature base string.</returns>
- /// <remarks>
- /// This method implements OAuth 1.0 section 9.1.
- /// </remarks>
- protected static string ConstructSignatureBaseString(ITamperResistantOAuthMessage message) {
- if (String.IsNullOrEmpty(message.HttpMethod)) {
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- MessagingStrings.ArgumentPropertyMissing,
- typeof(ITamperResistantOAuthMessage).Name,
- "HttpMethod"),
- "message");
- }
-
- List<string> signatureBaseStringElements = new List<string>(3);
-
- signatureBaseStringElements.Add(message.HttpMethod.ToUpperInvariant());
-
- UriBuilder endpoint = new UriBuilder(message.Recipient);
- endpoint.Query = null;
- endpoint.Fragment = null;
- signatureBaseStringElements.Add(endpoint.Uri.AbsoluteUri);
-
- var encodedDictionary = OAuthChannel.GetEncodedParameters(message);
- encodedDictionary.Remove("oauth_signature");
- var sortedKeyValueList = new List<KeyValuePair<string, string>>(encodedDictionary);
- sortedKeyValueList.Sort(SignatureBaseStringParameterComparer);
- StringBuilder paramBuilder = new StringBuilder();
- foreach (var pair in sortedKeyValueList) {
- if (paramBuilder.Length > 0) {
- paramBuilder.Append("&");
- }
-
- paramBuilder.Append(pair.Key);
- paramBuilder.Append('=');
- paramBuilder.Append(pair.Value);
- }
-
- signatureBaseStringElements.Add(paramBuilder.ToString());
-
- StringBuilder signatureBaseString = new StringBuilder();
- foreach (string element in signatureBaseStringElements) {
- if (signatureBaseString.Length > 0) {
- signatureBaseString.Append("&");
- }
-
- signatureBaseString.Append(Uri.EscapeDataString(element));
- }
-
- Logger.DebugFormat("Constructed signature base string: {0}", signatureBaseString);
- return signatureBaseString.ToString();
- }
-
- /// <summary>
- /// Gets the ConsumerSecret&TokenSecret" string, allowing either property to be empty or null.
- /// </summary>
- /// <param name="message">The message to extract the secrets from.</param>
- /// <returns>The concatenated string.</returns>
- protected static string GetConsumerAndTokenSecretString(ITamperResistantOAuthMessage message) {
- StringBuilder builder = new StringBuilder();
- if (!string.IsNullOrEmpty(message.ConsumerSecret)) {
- builder.Append(Uri.EscapeDataString(message.ConsumerSecret));
- }
- builder.Append("&");
- if (!string.IsNullOrEmpty(message.TokenSecret)) {
- builder.Append(Uri.EscapeDataString(message.TokenSecret));
- }
- return builder.ToString();
- }
-
- /// <summary>
- /// Clones this instance.
- /// </summary>
- /// <returns>A new instance of the binding element.</returns>
- /// <remarks>
- /// Implementations of this method need not clone the SignatureVerificationCallback member, as the
- /// <see cref="SigningBindingElementBase"/> class does this.
- /// </remarks>
- protected abstract ITamperProtectionChannelBindingElement Clone();
-
- /// <summary>
- /// Calculates a signature for a given message.
- /// </summary>
- /// <param name="message">The message to sign.</param>
- /// <returns>The signature for the message.</returns>
- protected abstract string GetSignature(ITamperResistantOAuthMessage message);
-
- /// <summary>
- /// Checks whether this binding element applies to this message.
- /// </summary>
- /// <param name="message">The message that needs to be signed.</param>
- /// <returns>True if this binding element can be used to sign the message. False otherwise.</returns>
- protected virtual bool IsMessageApplicable(ITamperResistantOAuthMessage message) {
- return string.IsNullOrEmpty(message.SignatureMethod) || message.SignatureMethod == this.signatureMethod;
- }
-
- /// <summary>
- /// Sorts parameters according to OAuth signature base string rules.
- /// </summary>
- /// <param name="left">The first parameter to compare.</param>
- /// <param name="right">The second parameter to compare.</param>
- /// <returns>Negative, zero or positive.</returns>
- private static int SignatureBaseStringParameterComparer(KeyValuePair<string, string> left, KeyValuePair<string, string> right) {
- int result = string.CompareOrdinal(left.Key, right.Key);
- if (result != 0) {
- return result;
- }
-
- return string.CompareOrdinal(left.Value, right.Value);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="SigningBindingElementBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + + /// <summary> + /// A binding element that signs outgoing messages and verifies the signature on incoming messages. + /// </summary> + public abstract class SigningBindingElementBase : ITamperProtectionChannelBindingElement { + /// <summary> + /// The signature method this binding element uses. + /// </summary> + private string signatureMethod; + + /// <summary> + /// Initializes a new instance of the <see cref="SigningBindingElementBase"/> class. + /// </summary> + /// <param name="signatureMethod">The OAuth signature method that the binding element uses.</param> + internal SigningBindingElementBase(string signatureMethod) { + this.signatureMethod = signatureMethod; + } + + #region IChannelBindingElement Properties + + /// <summary> + /// Gets the message protection provided by this binding element. + /// </summary> + public MessageProtections Protection { + get { return MessageProtections.TamperProtection; } + } + + #endregion + + #region ITamperProtectionChannelBindingElement members + + /// <summary> + /// Gets or sets the delegate that will initialize the non-serialized properties necessary on a signed + /// message so that its signature can be correctly calculated for verification. + /// </summary> + public Action<ITamperResistantOAuthMessage> SignatureCallback { get; set; } + + /// <summary> + /// Creates a new object that is a copy of the current instance. + /// </summary> + /// <returns> + /// A new object that is a copy of this instance. + /// </returns> + ITamperProtectionChannelBindingElement ITamperProtectionChannelBindingElement.Clone() { + ITamperProtectionChannelBindingElement clone = this.Clone(); + clone.SignatureCallback = this.SignatureCallback; + return clone; + } + + #endregion + + #region IChannelBindingElement Methods + + /// <summary> + /// Signs the outgoing message. + /// </summary> + /// <param name="message">The message to sign.</param> + /// <returns>True if the message was signed. False otherwise.</returns> + public bool PrepareMessageForSending(IProtocolMessage message) { + var signedMessage = message as ITamperResistantOAuthMessage; + if (signedMessage != null && this.IsMessageApplicable(signedMessage)) { + if (this.SignatureCallback != null) { + this.SignatureCallback(signedMessage); + } else { + Logger.Warn("Signing required, but callback delegate was not provided to provide additional data for signing."); + } + + signedMessage.SignatureMethod = this.signatureMethod; + Logger.DebugFormat("Signing {0} message using {1}.", message.GetType().Name, this.signatureMethod); + signedMessage.Signature = this.GetSignature(signedMessage); + return true; + } + + return false; + } + + /// <summary> + /// Verifies the signature on an incoming message. + /// </summary> + /// <param name="message">The message whose signature should be verified.</param> + /// <returns>True if the signature was verified. False if the message had no signature.</returns> + /// <exception cref="InvalidSignatureException">Thrown if the signature is invalid.</exception> + public bool PrepareMessageForReceiving(IProtocolMessage message) { + var signedMessage = message as ITamperResistantOAuthMessage; + if (signedMessage != null && this.IsMessageApplicable(signedMessage)) { + Logger.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature); + + if (!string.Equals(signedMessage.SignatureMethod, this.signatureMethod, StringComparison.Ordinal)) { + Logger.WarnFormat("Expected signature method '{0}' but received message with a signature method of '{1}'.", this.signatureMethod, signedMessage.SignatureMethod); + return false; + } + + if (this.SignatureCallback != null) { + this.SignatureCallback(signedMessage); + } else { + Logger.Warn("Signature verification required, but callback delegate was not provided to provide additional data for signing."); + } + + string signature = this.GetSignature(signedMessage); + if (signedMessage.Signature != signature) { + Logger.Error("Signature verification failed."); + throw new InvalidSignatureException(message); + } + + return true; + } + + return false; + } + + #endregion + + /// <summary> + /// Constructs the OAuth Signature Base String and returns the result. + /// </summary> + /// <param name="message">The message to derive the signature base string from.</param> + /// <returns>The signature base string.</returns> + /// <remarks> + /// This method implements OAuth 1.0 section 9.1. + /// </remarks> + protected static string ConstructSignatureBaseString(ITamperResistantOAuthMessage message) { + if (String.IsNullOrEmpty(message.HttpMethod)) { + throw new ArgumentException( + string.Format( + CultureInfo.CurrentCulture, + MessagingStrings.ArgumentPropertyMissing, + typeof(ITamperResistantOAuthMessage).Name, + "HttpMethod"), + "message"); + } + + List<string> signatureBaseStringElements = new List<string>(3); + + signatureBaseStringElements.Add(message.HttpMethod.ToUpperInvariant()); + + UriBuilder endpoint = new UriBuilder(message.Recipient); + endpoint.Query = null; + endpoint.Fragment = null; + signatureBaseStringElements.Add(endpoint.Uri.AbsoluteUri); + + var encodedDictionary = OAuthChannel.GetEncodedParameters(message); + encodedDictionary.Remove("oauth_signature"); + var sortedKeyValueList = new List<KeyValuePair<string, string>>(encodedDictionary); + sortedKeyValueList.Sort(SignatureBaseStringParameterComparer); + StringBuilder paramBuilder = new StringBuilder(); + foreach (var pair in sortedKeyValueList) { + if (paramBuilder.Length > 0) { + paramBuilder.Append("&"); + } + + paramBuilder.Append(pair.Key); + paramBuilder.Append('='); + paramBuilder.Append(pair.Value); + } + + signatureBaseStringElements.Add(paramBuilder.ToString()); + + StringBuilder signatureBaseString = new StringBuilder(); + foreach (string element in signatureBaseStringElements) { + if (signatureBaseString.Length > 0) { + signatureBaseString.Append("&"); + } + + signatureBaseString.Append(Uri.EscapeDataString(element)); + } + + Logger.DebugFormat("Constructed signature base string: {0}", signatureBaseString); + return signatureBaseString.ToString(); + } + + /// <summary> + /// Gets the ConsumerSecret&TokenSecret" string, allowing either property to be empty or null. + /// </summary> + /// <param name="message">The message to extract the secrets from.</param> + /// <returns>The concatenated string.</returns> + protected static string GetConsumerAndTokenSecretString(ITamperResistantOAuthMessage message) { + StringBuilder builder = new StringBuilder(); + if (!string.IsNullOrEmpty(message.ConsumerSecret)) { + builder.Append(Uri.EscapeDataString(message.ConsumerSecret)); + } + builder.Append("&"); + if (!string.IsNullOrEmpty(message.TokenSecret)) { + builder.Append(Uri.EscapeDataString(message.TokenSecret)); + } + return builder.ToString(); + } + + /// <summary> + /// Clones this instance. + /// </summary> + /// <returns>A new instance of the binding element.</returns> + /// <remarks> + /// Implementations of this method need not clone the SignatureVerificationCallback member, as the + /// <see cref="SigningBindingElementBase"/> class does this. + /// </remarks> + protected abstract ITamperProtectionChannelBindingElement Clone(); + + /// <summary> + /// Calculates a signature for a given message. + /// </summary> + /// <param name="message">The message to sign.</param> + /// <returns>The signature for the message.</returns> + protected abstract string GetSignature(ITamperResistantOAuthMessage message); + + /// <summary> + /// Checks whether this binding element applies to this message. + /// </summary> + /// <param name="message">The message that needs to be signed.</param> + /// <returns>True if this binding element can be used to sign the message. False otherwise.</returns> + protected virtual bool IsMessageApplicable(ITamperResistantOAuthMessage message) { + return string.IsNullOrEmpty(message.SignatureMethod) || message.SignatureMethod == this.signatureMethod; + } + + /// <summary> + /// Sorts parameters according to OAuth signature base string rules. + /// </summary> + /// <param name="left">The first parameter to compare.</param> + /// <param name="right">The second parameter to compare.</param> + /// <returns>Negative, zero or positive.</returns> + private static int SignatureBaseStringParameterComparer(KeyValuePair<string, string> left, KeyValuePair<string, string> right) { + int result = string.CompareOrdinal(left.Key, right.Key); + if (result != 0) { + return result; + } + + return string.CompareOrdinal(left.Value, right.Value); + } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/SigningBindingElementChain.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementChain.cs index 88119f1..f42c12e 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/SigningBindingElementChain.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/SigningBindingElementChain.cs @@ -1,132 +1,132 @@ -//-----------------------------------------------------------------------
-// <copyright file="SigningBindingElementChain.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A tamper protection applying binding element that can use any of several given
- /// binding elements to apply the protection.
- /// </summary>
- internal class SigningBindingElementChain : ITamperProtectionChannelBindingElement {
- /// <summary>
- /// The various signing binding elements that may be applicable to a message in preferred use order.
- /// </summary>
- private ITamperProtectionChannelBindingElement[] signers;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SigningBindingElementChain"/> class.
- /// </summary>
- /// <param name="signers">
- /// The signing binding elements that may be used for some outgoing message,
- /// in preferred use order.
- /// </param>
- internal SigningBindingElementChain(ITamperProtectionChannelBindingElement[] signers) {
- if (signers == null) {
- throw new ArgumentNullException("signers");
- }
- if (signers.Length == 0) {
- throw new ArgumentException(MessagingStrings.SequenceContainsNoElements, "signers");
- }
- if (signers.Contains(null)) {
- throw new ArgumentException(MessagingStrings.SequenceContainsNullElement, "signers");
- }
- MessageProtections protection = signers[0].Protection;
- if (signers.Any(element => element.Protection != protection)) {
- throw new ArgumentException(Strings.SigningElementsMustShareSameProtection, "signers");
- }
-
- this.signers = signers;
- }
-
- #region ITamperProtectionChannelBindingElement Properties
-
- /// <summary>
- /// Gets or sets the delegate that will initialize the non-serialized properties necessary on a signed
- /// message so that its signature can be correctly calculated for verification.
- /// May be null for Consumers (who never have to verify signatures).
- /// </summary>
- public Action<ITamperResistantOAuthMessage> SignatureCallback {
- get {
- return this.signers[0].SignatureCallback;
- }
-
- set {
- foreach (ITamperProtectionChannelBindingElement signer in this.signers) {
- signer.SignatureCallback = value;
- }
- }
- }
-
- #endregion
-
- #region IChannelBindingElement Members
-
- /// <summary>
- /// Gets the protection offered (if any) by this binding element.
- /// </summary>
- public MessageProtections Protection {
- get { return this.signers[0].Protection; }
- }
-
- /// <summary>
- /// Prepares a message for sending based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The message to prepare for sending.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False otherwise.
- /// </returns>
- public bool PrepareMessageForSending(IProtocolMessage message) {
- foreach (IChannelBindingElement signer in this.signers) {
- if (signer.PrepareMessageForSending(message)) {
- return true;
- }
- }
-
- return false;
- }
-
- /// <summary>
- /// Performs any transformation on an incoming message that may be necessary and/or
- /// validates an incoming message based on the rules of this channel binding element.
- /// </summary>
- /// <param name="message">The incoming message to process.</param>
- /// <returns>
- /// True if the <paramref name="message"/> applied to this binding element
- /// and the operation was successful. False if the operation did not apply to this message.
- /// </returns>
- public bool PrepareMessageForReceiving(IProtocolMessage message) {
- foreach (IChannelBindingElement signer in this.signers) {
- if (signer.PrepareMessageForReceiving(message)) {
- return true;
- }
- }
-
- return false;
- }
-
- #endregion
-
- #region ITamperProtectionChannelBindingElement Methods
-
- /// <summary>
- /// Creates a new object that is a copy of the current instance.
- /// </summary>
- /// <returns>
- /// A new object that is a copy of this instance.
- /// </returns>
- ITamperProtectionChannelBindingElement ITamperProtectionChannelBindingElement.Clone() {
- return new SigningBindingElementChain(this.signers.Select(el => (ITamperProtectionChannelBindingElement)el.Clone()).ToArray());
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="SigningBindingElementChain.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A tamper protection applying binding element that can use any of several given + /// binding elements to apply the protection. + /// </summary> + internal class SigningBindingElementChain : ITamperProtectionChannelBindingElement { + /// <summary> + /// The various signing binding elements that may be applicable to a message in preferred use order. + /// </summary> + private ITamperProtectionChannelBindingElement[] signers; + + /// <summary> + /// Initializes a new instance of the <see cref="SigningBindingElementChain"/> class. + /// </summary> + /// <param name="signers"> + /// The signing binding elements that may be used for some outgoing message, + /// in preferred use order. + /// </param> + internal SigningBindingElementChain(ITamperProtectionChannelBindingElement[] signers) { + if (signers == null) { + throw new ArgumentNullException("signers"); + } + if (signers.Length == 0) { + throw new ArgumentException(MessagingStrings.SequenceContainsNoElements, "signers"); + } + if (signers.Contains(null)) { + throw new ArgumentException(MessagingStrings.SequenceContainsNullElement, "signers"); + } + MessageProtections protection = signers[0].Protection; + if (signers.Any(element => element.Protection != protection)) { + throw new ArgumentException(Strings.SigningElementsMustShareSameProtection, "signers"); + } + + this.signers = signers; + } + + #region ITamperProtectionChannelBindingElement Properties + + /// <summary> + /// Gets or sets the delegate that will initialize the non-serialized properties necessary on a signed + /// message so that its signature can be correctly calculated for verification. + /// May be null for Consumers (who never have to verify signatures). + /// </summary> + public Action<ITamperResistantOAuthMessage> SignatureCallback { + get { + return this.signers[0].SignatureCallback; + } + + set { + foreach (ITamperProtectionChannelBindingElement signer in this.signers) { + signer.SignatureCallback = value; + } + } + } + + #endregion + + #region IChannelBindingElement Members + + /// <summary> + /// Gets the protection offered (if any) by this binding element. + /// </summary> + public MessageProtections Protection { + get { return this.signers[0].Protection; } + } + + /// <summary> + /// Prepares a message for sending based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The message to prepare for sending.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False otherwise. + /// </returns> + public bool PrepareMessageForSending(IProtocolMessage message) { + foreach (IChannelBindingElement signer in this.signers) { + if (signer.PrepareMessageForSending(message)) { + return true; + } + } + + return false; + } + + /// <summary> + /// Performs any transformation on an incoming message that may be necessary and/or + /// validates an incoming message based on the rules of this channel binding element. + /// </summary> + /// <param name="message">The incoming message to process.</param> + /// <returns> + /// True if the <paramref name="message"/> applied to this binding element + /// and the operation was successful. False if the operation did not apply to this message. + /// </returns> + public bool PrepareMessageForReceiving(IProtocolMessage message) { + foreach (IChannelBindingElement signer in this.signers) { + if (signer.PrepareMessageForReceiving(message)) { + return true; + } + } + + return false; + } + + #endregion + + #region ITamperProtectionChannelBindingElement Methods + + /// <summary> + /// Creates a new object that is a copy of the current instance. + /// </summary> + /// <returns> + /// A new object that is a copy of this instance. + /// </returns> + ITamperProtectionChannelBindingElement ITamperProtectionChannelBindingElement.Clone() { + return new SigningBindingElementChain(this.signers.Select(el => (ITamperProtectionChannelBindingElement)el.Clone()).ToArray()); + } + + #endregion + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/StandardTokenGenerator.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/StandardTokenGenerator.cs index a1bc36a..1d2e3af 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/StandardTokenGenerator.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/StandardTokenGenerator.cs @@ -1,68 +1,68 @@ -//-----------------------------------------------------------------------
-// <copyright file="StandardTokenGenerator.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.Security.Cryptography;
-
- /// <summary>
- /// A cryptographically strong random string generator for tokens and secrets.
- /// </summary>
- internal class StandardTokenGenerator : ITokenGenerator {
- /// <summary>
- /// The cryptographically strong random string generator for tokens and secrets.
- /// </summary>
- private RandomNumberGenerator cryptoProvider = new RNGCryptoServiceProvider();
-
- #region ITokenGenerator Members
-
- /// <summary>
- /// Generates a new token to represent a not-yet-authorized request to access protected resources.
- /// </summary>
- /// <param name="consumerKey">The consumer that requested this token.</param>
- /// <returns>The newly generated token.</returns>
- /// <remarks>
- /// This method should not store the newly generated token in any persistent store.
- /// This will be done in <see cref="ITokenManager.StoreNewRequestToken"/>.
- /// </remarks>
- public string GenerateRequestToken(string consumerKey) {
- return this.GenerateCryptographicallyStrongString();
- }
-
- /// <summary>
- /// Generates a new token to represent an authorized request to access protected resources.
- /// </summary>
- /// <param name="consumerKey">The consumer that requested this token.</param>
- /// <returns>The newly generated token.</returns>
- /// <remarks>
- /// This method should not store the newly generated token in any persistent store.
- /// This will be done in <see cref="ITokenManager.ExpireRequestTokenAndStoreNewAccessToken"/>.
- /// </remarks>
- public string GenerateAccessToken(string consumerKey) {
- return this.GenerateCryptographicallyStrongString();
- }
-
- /// <summary>
- /// Returns a cryptographically strong random string for use as a token secret.
- /// </summary>
- /// <returns>The generated string.</returns>
- public string GenerateSecret() {
- return this.GenerateCryptographicallyStrongString();
- }
-
- #endregion
-
- /// <summary>
- /// Returns a new random string.
- /// </summary>
- /// <returns>The new random string.</returns>
- private string GenerateCryptographicallyStrongString() {
- byte[] buffer = new byte[20];
- this.cryptoProvider.GetBytes(buffer);
- return Convert.ToBase64String(buffer);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="StandardTokenGenerator.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.Security.Cryptography; + + /// <summary> + /// A cryptographically strong random string generator for tokens and secrets. + /// </summary> + internal class StandardTokenGenerator : ITokenGenerator { + /// <summary> + /// The cryptographically strong random string generator for tokens and secrets. + /// </summary> + private RandomNumberGenerator cryptoProvider = new RNGCryptoServiceProvider(); + + #region ITokenGenerator Members + + /// <summary> + /// Generates a new token to represent a not-yet-authorized request to access protected resources. + /// </summary> + /// <param name="consumerKey">The consumer that requested this token.</param> + /// <returns>The newly generated token.</returns> + /// <remarks> + /// This method should not store the newly generated token in any persistent store. + /// This will be done in <see cref="ITokenManager.StoreNewRequestToken"/>. + /// </remarks> + public string GenerateRequestToken(string consumerKey) { + return this.GenerateCryptographicallyStrongString(); + } + + /// <summary> + /// Generates a new token to represent an authorized request to access protected resources. + /// </summary> + /// <param name="consumerKey">The consumer that requested this token.</param> + /// <returns>The newly generated token.</returns> + /// <remarks> + /// This method should not store the newly generated token in any persistent store. + /// This will be done in <see cref="ITokenManager.ExpireRequestTokenAndStoreNewAccessToken"/>. + /// </remarks> + public string GenerateAccessToken(string consumerKey) { + return this.GenerateCryptographicallyStrongString(); + } + + /// <summary> + /// Returns a cryptographically strong random string for use as a token secret. + /// </summary> + /// <returns>The generated string.</returns> + public string GenerateSecret() { + return this.GenerateCryptographicallyStrongString(); + } + + #endregion + + /// <summary> + /// Returns a new random string. + /// </summary> + /// <returns>The new random string.</returns> + private string GenerateCryptographicallyStrongString() { + byte[] buffer = new byte[20]; + this.cryptoProvider.GetBytes(buffer); + return Convert.ToBase64String(buffer); + } + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/StandardWebRequestHandler.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/StandardWebRequestHandler.cs index 12fcd28..7b5463c 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/StandardWebRequestHandler.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/StandardWebRequestHandler.cs @@ -1,70 +1,70 @@ -//-----------------------------------------------------------------------
-// <copyright file="StandardWebRequestHandler.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- using System;
- using System.IO;
- using System.Net;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// The default handler for transmitting <see cref="HttpWebRequest"/> instances
- /// and returning the responses.
- /// </summary>
- internal class StandardWebRequestHandler : IWebRequestHandler {
- #region IWebRequestHandler Members
-
- /// <summary>
- /// Prepares a POST <see cref="HttpWebRequest"/> and returns the request stream
- /// for writing out the POST entity data.
- /// </summary>
- /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
- /// <returns>The stream the caller should write out the entity data to.</returns>
- public TextWriter GetRequestStream(HttpWebRequest request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- try {
- return new StreamWriter(request.GetRequestStream());
- } catch (WebException ex) {
- throw new ProtocolException(MessagingStrings.ErrorInRequestReplyMessage, ex);
- }
- }
-
- /// <summary>
- /// Processes an <see cref="HttpWebRequest"/> and converts the
- /// <see cref="HttpWebResponse"/> to a <see cref="Response"/> instance.
- /// </summary>
- /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
- /// <returns>An instance of <see cref="Response"/> describing the response.</returns>
- public Response GetResponse(HttpWebRequest request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- try {
- Logger.DebugFormat("HTTP {0} {1}", request.Method, request.RequestUri);
- using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
- return new Response(response);
- }
- } catch (WebException ex) {
- if (Logger.IsErrorEnabled) {
- if (ex.Response != null) {
- using (var reader = new StreamReader(ex.Response.GetResponseStream())) {
- Logger.ErrorFormat("WebException from {0}: {1}", ex.Response.ResponseUri, reader.ReadToEnd());
- }
- } else {
- Logger.ErrorFormat("WebException {1} from {0}, no response available.", request.RequestUri, ex.Status);
- }
- }
- throw new ProtocolException(MessagingStrings.ErrorInRequestReplyMessage, ex);
- }
- }
-
- #endregion
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="StandardWebRequestHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + using System; + using System.IO; + using System.Net; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// The default handler for transmitting <see cref="HttpWebRequest"/> instances + /// and returning the responses. + /// </summary> + internal class StandardWebRequestHandler : IWebRequestHandler { + #region IWebRequestHandler Members + + /// <summary> + /// Prepares a POST <see cref="HttpWebRequest"/> and returns the request stream + /// for writing out the POST entity data. + /// </summary> + /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> + /// <returns>The stream the caller should write out the entity data to.</returns> + public TextWriter GetRequestStream(HttpWebRequest request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + try { + return new StreamWriter(request.GetRequestStream()); + } catch (WebException ex) { + throw new ProtocolException(MessagingStrings.ErrorInRequestReplyMessage, ex); + } + } + + /// <summary> + /// Processes an <see cref="HttpWebRequest"/> and converts the + /// <see cref="HttpWebResponse"/> to a <see cref="Response"/> instance. + /// </summary> + /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> + /// <returns>An instance of <see cref="Response"/> describing the response.</returns> + public Response GetResponse(HttpWebRequest request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + try { + Logger.DebugFormat("HTTP {0} {1}", request.Method, request.RequestUri); + using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { + return new Response(response); + } + } catch (WebException ex) { + if (Logger.IsErrorEnabled) { + if (ex.Response != null) { + using (var reader = new StreamReader(ex.Response.GetResponseStream())) { + Logger.ErrorFormat("WebException from {0}: {1}", ex.Response.ResponseUri, reader.ReadToEnd()); + } + } else { + Logger.ErrorFormat("WebException {1} from {0}, no response available.", request.RequestUri, ex.Status); + } + } + throw new ProtocolException(MessagingStrings.ErrorInRequestReplyMessage, ex); + } + } + + #endregion + } +} diff --git a/src/DotNetOAuth/OAuth/ChannelElements/TokenType.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/TokenType.cs index bebdca2..46c2bd9 100644 --- a/src/DotNetOAuth/OAuth/ChannelElements/TokenType.cs +++ b/src/DotNetOpenAuth/OAuth/ChannelElements/TokenType.cs @@ -1,30 +1,30 @@ -//-----------------------------------------------------------------------
-// <copyright file="TokenType.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.ChannelElements {
- /// <summary>
- /// The two types of tokens that exist in the OAuth protocol.
- /// </summary>
- public enum TokenType {
- /// <summary>
- /// A token that is freely issued to any known Consumer.
- /// It does not grant any authorization to access protected resources,
- /// but is used as a step in obtaining that access.
- /// </summary>
- RequestToken,
-
- /// <summary>
- /// A token only obtained after the owner of some protected resource(s)
- /// has approved a Consumer's access to said resource(s).
- /// </summary>
- AccessToken,
-
- /// <summary>
- /// An unrecognized, expired or invalid token.
- /// </summary>
- InvalidToken,
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="TokenType.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.ChannelElements { + /// <summary> + /// The two types of tokens that exist in the OAuth protocol. + /// </summary> + public enum TokenType { + /// <summary> + /// A token that is freely issued to any known Consumer. + /// It does not grant any authorization to access protected resources, + /// but is used as a step in obtaining that access. + /// </summary> + RequestToken, + + /// <summary> + /// A token only obtained after the owner of some protected resource(s) + /// has approved a Consumer's access to said resource(s). + /// </summary> + AccessToken, + + /// <summary> + /// An unrecognized, expired or invalid token. + /// </summary> + InvalidToken, + } +} diff --git a/src/DotNetOAuth/OAuth/ConsumerBase.cs b/src/DotNetOpenAuth/OAuth/ConsumerBase.cs index 6b3a4b9..63c04ea 100644 --- a/src/DotNetOAuth/OAuth/ConsumerBase.cs +++ b/src/DotNetOpenAuth/OAuth/ConsumerBase.cs @@ -1,176 +1,176 @@ -//-----------------------------------------------------------------------
-// <copyright file="ConsumerBase.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using System.Net;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// Base class for <see cref="WebConsumer"/> and <see cref="DesktopConsumer"/> types.
- /// </summary>
- public class ConsumerBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="ConsumerBase"/> class.
- /// </summary>
- /// <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, ITokenManager tokenManager) {
- if (serviceDescription == null) {
- throw new ArgumentNullException("serviceDescription");
- }
- if (tokenManager == null) {
- throw new ArgumentNullException("tokenManager");
- }
-
- this.WebRequestHandler = new StandardWebRequestHandler();
- ITamperProtectionChannelBindingElement signingElement = serviceDescription.CreateTamperProtectionElement();
- INonceStore store = new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge);
- this.OAuthChannel = new OAuthChannel(signingElement, store, tokenManager, new OAuthConsumerMessageTypeProvider(), this.WebRequestHandler);
- this.ServiceProvider = serviceDescription;
- }
-
- /// <summary>
- /// Gets or sets the Consumer Key used to communicate with the Service Provider.
- /// </summary>
- public string ConsumerKey { get; set; }
-
- /// <summary>
- /// Gets the Service Provider that will be accessed.
- /// </summary>
- public ServiceProviderDescription ServiceProvider { get; private set; }
-
- /// <summary>
- /// Gets the persistence store for tokens and secrets.
- /// </summary>
- public ITokenManager TokenManager {
- get { return this.OAuthChannel.TokenManager; }
- }
-
- /// <summary>
- /// Gets the channel to use for sending/receiving messages.
- /// </summary>
- public Channel Channel {
- get { return this.OAuthChannel; }
- }
-
- /// <summary>
- /// Gets or sets the channel to use for sending/receiving messages.
- /// </summary>
- internal OAuthChannel OAuthChannel { get; set; }
-
- /// <summary>
- /// Gets or sets the object that processes <see cref="HttpWebRequest"/>s.
- /// </summary>
- /// <remarks>
- /// This defaults to a straightforward implementation, but can be set
- /// to a mock object for testing purposes.
- /// </remarks>
- internal IWebRequestHandler WebRequestHandler { get; set; }
-
- /// <summary>
- /// Creates a web request prepared with OAuth authorization
- /// that may be further tailored by adding parameters by the caller.
- /// </summary>
- /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param>
- /// <param name="accessToken">The access token that permits access to the protected resource.</param>
- /// <returns>The initialized WebRequest object.</returns>
- public WebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) {
- IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken);
- HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message);
- return wr;
- }
-
- /// <summary>
- /// Creates a web request prepared with OAuth authorization
- /// that may be further tailored by adding parameters by the caller.
- /// </summary>
- /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param>
- /// <param name="accessToken">The access token that permits access to the protected resource.</param>
- /// <returns>The initialized WebRequest object.</returns>
- /// <exception cref="WebException">Thrown if the request fails for any reason after it is sent to the Service Provider.</exception>
- public Response PrepareAuthorizedRequestAndSend(MessageReceivingEndpoint endpoint, string accessToken) {
- IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken);
- HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message);
- return this.WebRequestHandler.GetResponse(wr);
- }
-
- /// <summary>
- /// Prepares an OAuth message that begins an authorization request that will
- /// redirect the user to the Service Provider to provide that authorization.
- /// </summary>
- /// <param name="callback">
- /// An optional Consumer URL that the Service Provider should redirect the
- /// User Agent to upon successful authorization.
- /// </param>
- /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param>
- /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param>
- /// <param name="requestToken">The request token that must be exchanged for an access token after the user has provided authorization.</param>
- /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
- [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "3#", Justification = "Two results")]
- protected internal UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters, out string requestToken) {
- // Obtain an unauthorized request token.
- var token = new UnauthorizedTokenRequest(this.ServiceProvider.RequestTokenEndpoint) {
- ConsumerKey = this.ConsumerKey,
- };
- token.AddNonOAuthParameters(requestParameters);
- var requestTokenResponse = this.Channel.Request<UnauthorizedTokenResponse>(token);
- this.TokenManager.StoreNewRequestToken(token, requestTokenResponse);
-
- // Request user authorization.
- ITokenContainingMessage assignedRequestToken = requestTokenResponse;
- var requestAuthorization = new UserAuthorizationRequest(this.ServiceProvider.UserAuthorizationEndpoint, assignedRequestToken.Token) {
- Callback = callback,
- };
- requestAuthorization.AddNonOAuthParameters(redirectParameters);
- requestToken = requestAuthorization.RequestToken;
- return requestAuthorization;
- }
-
- /// <summary>
- /// Creates a web request prepared with OAuth authorization
- /// that may be further tailored by adding parameters by the caller.
- /// </summary>
- /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param>
- /// <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) {
- if (endpoint == null) {
- throw new ArgumentNullException("endpoint");
- }
- if (String.IsNullOrEmpty(accessToken)) {
- throw new ArgumentNullException("accessToken");
- }
-
- AccessProtectedResourceRequest message = new AccessProtectedResourceRequest(endpoint) {
- AccessToken = accessToken,
- ConsumerKey = this.ConsumerKey,
- };
-
- return message;
- }
-
- /// <summary>
- /// Exchanges a given request token for access token.
- /// </summary>
- /// <param name="requestToken">The request token that the user has authorized.</param>
- /// <returns>The access token assigned by the Service Provider.</returns>
- protected AuthorizedTokenResponse ProcessUserAuthorization(string requestToken) {
- var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint) {
- RequestToken = requestToken,
- ConsumerKey = this.ConsumerKey,
- };
- var grantAccess = this.Channel.Request<AuthorizedTokenResponse>(requestAccess);
- this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(this.ConsumerKey, requestToken, grantAccess.AccessToken, grantAccess.TokenSecret);
- return grantAccess;
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ConsumerBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Net; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// Base class for <see cref="WebConsumer"/> and <see cref="DesktopConsumer"/> types. + /// </summary> + public class ConsumerBase { + /// <summary> + /// Initializes a new instance of the <see cref="ConsumerBase"/> class. + /// </summary> + /// <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, ITokenManager tokenManager) { + if (serviceDescription == null) { + throw new ArgumentNullException("serviceDescription"); + } + if (tokenManager == null) { + throw new ArgumentNullException("tokenManager"); + } + + this.WebRequestHandler = new StandardWebRequestHandler(); + ITamperProtectionChannelBindingElement signingElement = serviceDescription.CreateTamperProtectionElement(); + INonceStore store = new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge); + this.OAuthChannel = new OAuthChannel(signingElement, store, tokenManager, new OAuthConsumerMessageTypeProvider(), this.WebRequestHandler); + this.ServiceProvider = serviceDescription; + } + + /// <summary> + /// Gets or sets the Consumer Key used to communicate with the Service Provider. + /// </summary> + public string ConsumerKey { get; set; } + + /// <summary> + /// Gets the Service Provider that will be accessed. + /// </summary> + public ServiceProviderDescription ServiceProvider { get; private set; } + + /// <summary> + /// Gets the persistence store for tokens and secrets. + /// </summary> + public ITokenManager TokenManager { + get { return this.OAuthChannel.TokenManager; } + } + + /// <summary> + /// Gets the channel to use for sending/receiving messages. + /// </summary> + public Channel Channel { + get { return this.OAuthChannel; } + } + + /// <summary> + /// Gets or sets the channel to use for sending/receiving messages. + /// </summary> + internal OAuthChannel OAuthChannel { get; set; } + + /// <summary> + /// Gets or sets the object that processes <see cref="HttpWebRequest"/>s. + /// </summary> + /// <remarks> + /// This defaults to a straightforward implementation, but can be set + /// to a mock object for testing purposes. + /// </remarks> + internal IWebRequestHandler WebRequestHandler { get; set; } + + /// <summary> + /// Creates a web request prepared with OAuth authorization + /// that may be further tailored by adding parameters by the caller. + /// </summary> + /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> + /// <param name="accessToken">The access token that permits access to the protected resource.</param> + /// <returns>The initialized WebRequest object.</returns> + public WebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) { + IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); + HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message); + return wr; + } + + /// <summary> + /// Creates a web request prepared with OAuth authorization + /// that may be further tailored by adding parameters by the caller. + /// </summary> + /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> + /// <param name="accessToken">The access token that permits access to the protected resource.</param> + /// <returns>The initialized WebRequest object.</returns> + /// <exception cref="WebException">Thrown if the request fails for any reason after it is sent to the Service Provider.</exception> + public Response PrepareAuthorizedRequestAndSend(MessageReceivingEndpoint endpoint, string accessToken) { + IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); + HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message); + return this.WebRequestHandler.GetResponse(wr); + } + + /// <summary> + /// Prepares an OAuth message that begins an authorization request that will + /// redirect the user to the Service Provider to provide that authorization. + /// </summary> + /// <param name="callback"> + /// An optional Consumer URL that the Service Provider should redirect the + /// User Agent to upon successful authorization. + /// </param> + /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param> + /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param> + /// <param name="requestToken">The request token that must be exchanged for an access token after the user has provided authorization.</param> + /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "3#", Justification = "Two results")] + protected internal UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters, out string requestToken) { + // Obtain an unauthorized request token. + var token = new UnauthorizedTokenRequest(this.ServiceProvider.RequestTokenEndpoint) { + ConsumerKey = this.ConsumerKey, + }; + token.AddNonOAuthParameters(requestParameters); + var requestTokenResponse = this.Channel.Request<UnauthorizedTokenResponse>(token); + this.TokenManager.StoreNewRequestToken(token, requestTokenResponse); + + // Request user authorization. + ITokenContainingMessage assignedRequestToken = requestTokenResponse; + var requestAuthorization = new UserAuthorizationRequest(this.ServiceProvider.UserAuthorizationEndpoint, assignedRequestToken.Token) { + Callback = callback, + }; + requestAuthorization.AddNonOAuthParameters(redirectParameters); + requestToken = requestAuthorization.RequestToken; + return requestAuthorization; + } + + /// <summary> + /// Creates a web request prepared with OAuth authorization + /// that may be further tailored by adding parameters by the caller. + /// </summary> + /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> + /// <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) { + if (endpoint == null) { + throw new ArgumentNullException("endpoint"); + } + if (String.IsNullOrEmpty(accessToken)) { + throw new ArgumentNullException("accessToken"); + } + + AccessProtectedResourceRequest message = new AccessProtectedResourceRequest(endpoint) { + AccessToken = accessToken, + ConsumerKey = this.ConsumerKey, + }; + + return message; + } + + /// <summary> + /// Exchanges a given request token for access token. + /// </summary> + /// <param name="requestToken">The request token that the user has authorized.</param> + /// <returns>The access token assigned by the Service Provider.</returns> + protected AuthorizedTokenResponse ProcessUserAuthorization(string requestToken) { + var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint) { + RequestToken = requestToken, + ConsumerKey = this.ConsumerKey, + }; + var grantAccess = this.Channel.Request<AuthorizedTokenResponse>(requestAccess); + this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(this.ConsumerKey, requestToken, grantAccess.AccessToken, grantAccess.TokenSecret); + return grantAccess; + } + } +} diff --git a/src/DotNetOAuth/OAuth/DesktopConsumer.cs b/src/DotNetOpenAuth/OAuth/DesktopConsumer.cs index 62d64f2..20b41fb 100644 --- a/src/DotNetOAuth/OAuth/DesktopConsumer.cs +++ b/src/DotNetOpenAuth/OAuth/DesktopConsumer.cs @@ -1,55 +1,56 @@ -//-----------------------------------------------------------------------
-// <copyright file="DesktopConsumer.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// Used by a desktop application to use OAuth to access the Service Provider on behalf of the User.
- /// </summary>
- /// <remarks>
- /// The methods on this class are thread-safe. Provided the properties are set and not changed
- /// afterward, a single instance of this class may be used by an entire desktop application safely.
- /// </remarks>
- public class DesktopConsumer : ConsumerBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="DesktopConsumer"/> class.
- /// </summary>
- /// <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>
- public DesktopConsumer(ServiceProviderDescription serviceDescription, ITokenManager tokenManager)
- : base(serviceDescription, tokenManager) {
- }
-
- /// <summary>
- /// Begins an OAuth authorization request.
- /// </summary>
- /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param>
- /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param>
- /// <param name="requestToken">The request token that must be exchanged for an access token after the user has provided authorization.</param>
- /// <returns>The URL to open a browser window to allow the user to provide authorization.</returns>
- [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Two results")]
- public Uri RequestUserAuthorization(IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters, out string requestToken) {
- var message = this.PrepareRequestUserAuthorization(null, requestParameters, redirectParameters, out requestToken);
- Response response = this.Channel.Send(message);
- return response.DirectUriRequest;
- }
-
- /// <summary>
- /// Exchanges a given request token for access token.
- /// </summary>
- /// <param name="requestToken">The request token that the user has authorized.</param>
- /// <returns>The access token assigned by the Service Provider.</returns>
- public new AuthorizedTokenResponse ProcessUserAuthorization(string requestToken) {
- return base.ProcessUserAuthorization(requestToken);
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="DesktopConsumer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// Used by a desktop application to use OAuth to access the Service Provider on behalf of the User. + /// </summary> + /// <remarks> + /// The methods on this class are thread-safe. Provided the properties are set and not changed + /// afterward, a single instance of this class may be used by an entire desktop application safely. + /// </remarks> + public class DesktopConsumer : ConsumerBase { + /// <summary> + /// Initializes a new instance of the <see cref="DesktopConsumer"/> class. + /// </summary> + /// <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> + public DesktopConsumer(ServiceProviderDescription serviceDescription, ITokenManager tokenManager) + : base(serviceDescription, tokenManager) { + } + + /// <summary> + /// Begins an OAuth authorization request. + /// </summary> + /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param> + /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param> + /// <param name="requestToken">The request token that must be exchanged for an access token after the user has provided authorization.</param> + /// <returns>The URL to open a browser window to allow the user to provide authorization.</returns> + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Two results")] + public Uri RequestUserAuthorization(IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters, out string requestToken) { + var message = this.PrepareRequestUserAuthorization(null, requestParameters, redirectParameters, out requestToken); + Response response = this.Channel.Send(message); + return response.DirectUriRequest; + } + + /// <summary> + /// Exchanges a given request token for access token. + /// </summary> + /// <param name="requestToken">The request token that the user has authorized.</param> + /// <returns>The access token assigned by the Service Provider.</returns> + public new AuthorizedTokenResponse ProcessUserAuthorization(string requestToken) { + return base.ProcessUserAuthorization(requestToken); + } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth/OAuth/Messages/AccessProtectedResourceRequest.cs index 2704dd5..62e02de 100644 --- a/src/DotNetOAuth/OAuth/Messages/AccessProtectedResourceRequest.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/AccessProtectedResourceRequest.cs @@ -1,45 +1,45 @@ -//-----------------------------------------------------------------------
-// <copyright file="AccessProtectedResourceRequest.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System.Diagnostics.CodeAnalysis;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A message attached to a request for protected resources that provides the necessary
- /// credentials to be granted access to those resources.
- /// </summary>
- public class AccessProtectedResourceRequest : SignedMessageBase, ITokenContainingMessage {
- /// <summary>
- /// Initializes a new instance of the <see cref="AccessProtectedResourceRequest"/> class.
- /// </summary>
- /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param>
- protected internal AccessProtectedResourceRequest(MessageReceivingEndpoint serviceProvider)
- : base(MessageTransport.Direct, serviceProvider) {
- }
-
- /// <summary>
- /// Gets or sets the Token.
- /// </summary>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")]
- string ITokenContainingMessage.Token {
- get { return this.AccessToken; }
- set { this.AccessToken = value; }
- }
-
- /// <summary>
- /// Gets or sets the Access Token.
- /// </summary>
- /// <remarks>
- /// In addition to just allowing OAuth to verify a valid message,
- /// this property is useful on the Service Provider to verify that the access token
- /// has proper authorization for the resource being requested, and to know the
- /// context around which user provided the authorization.
- /// </remarks>
- [MessagePart("oauth_token", IsRequired = true)]
- public string AccessToken { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="AccessProtectedResourceRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System.Diagnostics.CodeAnalysis; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A message attached to a request for protected resources that provides the necessary + /// credentials to be granted access to those resources. + /// </summary> + public class AccessProtectedResourceRequest : SignedMessageBase, ITokenContainingMessage { + /// <summary> + /// Initializes a new instance of the <see cref="AccessProtectedResourceRequest"/> class. + /// </summary> + /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param> + protected internal AccessProtectedResourceRequest(MessageReceivingEndpoint serviceProvider) + : base(MessageTransport.Direct, serviceProvider) { + } + + /// <summary> + /// Gets or sets the Token. + /// </summary> + [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")] + string ITokenContainingMessage.Token { + get { return this.AccessToken; } + set { this.AccessToken = value; } + } + + /// <summary> + /// Gets or sets the Access Token. + /// </summary> + /// <remarks> + /// In addition to just allowing OAuth to verify a valid message, + /// this property is useful on the Service Provider to verify that the access token + /// has proper authorization for the resource being requested, and to know the + /// context around which user provided the authorization. + /// </remarks> + [MessagePart("oauth_token", IsRequired = true)] + public string AccessToken { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/AuthorizedTokenRequest.cs b/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenRequest.cs index 8f76046..d53221d 100644 --- a/src/DotNetOAuth/OAuth/Messages/AuthorizedTokenRequest.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenRequest.cs @@ -1,53 +1,53 @@ -//-----------------------------------------------------------------------
-// <copyright file="AuthorizedTokenRequest.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System.Globalization;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A direct message sent by the Consumer to exchange an authorized Request Token
- /// for an Access Token and Token Secret.
- /// </summary>
- /// <remarks>
- /// The class is sealed because the OAuth spec forbids adding parameters to this message.
- /// </remarks>
- public sealed class AuthorizedTokenRequest : SignedMessageBase, ITokenContainingMessage {
- /// <summary>
- /// Initializes a new instance of the <see cref="AuthorizedTokenRequest"/> class.
- /// </summary>
- /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param>
- internal AuthorizedTokenRequest(MessageReceivingEndpoint serviceProvider)
- : base(MessageTransport.Direct, serviceProvider) {
- }
-
- /// <summary>
- /// Gets or sets the Token.
- /// </summary>
- string ITokenContainingMessage.Token {
- get { return this.RequestToken; }
- set { this.RequestToken = value; }
- }
-
- /// <summary>
- /// Gets or sets the unauthorized Request Token used to obtain authorization.
- /// </summary>
- [MessagePart("oauth_token", IsRequired = true)]
- internal string RequestToken { get; set; }
-
- /// <summary>
- /// Checks the message state for conformity to the protocol specification
- /// and throws an exception if the message is invalid.
- /// </summary>
- protected override void EnsureValidMessage() {
- base.EnsureValidMessage();
-
- if (this.ExtraData.Count > 0) {
- throw new ProtocolException(string.Format(CultureInfo.CurrentCulture, Strings.MessageNotAllowedExtraParameters, GetType().Name));
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="AuthorizedTokenRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System.Globalization; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A direct message sent by the Consumer to exchange an authorized Request Token + /// for an Access Token and Token Secret. + /// </summary> + /// <remarks> + /// The class is sealed because the OAuth spec forbids adding parameters to this message. + /// </remarks> + public sealed class AuthorizedTokenRequest : SignedMessageBase, ITokenContainingMessage { + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizedTokenRequest"/> class. + /// </summary> + /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param> + internal AuthorizedTokenRequest(MessageReceivingEndpoint serviceProvider) + : base(MessageTransport.Direct, serviceProvider) { + } + + /// <summary> + /// Gets or sets the Token. + /// </summary> + string ITokenContainingMessage.Token { + get { return this.RequestToken; } + set { this.RequestToken = value; } + } + + /// <summary> + /// Gets or sets the unauthorized Request Token used to obtain authorization. + /// </summary> + [MessagePart("oauth_token", IsRequired = true)] + internal string RequestToken { get; set; } + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + protected override void EnsureValidMessage() { + base.EnsureValidMessage(); + + if (this.ExtraData.Count > 0) { + throw new ProtocolException(string.Format(CultureInfo.CurrentCulture, Strings.MessageNotAllowedExtraParameters, GetType().Name)); + } + } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/AuthorizedTokenResponse.cs b/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenResponse.cs index 4c28edd..3030c01 100644 --- a/src/DotNetOAuth/OAuth/Messages/AuthorizedTokenResponse.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/AuthorizedTokenResponse.cs @@ -1,60 +1,60 @@ -//-----------------------------------------------------------------------
-// <copyright file="AuthorizedTokenResponse.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A direct message sent from Service Provider to Consumer in response to
- /// a Consumer's <see cref="AuthorizedTokenRequest"/> request.
- /// </summary>
- public class AuthorizedTokenResponse : MessageBase, ITokenSecretContainingMessage {
- /// <summary>
- /// Initializes a new instance of the <see cref="AuthorizedTokenResponse"/> class.
- /// </summary>
- protected internal AuthorizedTokenResponse()
- : base(MessageProtections.None, MessageTransport.Direct) {
- }
-
- /// <summary>
- /// Gets or sets the Access Token assigned by the Service Provider.
- /// </summary>
- [MessagePart("oauth_token", IsRequired = true)]
- public string AccessToken { get; set; }
-
- /// <summary>
- /// Gets or sets the Request or Access Token.
- /// </summary>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")]
- string ITokenContainingMessage.Token {
- get { return this.AccessToken; }
- set { this.AccessToken = value; }
- }
-
- /// <summary>
- /// Gets or sets the Request or Access Token secret.
- /// </summary>
- string ITokenSecretContainingMessage.TokenSecret {
- get { return this.TokenSecret; }
- set { this.TokenSecret = value; }
- }
-
- /// <summary>
- /// Gets the extra, non-OAuth parameters that will be included in the message.
- /// </summary>
- public new IDictionary<string, string> ExtraData {
- get { return base.ExtraData; }
- }
-
- /// <summary>
- /// Gets or sets the Token Secret.
- /// </summary>
- [MessagePart("oauth_token_secret", IsRequired = true)]
- protected internal string TokenSecret { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="AuthorizedTokenResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A direct message sent from Service Provider to Consumer in response to + /// a Consumer's <see cref="AuthorizedTokenRequest"/> request. + /// </summary> + public class AuthorizedTokenResponse : MessageBase, ITokenSecretContainingMessage { + /// <summary> + /// Initializes a new instance of the <see cref="AuthorizedTokenResponse"/> class. + /// </summary> + protected internal AuthorizedTokenResponse() + : base(MessageProtections.None, MessageTransport.Direct) { + } + + /// <summary> + /// Gets or sets the Access Token assigned by the Service Provider. + /// </summary> + [MessagePart("oauth_token", IsRequired = true)] + public string AccessToken { get; set; } + + /// <summary> + /// Gets or sets the Request or Access Token. + /// </summary> + [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")] + string ITokenContainingMessage.Token { + get { return this.AccessToken; } + set { this.AccessToken = value; } + } + + /// <summary> + /// Gets or sets the Request or Access Token secret. + /// </summary> + string ITokenSecretContainingMessage.TokenSecret { + get { return this.TokenSecret; } + set { this.TokenSecret = value; } + } + + /// <summary> + /// Gets the extra, non-OAuth parameters that will be included in the message. + /// </summary> + public new IDictionary<string, string> ExtraData { + get { return base.ExtraData; } + } + + /// <summary> + /// Gets or sets the Token Secret. + /// </summary> + [MessagePart("oauth_token_secret", IsRequired = true)] + protected internal string TokenSecret { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/ITokenContainingMessage.cs b/src/DotNetOpenAuth/OAuth/Messages/ITokenContainingMessage.cs index 57ee86d..832b754 100644 --- a/src/DotNetOAuth/OAuth/Messages/ITokenContainingMessage.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/ITokenContainingMessage.cs @@ -1,17 +1,17 @@ -//-----------------------------------------------------------------------
-// <copyright file="ITokenContainingMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- /// <summary>
- /// An interface implemented by all OAuth messages that have a request or access token property.
- /// </summary>
- public interface ITokenContainingMessage {
- /// <summary>
- /// Gets or sets the Request or Access Token.
- /// </summary>
- string Token { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ITokenContainingMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + /// <summary> + /// An interface implemented by all OAuth messages that have a request or access token property. + /// </summary> + public interface ITokenContainingMessage { + /// <summary> + /// Gets or sets the Request or Access Token. + /// </summary> + string Token { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/ITokenSecretContainingMessage.cs b/src/DotNetOpenAuth/OAuth/Messages/ITokenSecretContainingMessage.cs index 98d09ee..95809ec 100644 --- a/src/DotNetOAuth/OAuth/Messages/ITokenSecretContainingMessage.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/ITokenSecretContainingMessage.cs @@ -1,17 +1,17 @@ -//-----------------------------------------------------------------------
-// <copyright file="ITokenSecretContainingMessage.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- /// <summary>
- /// An interface implemented by all OAuth messages that have a request or access token and secret properties.
- /// </summary>
- public interface ITokenSecretContainingMessage : ITokenContainingMessage {
- /// <summary>
- /// Gets or sets the Request or Access Token secret.
- /// </summary>
- string TokenSecret { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ITokenSecretContainingMessage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + /// <summary> + /// An interface implemented by all OAuth messages that have a request or access token and secret properties. + /// </summary> + public interface ITokenSecretContainingMessage : ITokenContainingMessage { + /// <summary> + /// Gets or sets the Request or Access Token secret. + /// </summary> + string TokenSecret { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/MessageBase.cs b/src/DotNetOpenAuth/OAuth/Messages/MessageBase.cs index a74b9f2..35a0c16 100644 --- a/src/DotNetOAuth/OAuth/Messages/MessageBase.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/MessageBase.cs @@ -1,239 +1,239 @@ -//-----------------------------------------------------------------------
-// <copyright file="MessageBase.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Text;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Reflection;
- using DotNetOAuth.OAuth.ChannelElements;
-
- /// <summary>
- /// A base class for all OAuth messages.
- /// </summary>
- public abstract class MessageBase : IOAuthDirectedMessage {
- /// <summary>
- /// A store for extra name/value data pairs that are attached to this message.
- /// </summary>
- private Dictionary<string, string> extraData = new Dictionary<string, string>();
-
- /// <summary>
- /// Gets a value indicating whether signing this message is required.
- /// </summary>
- private MessageProtections protectionRequired;
-
- /// <summary>
- /// Gets a value indicating whether this is a direct or indirect message.
- /// </summary>
- private MessageTransport transport;
-
- /// <summary>
- /// The URI to the remote endpoint to send this message to.
- /// </summary>
- private MessageReceivingEndpoint recipient;
-
-#if DEBUG
- /// <summary>
- /// Initializes static members of the <see cref="MessageBase"/> class.
- /// </summary>
- static MessageBase() {
- LowSecurityMode = true;
- }
-#endif
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessageBase"/> class.
- /// </summary>
- /// <param name="protectionRequired">The level of protection the message requires.</param>
- /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
- protected MessageBase(MessageProtections protectionRequired, MessageTransport transport) {
- this.protectionRequired = protectionRequired;
- this.transport = transport;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="MessageBase"/> class.
- /// </summary>
- /// <param name="protectionRequired">The level of protection the message requires.</param>
- /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
- /// <param name="recipient">The URI that a directed message will be delivered to.</param>
- protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient) {
- if (recipient == null) {
- throw new ArgumentNullException("recipient");
- }
-
- this.protectionRequired = protectionRequired;
- this.transport = transport;
- this.recipient = recipient;
- }
-
- #region IProtocolMessage Properties
-
- /// <summary>
- /// Gets the version of the protocol this message is prepared to implement.
- /// </summary>
- Version IProtocolMessage.ProtocolVersion {
- get { return this.ProtocolVersion; }
- }
-
- /// <summary>
- /// Gets the level of protection this message requires.
- /// </summary>
- MessageProtections IProtocolMessage.RequiredProtection {
- get { return this.RequiredProtection; }
- }
-
- /// <summary>
- /// Gets a value indicating whether this is a direct or indirect message.
- /// </summary>
- MessageTransport IProtocolMessage.Transport {
- get { return this.Transport; }
- }
-
- /// <summary>
- /// Gets the dictionary of additional name/value fields tacked on to this message.
- /// </summary>
- IDictionary<string, string> IProtocolMessage.ExtraData {
- get { return this.ExtraData; }
- }
-
- #endregion
-
- #region IDirectedProtocolMessage Members
-
- /// <summary>
- /// Gets the URI to the Service Provider endpoint to send this message to.
- /// </summary>
- Uri IDirectedProtocolMessage.Recipient {
- get { return this.recipient.Location; }
- }
-
- #endregion
-
- #region IOAuthDirectedMessage Properties
-
- /// <summary>
- /// Gets the preferred method of transport for the message.
- /// </summary>
- HttpDeliveryMethods IOAuthDirectedMessage.HttpMethods {
- get { return this.HttpMethods; }
- }
-
- /// <summary>
- /// Gets or sets the URI to the Service Provider endpoint to send this message to.
- /// </summary>
- Uri IOAuthDirectedMessage.Recipient {
- get { return this.Recipient; }
- set { this.Recipient = value; }
- }
-
- #endregion
-
- /// <summary>
- /// Gets or sets a value indicating whether security sensitive strings are
- /// emitted from the ToString() method.
- /// </summary>
- internal static bool LowSecurityMode { get; set; }
-
- /// <summary>
- /// Gets the version of the protocol this message is prepared to implement.
- /// </summary>
- protected virtual Version ProtocolVersion {
- get { return new Version(1, 0); }
- }
-
- /// <summary>
- /// Gets the level of protection this message requires.
- /// </summary>
- protected MessageProtections RequiredProtection {
- get { return this.protectionRequired; }
- }
-
- /// <summary>
- /// Gets a value indicating whether this is a direct or indirect message.
- /// </summary>
- protected MessageTransport Transport {
- get { return this.transport; }
- }
-
- /// <summary>
- /// Gets the dictionary of additional name/value fields tacked on to this message.
- /// </summary>
- protected IDictionary<string, string> ExtraData {
- get { return this.extraData; }
- }
-
- /// <summary>
- /// Gets the preferred method of transport for the message.
- /// </summary>
- protected HttpDeliveryMethods HttpMethods {
- get { return this.recipient != null ? this.recipient.AllowedMethods : HttpDeliveryMethods.None; }
- }
-
- /// <summary>
- /// Gets or sets the URI to the Service Provider endpoint to send this message to.
- /// </summary>
- protected Uri Recipient {
- get {
- return this.recipient != null ? this.recipient.Location : null;
- }
-
- set {
- if (this.recipient != null) {
- this.recipient = new MessageReceivingEndpoint(value, this.recipient.AllowedMethods);
- } else if (value != null) {
- throw new InvalidOperationException();
- }
- }
- }
-
- #region IProtocolMessage Methods
-
- /// <summary>
- /// Checks the message state for conformity to the protocol specification
- /// and throws an exception if the message is invalid.
- /// </summary>
- void IProtocolMessage.EnsureValidMessage() {
- this.EnsureValidMessage();
- }
-
- #endregion
-
- /// <summary>
- /// Returns a human-friendly string describing the message and all serializable properties.
- /// </summary>
- /// <returns>The string representation of this object.</returns>
- public override string ToString() {
- StringBuilder builder = new StringBuilder();
- builder.AppendFormat(CultureInfo.InvariantCulture, "{0} message", GetType().Name);
- if (this.recipient != null) {
- builder.AppendFormat(CultureInfo.InvariantCulture, " as {0} to {1}", this.recipient.AllowedMethods, this.recipient.Location);
- }
- builder.AppendLine();
- MessageDictionary dictionary = new MessageDictionary(this);
- foreach (var pair in dictionary) {
- string value = pair.Value;
- if (pair.Key == "oauth_signature" && !LowSecurityMode) {
- value = "xxxxxxxxxxxxx (not shown)";
- }
- builder.Append('\t');
- builder.Append(pair.Key);
- builder.Append(": ");
- builder.AppendLine(value);
- }
-
- return builder.ToString();
- }
-
- /// <summary>
- /// Checks the message state for conformity to the protocol specification
- /// and throws an exception if the message is invalid.
- /// </summary>
- protected virtual void EnsureValidMessage() { }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="MessageBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Text; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OAuth.ChannelElements; + + /// <summary> + /// A base class for all OAuth messages. + /// </summary> + public abstract class MessageBase : IOAuthDirectedMessage { + /// <summary> + /// A store for extra name/value data pairs that are attached to this message. + /// </summary> + private Dictionary<string, string> extraData = new Dictionary<string, string>(); + + /// <summary> + /// Gets a value indicating whether signing this message is required. + /// </summary> + private MessageProtections protectionRequired; + + /// <summary> + /// Gets a value indicating whether this is a direct or indirect message. + /// </summary> + private MessageTransport transport; + + /// <summary> + /// The URI to the remote endpoint to send this message to. + /// </summary> + private MessageReceivingEndpoint recipient; + +#if DEBUG + /// <summary> + /// Initializes static members of the <see cref="MessageBase"/> class. + /// </summary> + static MessageBase() { + LowSecurityMode = true; + } +#endif + + /// <summary> + /// Initializes a new instance of the <see cref="MessageBase"/> class. + /// </summary> + /// <param name="protectionRequired">The level of protection the message requires.</param> + /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param> + protected MessageBase(MessageProtections protectionRequired, MessageTransport transport) { + this.protectionRequired = protectionRequired; + this.transport = transport; + } + + /// <summary> + /// Initializes a new instance of the <see cref="MessageBase"/> class. + /// </summary> + /// <param name="protectionRequired">The level of protection the message requires.</param> + /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param> + /// <param name="recipient">The URI that a directed message will be delivered to.</param> + protected MessageBase(MessageProtections protectionRequired, MessageTransport transport, MessageReceivingEndpoint recipient) { + if (recipient == null) { + throw new ArgumentNullException("recipient"); + } + + this.protectionRequired = protectionRequired; + this.transport = transport; + this.recipient = recipient; + } + + #region IProtocolMessage Properties + + /// <summary> + /// Gets the version of the protocol this message is prepared to implement. + /// </summary> + Version IProtocolMessage.ProtocolVersion { + get { return this.ProtocolVersion; } + } + + /// <summary> + /// Gets the level of protection this message requires. + /// </summary> + MessageProtections IProtocolMessage.RequiredProtection { + get { return this.RequiredProtection; } + } + + /// <summary> + /// Gets a value indicating whether this is a direct or indirect message. + /// </summary> + MessageTransport IProtocolMessage.Transport { + get { return this.Transport; } + } + + /// <summary> + /// Gets the dictionary of additional name/value fields tacked on to this message. + /// </summary> + IDictionary<string, string> IProtocolMessage.ExtraData { + get { return this.ExtraData; } + } + + #endregion + + #region IDirectedProtocolMessage Members + + /// <summary> + /// Gets the URI to the Service Provider endpoint to send this message to. + /// </summary> + Uri IDirectedProtocolMessage.Recipient { + get { return this.recipient.Location; } + } + + #endregion + + #region IOAuthDirectedMessage Properties + + /// <summary> + /// Gets the preferred method of transport for the message. + /// </summary> + HttpDeliveryMethods IOAuthDirectedMessage.HttpMethods { + get { return this.HttpMethods; } + } + + /// <summary> + /// Gets or sets the URI to the Service Provider endpoint to send this message to. + /// </summary> + Uri IOAuthDirectedMessage.Recipient { + get { return this.Recipient; } + set { this.Recipient = value; } + } + + #endregion + + /// <summary> + /// Gets or sets a value indicating whether security sensitive strings are + /// emitted from the ToString() method. + /// </summary> + internal static bool LowSecurityMode { get; set; } + + /// <summary> + /// Gets the version of the protocol this message is prepared to implement. + /// </summary> + protected virtual Version ProtocolVersion { + get { return new Version(1, 0); } + } + + /// <summary> + /// Gets the level of protection this message requires. + /// </summary> + protected MessageProtections RequiredProtection { + get { return this.protectionRequired; } + } + + /// <summary> + /// Gets a value indicating whether this is a direct or indirect message. + /// </summary> + protected MessageTransport Transport { + get { return this.transport; } + } + + /// <summary> + /// Gets the dictionary of additional name/value fields tacked on to this message. + /// </summary> + protected IDictionary<string, string> ExtraData { + get { return this.extraData; } + } + + /// <summary> + /// Gets the preferred method of transport for the message. + /// </summary> + protected HttpDeliveryMethods HttpMethods { + get { return this.recipient != null ? this.recipient.AllowedMethods : HttpDeliveryMethods.None; } + } + + /// <summary> + /// Gets or sets the URI to the Service Provider endpoint to send this message to. + /// </summary> + protected Uri Recipient { + get { + return this.recipient != null ? this.recipient.Location : null; + } + + set { + if (this.recipient != null) { + this.recipient = new MessageReceivingEndpoint(value, this.recipient.AllowedMethods); + } else if (value != null) { + throw new InvalidOperationException(); + } + } + } + + #region IProtocolMessage Methods + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + void IProtocolMessage.EnsureValidMessage() { + this.EnsureValidMessage(); + } + + #endregion + + /// <summary> + /// Returns a human-friendly string describing the message and all serializable properties. + /// </summary> + /// <returns>The string representation of this object.</returns> + public override string ToString() { + StringBuilder builder = new StringBuilder(); + builder.AppendFormat(CultureInfo.InvariantCulture, "{0} message", GetType().Name); + if (this.recipient != null) { + builder.AppendFormat(CultureInfo.InvariantCulture, " as {0} to {1}", this.recipient.AllowedMethods, this.recipient.Location); + } + builder.AppendLine(); + MessageDictionary dictionary = new MessageDictionary(this); + foreach (var pair in dictionary) { + string value = pair.Value; + if (pair.Key == "oauth_signature" && !LowSecurityMode) { + value = "xxxxxxxxxxxxx (not shown)"; + } + builder.Append('\t'); + builder.Append(pair.Key); + builder.Append(": "); + builder.AppendLine(value); + } + + return builder.ToString(); + } + + /// <summary> + /// Checks the message state for conformity to the protocol specification + /// and throws an exception if the message is invalid. + /// </summary> + protected virtual void EnsureValidMessage() { } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/OAuth Messages.cd b/src/DotNetOpenAuth/OAuth/Messages/OAuth Messages.cd index 414644a..6e1696e 100644 --- a/src/DotNetOAuth/OAuth/Messages/OAuth Messages.cd +++ b/src/DotNetOpenAuth/OAuth/Messages/OAuth Messages.cd @@ -1,215 +1,215 @@ -<?xml version="1.0" encoding="utf-8"?>
-<ClassDiagram MajorVersion="1" MinorVersion="1" GroupingSetting="Access">
- <Comment CommentText="Messages from Service Provider">
- <Position X="7.912" Y="0.715" Height="0.291" Width="2.02" />
- </Comment>
- <Comment CommentText="Messages from Consumer">
- <Position X="4.36" Y="0.683" Height="0.291" Width="2.02" />
- </Comment>
- <Class Name="DotNetOAuth.OAuth.Messages.AccessProtectedResourceRequest">
- <Position X="4.25" Y="7.75" Width="3" />
- <Members>
- <Property Name="ITokenContainingMessage.Token" Hidden="true" />
- </Members>
- <InheritanceLine Type="DotNetOAuth.OAuth.Messages.SignedMessageBase" ManuallyRouted="true" FixedFromPoint="true" FixedToPoint="true">
- <Path>
- <Point X="3.5" Y="5.626" />
- <Point X="3.5" Y="8.25" />
- <Point X="4.25" Y="8.25" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>AAAAAAACAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messages\AccessProtectedResourceRequest.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.UnauthorizedTokenResponse">
- <Position X="7.5" Y="1.5" Width="3" />
- <Members>
- <Property Name="ITokenContainingMessage.Token" Hidden="true" />
- <Property Name="ITokenSecretContainingMessage.TokenSecret" Hidden="true" />
- </Members>
- <Compartments>
- <Compartment Name="Methods" Collapsed="true" />
- </Compartments>
- <TypeIdentifier>
- <HashCode>AAAAAAACAAAAAAAAAAEAAAAAAIAAIAAAIAAAAAAAAAA=</HashCode>
- <FileName>Messages\UnauthorizedTokenResponse.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.UserAuthorizationResponse">
- <Position X="7.5" Y="4.5" Width="3" />
- <Members>
- <Property Name="ITokenContainingMessage.Token" Hidden="true" />
- </Members>
- <Compartments>
- <Compartment Name="Methods" Collapsed="true" />
- </Compartments>
- <InheritanceLine Type="DotNetOAuth.OAuth.Messages.MessageBase" FixedFromPoint="true" FixedToPoint="true">
- <Path>
- <Point X="10.75" Y="4.688" />
- <Point X="10.5" Y="4.688" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>AAAAAAACAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messages\UserAuthorizationResponse.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.UserAuthorizationRequest">
- <Position X="4.25" Y="3" Width="3" />
- <Members>
- <Property Name="ITokenContainingMessage.Token" Hidden="true" />
- </Members>
- <Compartments>
- <Compartment Name="Methods" Collapsed="true" />
- </Compartments>
- <InheritanceLine Type="DotNetOAuth.OAuth.Messages.MessageBase" FixedFromPoint="true" FixedToPoint="true">
- <Path>
- <Point X="10.75" Y="4.125" />
- <Point X="7.25" Y="4.125" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>AAAAAAACAAAAAAAAAAAAAAAAAIAAAAAAIAAAAAAAQAA=</HashCode>
- <FileName>Messages\UserAuthorizationRequest.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.AuthorizedTokenResponse">
- <Position X="7.5" Y="6.25" Width="3" />
- <Members>
- <Property Name="ITokenContainingMessage.Token" Hidden="true" />
- <Property Name="ITokenSecretContainingMessage.TokenSecret" Hidden="true" />
- </Members>
- <Compartments>
- <Compartment Name="Methods" Collapsed="true" />
- </Compartments>
- <InheritanceLine Type="DotNetOAuth.OAuth.Messages.MessageBase" ManuallyRouted="true" FixedFromPoint="true" FixedToPoint="true">
- <Path>
- <Point X="11" Y="4.805" />
- <Point X="11" Y="7.013" />
- <Point X="10.5" Y="7.013" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>AAAAAAACAAAAAAAAAAAAAAAAEAAAIAAAIAAAAAAAAAA=</HashCode>
- <FileName>Messages\AuthorizedTokenResponse.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.MessageBase">
- <Position X="10.75" Y="1" Width="3.5" />
- <Members>
- <Field Name="extraData" Hidden="true" />
- <Property Name="IDirectedProtocolMessage.Recipient" Hidden="true" />
- <Property Name="IOAuthDirectedMessage.HttpMethods" Hidden="true" />
- <Property Name="IOAuthDirectedMessage.Recipient" Hidden="true" />
- <Method Name="IProtocolMessage.EnsureValidMessage" Hidden="true" />
- <Property Name="IProtocolMessage.ExtraData" Hidden="true" />
- <Property Name="IProtocolMessage.ProtocolVersion" Hidden="true" />
- <Property Name="IProtocolMessage.RequiredProtection" Hidden="true" />
- <Property Name="IProtocolMessage.Transport" Hidden="true" />
- <Field Name="protectionRequired" Hidden="true" />
- <Field Name="recipient" Hidden="true" />
- <Field Name="transport" Hidden="true" />
- </Members>
- <Compartments>
- <Compartment Name="Fields" Collapsed="true" />
- </Compartments>
- <TypeIdentifier>
- <HashCode>AAAKAAAAYAAAgAEEAIAAAAYAAAQEIDAAIgCCACAAAAA=</HashCode>
- <FileName>Messages\MessageBase.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.AuthorizedTokenRequest">
- <Position X="4.25" Y="5.5" Width="3" />
- <Members>
- <Property Name="ITokenContainingMessage.Token" Hidden="true" />
- </Members>
- <Compartments>
- <Compartment Name="Methods" Collapsed="true" />
- </Compartments>
- <InheritanceLine Type="DotNetOAuth.OAuth.Messages.SignedMessageBase" ManuallyRouted="true" FixedFromPoint="true" FixedToPoint="true">
- <Path>
- <Point X="4" Y="4.947" />
- <Point X="4.123" Y="4.947" />
- <Point X="4.123" Y="5.75" />
- <Point X="4.25" Y="5.75" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>AAAAAAACQAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messages\AuthorizedTokenRequest.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.UnauthorizedTokenRequest">
- <Position X="4.25" Y="1" Width="3" />
- <Compartments>
- <Compartment Name="Internal" Collapsed="true" />
- <Compartment Name="Private" Collapsed="true" />
- <Compartment Name="Methods" Collapsed="true" />
- </Compartments>
- <InheritanceLine Type="DotNetOAuth.OAuth.Messages.SignedMessageBase" FixedFromPoint="true">
- <Path>
- <Point X="4" Y="1.855" />
- <Point X="4.25" Y="1.855" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAA=</HashCode>
- <FileName>Messages\UnauthorizedTokenRequest.cs</FileName>
- </TypeIdentifier>
- </Class>
- <Class Name="DotNetOAuth.OAuth.Messages.SignedMessageBase">
- <Position X="0.5" Y="1.5" Width="3.5" />
- <Members>
- <Property Name="ITamperResistantOAuthMessage.ConsumerSecret" Hidden="true" />
- <Property Name="ITamperResistantOAuthMessage.HttpMethod" Hidden="true" />
- <Property Name="ITamperResistantOAuthMessage.SignatureMethod" Hidden="true" />
- <Property Name="ITamperResistantOAuthMessage.TokenSecret" Hidden="true" />
- <Property Name="ITamperResistantProtocolMessage.Signature" Hidden="true" />
- </Members>
- <InheritanceLine Type="DotNetOAuth.OAuth.Messages.MessageBase" FixedFromPoint="true" FixedToPoint="true">
- <Path>
- <Point X="12.875" Y="1" />
- <Point X="12.875" Y="0.625" />
- <Point X="3" Y="0.625" />
- <Point X="3" Y="1.5" />
- </Path>
- </InheritanceLine>
- <TypeIdentifier>
- <HashCode>IIAAFAAAAIAAAAAAgICAAgAAAgAAIAQAAAEAIAAQAAE=</HashCode>
- <FileName>Messages\SignedMessageBase.cs</FileName>
- </TypeIdentifier>
- <Lollipop Position="0.2" />
- </Class>
- <Interface Name="DotNetOAuth.OAuth.ChannelElements.ITamperResistantOAuthMessage">
- <Position X="11.25" Y="5.25" Width="2.5" />
- <TypeIdentifier>
- <HashCode>AIAAAAAAAAAAAAAAAIAAAgAAAAAAIAQAAAAAAAAAAAA=</HashCode>
- <FileName>ChannelElements\ITamperResistantOAuthMessage.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Interface Name="DotNetOAuth.OAuth.Messages.ITokenSecretContainingMessage">
- <Position X="1" Y="7.5" Width="2" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAA=</HashCode>
- <FileName>Messages\ITokenSecretContainingMessage.cs</FileName>
- <NewMemberFileName>Messages\ITokenContainingMessage.cs</NewMemberFileName>
- </TypeIdentifier>
- </Interface>
- <Interface Name="DotNetOAuth.OAuth.Messages.ITokenContainingMessage">
- <Position X="1" Y="6" Width="2" />
- <TypeIdentifier>
- <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAA=</HashCode>
- <FileName>Messages\ITokenContainingMessage.cs</FileName>
- </TypeIdentifier>
- </Interface>
- <Font Name="Segoe UI" Size="9" />
+<?xml version="1.0" encoding="utf-8"?> +<ClassDiagram MajorVersion="1" MinorVersion="1" GroupingSetting="Access"> + <Comment CommentText="Messages from Service Provider"> + <Position X="7.912" Y="0.715" Height="0.291" Width="2.02" /> + </Comment> + <Comment CommentText="Messages from Consumer"> + <Position X="4.36" Y="0.683" Height="0.291" Width="2.02" /> + </Comment> + <Class Name="DotNetOpenAuth.Messages.AccessProtectedResourceRequest"> + <Position X="4.25" Y="7.75" Width="3" /> + <Members> + <Property Name="ITokenContainingMessage.Token" Hidden="true" /> + </Members> + <InheritanceLine Type="DotNetOpenAuth.Messages.SignedMessageBase" ManuallyRouted="true" FixedFromPoint="true" FixedToPoint="true"> + <Path> + <Point X="3.5" Y="5.626" /> + <Point X="3.5" Y="8.25" /> + <Point X="4.25" Y="8.25" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAACAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messages\AccessProtectedResourceRequest.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messages.UnauthorizedTokenResponse"> + <Position X="7.5" Y="1.5" Width="3" /> + <Members> + <Property Name="ITokenContainingMessage.Token" Hidden="true" /> + <Property Name="ITokenSecretContainingMessage.TokenSecret" Hidden="true" /> + </Members> + <Compartments> + <Compartment Name="Methods" Collapsed="true" /> + </Compartments> + <TypeIdentifier> + <HashCode>AAAAAAACAAAAAAAAAAEAAAAAAIAAIAAAIAAAAAAAAAA=</HashCode> + <FileName>Messages\UnauthorizedTokenResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messages.UserAuthorizationResponse"> + <Position X="7.5" Y="4.5" Width="3" /> + <Members> + <Property Name="ITokenContainingMessage.Token" Hidden="true" /> + </Members> + <Compartments> + <Compartment Name="Methods" Collapsed="true" /> + </Compartments> + <InheritanceLine Type="DotNetOpenAuth.Messages.MessageBase" FixedFromPoint="true" FixedToPoint="true"> + <Path> + <Point X="10.75" Y="4.688" /> + <Point X="10.5" Y="4.688" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAACAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messages\UserAuthorizationResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messages.UserAuthorizationRequest"> + <Position X="4.25" Y="3" Width="3" /> + <Members> + <Property Name="ITokenContainingMessage.Token" Hidden="true" /> + </Members> + <Compartments> + <Compartment Name="Methods" Collapsed="true" /> + </Compartments> + <InheritanceLine Type="DotNetOpenAuth.Messages.MessageBase" FixedFromPoint="true" FixedToPoint="true"> + <Path> + <Point X="10.75" Y="4.125" /> + <Point X="7.25" Y="4.125" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAACAAAAAAAAAAAAAAAAAIAAAAAAIAAAAAAAQAA=</HashCode> + <FileName>Messages\UserAuthorizationRequest.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messages.AuthorizedTokenResponse"> + <Position X="7.5" Y="6.25" Width="3" /> + <Members> + <Property Name="ITokenContainingMessage.Token" Hidden="true" /> + <Property Name="ITokenSecretContainingMessage.TokenSecret" Hidden="true" /> + </Members> + <Compartments> + <Compartment Name="Methods" Collapsed="true" /> + </Compartments> + <InheritanceLine Type="DotNetOpenAuth.Messages.MessageBase" ManuallyRouted="true" FixedFromPoint="true" FixedToPoint="true"> + <Path> + <Point X="11" Y="4.805" /> + <Point X="11" Y="7.013" /> + <Point X="10.5" Y="7.013" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAACAAAAAAAAAAAAAAAAEAAAIAAAIAAAAAAAAAA=</HashCode> + <FileName>Messages\AuthorizedTokenResponse.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messages.MessageBase"> + <Position X="10.75" Y="1" Width="3.5" /> + <Members> + <Field Name="extraData" Hidden="true" /> + <Property Name="IDirectedProtocolMessage.Recipient" Hidden="true" /> + <Property Name="IOAuthDirectedMessage.HttpMethods" Hidden="true" /> + <Property Name="IOAuthDirectedMessage.Recipient" Hidden="true" /> + <Method Name="IProtocolMessage.EnsureValidMessage" Hidden="true" /> + <Property Name="IProtocolMessage.ExtraData" Hidden="true" /> + <Property Name="IProtocolMessage.ProtocolVersion" Hidden="true" /> + <Property Name="IProtocolMessage.RequiredProtection" Hidden="true" /> + <Property Name="IProtocolMessage.Transport" Hidden="true" /> + <Field Name="protectionRequired" Hidden="true" /> + <Field Name="recipient" Hidden="true" /> + <Field Name="transport" Hidden="true" /> + </Members> + <Compartments> + <Compartment Name="Fields" Collapsed="true" /> + </Compartments> + <TypeIdentifier> + <HashCode>AAAKAAAAYAAAgAEEAIAAAAYAAAQEIDAAIgCCACAAAAA=</HashCode> + <FileName>Messages\MessageBase.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messages.AuthorizedTokenRequest"> + <Position X="4.25" Y="5.5" Width="3" /> + <Members> + <Property Name="ITokenContainingMessage.Token" Hidden="true" /> + </Members> + <Compartments> + <Compartment Name="Methods" Collapsed="true" /> + </Compartments> + <InheritanceLine Type="DotNetOpenAuth.Messages.SignedMessageBase" ManuallyRouted="true" FixedFromPoint="true" FixedToPoint="true"> + <Path> + <Point X="4" Y="4.947" /> + <Point X="4.123" Y="4.947" /> + <Point X="4.123" Y="5.75" /> + <Point X="4.25" Y="5.75" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAACQAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAA=</HashCode> + <FileName>Messages\AuthorizedTokenRequest.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Class Name="DotNetOpenAuth.Messages.UnauthorizedTokenRequest"> + <Position X="4.25" Y="1" Width="3" /> + <Compartments> + <Compartment Name="Internal" Collapsed="true" /> + <Compartment Name="Private" Collapsed="true" /> + <Compartment Name="Methods" Collapsed="true" /> + </Compartments> + <InheritanceLine Type="DotNetOpenAuth.Messages.SignedMessageBase" FixedFromPoint="true"> + <Path> + <Point X="4" Y="1.855" /> + <Point X="4.25" Y="1.855" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAA=</HashCode> + <FileName>Messages\UnauthorizedTokenRequest.cs</FileName> + </TypeIdentifier> + </Class> + <Class Name="DotNetOpenAuth.Messages.SignedMessageBase"> + <Position X="0.5" Y="1.5" Width="3.5" /> + <Members> + <Property Name="ITamperResistantOAuthMessage.ConsumerSecret" Hidden="true" /> + <Property Name="ITamperResistantOAuthMessage.HttpMethod" Hidden="true" /> + <Property Name="ITamperResistantOAuthMessage.SignatureMethod" Hidden="true" /> + <Property Name="ITamperResistantOAuthMessage.TokenSecret" Hidden="true" /> + <Property Name="ITamperResistantProtocolMessage.Signature" Hidden="true" /> + </Members> + <InheritanceLine Type="DotNetOpenAuth.Messages.MessageBase" FixedFromPoint="true" FixedToPoint="true"> + <Path> + <Point X="12.875" Y="1" /> + <Point X="12.875" Y="0.625" /> + <Point X="3" Y="0.625" /> + <Point X="3" Y="1.5" /> + </Path> + </InheritanceLine> + <TypeIdentifier> + <HashCode>IIAAFAAAAIAAAAAAgICAAgAAAgAAIAQAAAEAIAAQAAE=</HashCode> + <FileName>Messages\SignedMessageBase.cs</FileName> + </TypeIdentifier> + <Lollipop Position="0.2" /> + </Class> + <Interface Name="DotNetOpenAuth.ChannelElements.ITamperResistantOAuthMessage"> + <Position X="11.25" Y="5.25" Width="2.5" /> + <TypeIdentifier> + <HashCode>AIAAAAAAAAAAAAAAAIAAAgAAAAAAIAQAAAAAAAAAAAA=</HashCode> + <FileName>ChannelElements\ITamperResistantOAuthMessage.cs</FileName> + </TypeIdentifier> + </Interface> + <Interface Name="DotNetOpenAuth.Messages.ITokenSecretContainingMessage"> + <Position X="1" Y="7.5" Width="2" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAA=</HashCode> + <FileName>Messages\ITokenSecretContainingMessage.cs</FileName> + <NewMemberFileName>Messages\ITokenContainingMessage.cs</NewMemberFileName> + </TypeIdentifier> + </Interface> + <Interface Name="DotNetOpenAuth.Messages.ITokenContainingMessage"> + <Position X="1" Y="6" Width="2" /> + <TypeIdentifier> + <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAA=</HashCode> + <FileName>Messages\ITokenContainingMessage.cs</FileName> + </TypeIdentifier> + </Interface> + <Font Name="Segoe UI" Size="9" /> </ClassDiagram>
\ No newline at end of file diff --git a/src/DotNetOAuth/OAuth/Messages/SignedMessageBase.cs b/src/DotNetOpenAuth/OAuth/Messages/SignedMessageBase.cs index 5d94013..c00e403 100644 --- a/src/DotNetOAuth/OAuth/Messages/SignedMessageBase.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/SignedMessageBase.cs @@ -1,161 +1,161 @@ -//-----------------------------------------------------------------------
-// <copyright file="SignedMessageBase.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System;
- using System.Diagnostics.CodeAnalysis;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.OAuth.ChannelElements;
-
- /// <summary>
- /// A base class for all signed OAuth messages.
- /// </summary>
- public class SignedMessageBase : MessageBase, ITamperResistantOAuthMessage, IExpiringProtocolMessage, IReplayProtectedProtocolMessage {
- /// <summary>
- /// The reference date and time for calculating time stamps.
- /// </summary>
- private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
-
- /// <summary>
- /// The number of seconds since 1/1/1970, consistent with the OAuth timestamp requirement.
- /// </summary>
- [MessagePart("oauth_timestamp", IsRequired = true)]
- private long timestamp;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="SignedMessageBase"/> class.
- /// </summary>
- /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param>
- /// <param name="recipient">The URI that a directed message will be delivered to.</param>
- internal SignedMessageBase(MessageTransport transport, MessageReceivingEndpoint recipient)
- : base(MessageProtections.All, transport, recipient) {
- ITamperResistantOAuthMessage self = (ITamperResistantOAuthMessage)this;
- HttpDeliveryMethods methods = ((IOAuthDirectedMessage)this).HttpMethods;
- self.HttpMethod = (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET";
- }
-
- #region ITamperResistantOAuthMessage Members
-
- /// <summary>
- /// Gets or sets the signature method used to sign the request.
- /// </summary>
- string ITamperResistantOAuthMessage.SignatureMethod {
- get { return this.SignatureMethod; }
- set { this.SignatureMethod = value; }
- }
-
- /// <summary>
- /// Gets or sets the Token Secret used to sign the message.
- /// </summary>
- string ITamperResistantOAuthMessage.TokenSecret {
- get { return this.TokenSecret; }
- set { this.TokenSecret = value; }
- }
-
- /// <summary>
- /// Gets or sets the Consumer key.
- /// </summary>
- [MessagePart("oauth_consumer_key", IsRequired = true)]
- public string ConsumerKey { get; set; }
-
- /// <summary>
- /// Gets or sets the Consumer Secret used to sign the message.
- /// </summary>
- string ITamperResistantOAuthMessage.ConsumerSecret {
- get { return this.ConsumerSecret; }
- set { this.ConsumerSecret = value; }
- }
-
- /// <summary>
- /// Gets or sets the HTTP method that will be used to transmit the message.
- /// </summary>
- string ITamperResistantOAuthMessage.HttpMethod {
- get { return this.HttpMethod; }
- set { this.HttpMethod = value; }
- }
-
- #endregion
-
- #region ITamperResistantProtocolMessage Members
-
- /// <summary>
- /// Gets or sets the message signature.
- /// </summary>
- string ITamperResistantProtocolMessage.Signature {
- get { return this.Signature; }
- set { this.Signature = value; }
- }
-
- #endregion
-
- #region IExpiringProtocolMessage Members
-
- /// <summary>
- /// Gets or sets the OAuth timestamp of the message.
- /// </summary>
- DateTime IExpiringProtocolMessage.UtcCreationDate {
- get { return epoch + TimeSpan.FromSeconds(this.timestamp); }
- set { this.timestamp = (long)(value - epoch).TotalSeconds; }
- }
-
- #endregion
-
- #region IReplayProtectedProtocolMessage Members
-
- /// <summary>
- /// Gets or sets the message nonce used for replay detection.
- /// </summary>
- [MessagePart("oauth_nonce", IsRequired = true)]
- string IReplayProtectedProtocolMessage.Nonce { get; set; }
-
- #endregion
-
- /// <summary>
- /// Gets or sets the signature method used to sign the request.
- /// </summary>
- [MessagePart("oauth_signature_method", IsRequired = true)]
- protected string SignatureMethod { get; set; }
-
- /// <summary>
- /// Gets or sets the Token Secret used to sign the message.
- /// </summary>
- protected string TokenSecret { get; set; }
-
- /// <summary>
- /// Gets or sets the Consumer Secret used to sign the message.
- /// </summary>
- protected string ConsumerSecret { get; set; }
-
- /// <summary>
- /// Gets or sets the HTTP method that will be used to transmit the message.
- /// </summary>
- protected string HttpMethod { get; set; }
-
- /// <summary>
- /// Gets or sets the message signature.
- /// </summary>
- [MessagePart("oauth_signature", IsRequired = true)]
- protected string Signature { get; set; }
-
- /// <summary>
- /// Gets or sets the version of the protocol this message was created with.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Accessed via reflection.")]
- [MessagePart("oauth_version", IsRequired = false)]
- private string Version {
- get {
- return ProtocolVersion.ToString();
- }
-
- set {
- if (value != this.Version) {
- throw new ArgumentOutOfRangeException("value");
- }
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="SignedMessageBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System; + using System.Diagnostics.CodeAnalysis; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth.ChannelElements; + + /// <summary> + /// A base class for all signed OAuth messages. + /// </summary> + public class SignedMessageBase : MessageBase, ITamperResistantOAuthMessage, IExpiringProtocolMessage, IReplayProtectedProtocolMessage { + /// <summary> + /// The reference date and time for calculating time stamps. + /// </summary> + private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + /// <summary> + /// The number of seconds since 1/1/1970, consistent with the OAuth timestamp requirement. + /// </summary> + [MessagePart("oauth_timestamp", IsRequired = true)] + private long timestamp; + + /// <summary> + /// Initializes a new instance of the <see cref="SignedMessageBase"/> class. + /// </summary> + /// <param name="transport">A value indicating whether this message requires a direct or indirect transport.</param> + /// <param name="recipient">The URI that a directed message will be delivered to.</param> + internal SignedMessageBase(MessageTransport transport, MessageReceivingEndpoint recipient) + : base(MessageProtections.All, transport, recipient) { + ITamperResistantOAuthMessage self = (ITamperResistantOAuthMessage)this; + HttpDeliveryMethods methods = ((IOAuthDirectedMessage)this).HttpMethods; + self.HttpMethod = (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET"; + } + + #region ITamperResistantOAuthMessage Members + + /// <summary> + /// Gets or sets the signature method used to sign the request. + /// </summary> + string ITamperResistantOAuthMessage.SignatureMethod { + get { return this.SignatureMethod; } + set { this.SignatureMethod = value; } + } + + /// <summary> + /// Gets or sets the Token Secret used to sign the message. + /// </summary> + string ITamperResistantOAuthMessage.TokenSecret { + get { return this.TokenSecret; } + set { this.TokenSecret = value; } + } + + /// <summary> + /// Gets or sets the Consumer key. + /// </summary> + [MessagePart("oauth_consumer_key", IsRequired = true)] + public string ConsumerKey { get; set; } + + /// <summary> + /// Gets or sets the Consumer Secret used to sign the message. + /// </summary> + string ITamperResistantOAuthMessage.ConsumerSecret { + get { return this.ConsumerSecret; } + set { this.ConsumerSecret = value; } + } + + /// <summary> + /// Gets or sets the HTTP method that will be used to transmit the message. + /// </summary> + string ITamperResistantOAuthMessage.HttpMethod { + get { return this.HttpMethod; } + set { this.HttpMethod = value; } + } + + #endregion + + #region ITamperResistantProtocolMessage Members + + /// <summary> + /// Gets or sets the message signature. + /// </summary> + string ITamperResistantProtocolMessage.Signature { + get { return this.Signature; } + set { this.Signature = value; } + } + + #endregion + + #region IExpiringProtocolMessage Members + + /// <summary> + /// Gets or sets the OAuth timestamp of the message. + /// </summary> + DateTime IExpiringProtocolMessage.UtcCreationDate { + get { return epoch + TimeSpan.FromSeconds(this.timestamp); } + set { this.timestamp = (long)(value - epoch).TotalSeconds; } + } + + #endregion + + #region IReplayProtectedProtocolMessage Members + + /// <summary> + /// Gets or sets the message nonce used for replay detection. + /// </summary> + [MessagePart("oauth_nonce", IsRequired = true)] + string IReplayProtectedProtocolMessage.Nonce { get; set; } + + #endregion + + /// <summary> + /// Gets or sets the signature method used to sign the request. + /// </summary> + [MessagePart("oauth_signature_method", IsRequired = true)] + protected string SignatureMethod { get; set; } + + /// <summary> + /// Gets or sets the Token Secret used to sign the message. + /// </summary> + protected string TokenSecret { get; set; } + + /// <summary> + /// Gets or sets the Consumer Secret used to sign the message. + /// </summary> + protected string ConsumerSecret { get; set; } + + /// <summary> + /// Gets or sets the HTTP method that will be used to transmit the message. + /// </summary> + protected string HttpMethod { get; set; } + + /// <summary> + /// Gets or sets the message signature. + /// </summary> + [MessagePart("oauth_signature", IsRequired = true)] + protected string Signature { get; set; } + + /// <summary> + /// Gets or sets the version of the protocol this message was created with. + /// </summary> + [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Accessed via reflection.")] + [MessagePart("oauth_version", IsRequired = false)] + private string Version { + get { + return ProtocolVersion.ToString(); + } + + set { + if (value != this.Version) { + throw new ArgumentOutOfRangeException("value"); + } + } + } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/UnauthorizedTokenRequest.cs b/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenRequest.cs index 7d83135..e491bad 100644 --- a/src/DotNetOAuth/OAuth/Messages/UnauthorizedTokenRequest.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenRequest.cs @@ -1,30 +1,30 @@ -//-----------------------------------------------------------------------
-// <copyright file="UnauthorizedTokenRequest.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System.Collections.Generic;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A direct message sent from Consumer to Service Provider to request a Request Token.
- /// </summary>
- public class UnauthorizedTokenRequest : SignedMessageBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="UnauthorizedTokenRequest"/> class.
- /// </summary>
- /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param>
- protected internal UnauthorizedTokenRequest(MessageReceivingEndpoint serviceProvider)
- : base(MessageTransport.Direct, serviceProvider) {
- }
-
- /// <summary>
- /// Gets the extra, non-OAuth parameters that will be included in the message.
- /// </summary>
- public new IDictionary<string, string> ExtraData {
- get { return base.ExtraData; }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="UnauthorizedTokenRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System.Collections.Generic; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A direct message sent from Consumer to Service Provider to request a Request Token. + /// </summary> + public class UnauthorizedTokenRequest : SignedMessageBase { + /// <summary> + /// Initializes a new instance of the <see cref="UnauthorizedTokenRequest"/> class. + /// </summary> + /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param> + protected internal UnauthorizedTokenRequest(MessageReceivingEndpoint serviceProvider) + : base(MessageTransport.Direct, serviceProvider) { + } + + /// <summary> + /// Gets the extra, non-OAuth parameters that will be included in the message. + /// </summary> + public new IDictionary<string, string> ExtraData { + get { return base.ExtraData; } + } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/UnauthorizedTokenResponse.cs b/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenResponse.cs index f527943..39f8fd0 100644 --- a/src/DotNetOAuth/OAuth/Messages/UnauthorizedTokenResponse.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/UnauthorizedTokenResponse.cs @@ -1,92 +1,92 @@ -//-----------------------------------------------------------------------
-// <copyright file="UnauthorizedTokenResponse.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A direct message sent from Service Provider to Consumer in response to
- /// a Consumer's <see cref="UnauthorizedTokenRequest"/> request.
- /// </summary>
- public class UnauthorizedTokenResponse : MessageBase, ITokenSecretContainingMessage {
- /// <summary>
- /// Initializes a new instance of the <see cref="UnauthorizedTokenResponse"/> class.
- /// </summary>
- /// <param name="requestMessage">The unauthorized request token message that this message is being generated in response to.</param>
- /// <param name="requestToken">The request token.</param>
- /// <param name="tokenSecret">The token secret.</param>
- /// <remarks>
- /// This constructor is used by the Service Provider to send the message.
- /// </remarks>
- protected internal UnauthorizedTokenResponse(UnauthorizedTokenRequest requestMessage, string requestToken, string tokenSecret) : this() {
- if (requestMessage == null) {
- throw new ArgumentNullException("requestMessage");
- }
- if (string.IsNullOrEmpty(requestToken)) {
- throw new ArgumentNullException("requestToken");
- }
- if (string.IsNullOrEmpty(tokenSecret)) {
- throw new ArgumentNullException("tokenSecret");
- }
-
- this.RequestMessage = requestMessage;
- this.RequestToken = requestToken;
- this.TokenSecret = tokenSecret;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="UnauthorizedTokenResponse"/> class.
- /// </summary>
- /// <remarks>This constructor is used by the consumer to deserialize the message.</remarks>
- protected internal UnauthorizedTokenResponse()
- : base(MessageProtections.None, MessageTransport.Direct) {
- }
-
- /// <summary>
- /// Gets or sets the Request or Access Token.
- /// </summary>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")]
- string ITokenContainingMessage.Token {
- get { return this.RequestToken; }
- set { this.RequestToken = value; }
- }
-
- /// <summary>
- /// Gets or sets the Request or Access Token secret.
- /// </summary>
- string ITokenSecretContainingMessage.TokenSecret {
- get { return this.TokenSecret; }
- set { this.TokenSecret = value; }
- }
-
- /// <summary>
- /// Gets the extra, non-OAuth parameters that will be included in the message.
- /// </summary>
- public new IDictionary<string, string> ExtraData {
- get { return base.ExtraData; }
- }
-
- /// <summary>
- /// Gets or sets the Request Token.
- /// </summary>
- [MessagePart("oauth_token", IsRequired = true)]
- internal string RequestToken { get; set; }
-
- /// <summary>
- /// Gets the original request for an unauthorized token.
- /// </summary>
- internal UnauthorizedTokenRequest RequestMessage { get; private set; }
-
- /// <summary>
- /// Gets or sets the Token Secret.
- /// </summary>
- [MessagePart("oauth_token_secret", IsRequired = true)]
- protected internal string TokenSecret { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="UnauthorizedTokenResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A direct message sent from Service Provider to Consumer in response to + /// a Consumer's <see cref="UnauthorizedTokenRequest"/> request. + /// </summary> + public class UnauthorizedTokenResponse : MessageBase, ITokenSecretContainingMessage { + /// <summary> + /// Initializes a new instance of the <see cref="UnauthorizedTokenResponse"/> class. + /// </summary> + /// <param name="requestMessage">The unauthorized request token message that this message is being generated in response to.</param> + /// <param name="requestToken">The request token.</param> + /// <param name="tokenSecret">The token secret.</param> + /// <remarks> + /// This constructor is used by the Service Provider to send the message. + /// </remarks> + protected internal UnauthorizedTokenResponse(UnauthorizedTokenRequest requestMessage, string requestToken, string tokenSecret) : this() { + if (requestMessage == null) { + throw new ArgumentNullException("requestMessage"); + } + if (string.IsNullOrEmpty(requestToken)) { + throw new ArgumentNullException("requestToken"); + } + if (string.IsNullOrEmpty(tokenSecret)) { + throw new ArgumentNullException("tokenSecret"); + } + + this.RequestMessage = requestMessage; + this.RequestToken = requestToken; + this.TokenSecret = tokenSecret; + } + + /// <summary> + /// Initializes a new instance of the <see cref="UnauthorizedTokenResponse"/> class. + /// </summary> + /// <remarks>This constructor is used by the consumer to deserialize the message.</remarks> + protected internal UnauthorizedTokenResponse() + : base(MessageProtections.None, MessageTransport.Direct) { + } + + /// <summary> + /// Gets or sets the Request or Access Token. + /// </summary> + [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")] + string ITokenContainingMessage.Token { + get { return this.RequestToken; } + set { this.RequestToken = value; } + } + + /// <summary> + /// Gets or sets the Request or Access Token secret. + /// </summary> + string ITokenSecretContainingMessage.TokenSecret { + get { return this.TokenSecret; } + set { this.TokenSecret = value; } + } + + /// <summary> + /// Gets the extra, non-OAuth parameters that will be included in the message. + /// </summary> + public new IDictionary<string, string> ExtraData { + get { return base.ExtraData; } + } + + /// <summary> + /// Gets or sets the Request Token. + /// </summary> + [MessagePart("oauth_token", IsRequired = true)] + internal string RequestToken { get; set; } + + /// <summary> + /// Gets the original request for an unauthorized token. + /// </summary> + internal UnauthorizedTokenRequest RequestMessage { get; private set; } + + /// <summary> + /// Gets or sets the Token Secret. + /// </summary> + [MessagePart("oauth_token_secret", IsRequired = true)] + protected internal string TokenSecret { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/UserAuthorizationRequest.cs b/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationRequest.cs index 79dd966..f1af0bc 100644 --- a/src/DotNetOAuth/OAuth/Messages/UserAuthorizationRequest.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationRequest.cs @@ -1,71 +1,71 @@ -//-----------------------------------------------------------------------
-// <copyright file="UserAuthorizationRequest.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A message used to redirect the user from a Consumer to a Service Provider's web site
- /// so the Service Provider can ask the user to authorize the Consumer's access to some
- /// protected resource(s).
- /// </summary>
- public class UserAuthorizationRequest : MessageBase, ITokenContainingMessage {
- /// <summary>
- /// Initializes a new instance of the <see cref="UserAuthorizationRequest"/> class.
- /// </summary>
- /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param>
- /// <param name="requestToken">The request token.</param>
- internal UserAuthorizationRequest(MessageReceivingEndpoint serviceProvider, string requestToken)
- : this(serviceProvider) {
- this.RequestToken = requestToken;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="UserAuthorizationRequest"/> class.
- /// </summary>
- /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param>
- internal UserAuthorizationRequest(MessageReceivingEndpoint serviceProvider)
- : base(MessageProtections.None, MessageTransport.Indirect, serviceProvider) {
- }
-
- /// <summary>
- /// Gets or sets the Request or Access Token.
- /// </summary>
- [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")]
- string ITokenContainingMessage.Token {
- get { return this.RequestToken; }
- set { this.RequestToken = value; }
- }
-
- /// <summary>
- /// Gets the extra, non-OAuth parameters that will be included in the message.
- /// </summary>
- public new IDictionary<string, string> ExtraData {
- get { return base.ExtraData; }
- }
-
- /// <summary>
- /// Gets or sets the Request Token obtained in the previous step.
- /// </summary>
- /// <remarks>
- /// The Service Provider MAY declare this parameter as REQUIRED, or
- /// accept requests to the User Authorization URL without it, in which
- /// case it will prompt the User to enter it manually.
- /// </remarks>
- [MessagePart("oauth_token", IsRequired = false)]
- internal string RequestToken { get; set; }
-
- /// <summary>
- /// Gets or sets a URL the Service Provider will use to redirect the User back
- /// to the Consumer when Obtaining User Authorization is complete. Optional.
- /// </summary>
- [MessagePart("oauth_callback", IsRequired = false)]
- internal Uri Callback { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="UserAuthorizationRequest.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A message used to redirect the user from a Consumer to a Service Provider's web site + /// so the Service Provider can ask the user to authorize the Consumer's access to some + /// protected resource(s). + /// </summary> + public class UserAuthorizationRequest : MessageBase, ITokenContainingMessage { + /// <summary> + /// Initializes a new instance of the <see cref="UserAuthorizationRequest"/> class. + /// </summary> + /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param> + /// <param name="requestToken">The request token.</param> + internal UserAuthorizationRequest(MessageReceivingEndpoint serviceProvider, string requestToken) + : this(serviceProvider) { + this.RequestToken = requestToken; + } + + /// <summary> + /// Initializes a new instance of the <see cref="UserAuthorizationRequest"/> class. + /// </summary> + /// <param name="serviceProvider">The URI of the Service Provider endpoint to send this message to.</param> + internal UserAuthorizationRequest(MessageReceivingEndpoint serviceProvider) + : base(MessageProtections.None, MessageTransport.Indirect, serviceProvider) { + } + + /// <summary> + /// Gets or sets the Request or Access Token. + /// </summary> + [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "This property IS accessible by a different name.")] + string ITokenContainingMessage.Token { + get { return this.RequestToken; } + set { this.RequestToken = value; } + } + + /// <summary> + /// Gets the extra, non-OAuth parameters that will be included in the message. + /// </summary> + public new IDictionary<string, string> ExtraData { + get { return base.ExtraData; } + } + + /// <summary> + /// Gets or sets the Request Token obtained in the previous step. + /// </summary> + /// <remarks> + /// The Service Provider MAY declare this parameter as REQUIRED, or + /// accept requests to the User Authorization URL without it, in which + /// case it will prompt the User to enter it manually. + /// </remarks> + [MessagePart("oauth_token", IsRequired = false)] + internal string RequestToken { get; set; } + + /// <summary> + /// Gets or sets a URL the Service Provider will use to redirect the User back + /// to the Consumer when Obtaining User Authorization is complete. Optional. + /// </summary> + [MessagePart("oauth_callback", IsRequired = false)] + internal Uri Callback { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/Messages/UserAuthorizationResponse.cs b/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationResponse.cs index ab66dfe..da6a909 100644 --- a/src/DotNetOAuth/OAuth/Messages/UserAuthorizationResponse.cs +++ b/src/DotNetOpenAuth/OAuth/Messages/UserAuthorizationResponse.cs @@ -1,40 +1,40 @@ -//-----------------------------------------------------------------------
-// <copyright file="UserAuthorizationResponse.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth.Messages {
- using System;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// A message used to redirect the user from a Service Provider to a Consumer's web site.
- /// </summary>
- /// <remarks>
- /// The class is sealed because extra parameters are determined by the callback URI provided by the Consumer.
- /// </remarks>
- public sealed class UserAuthorizationResponse : MessageBase, ITokenContainingMessage {
- /// <summary>
- /// Initializes a new instance of the <see cref="UserAuthorizationResponse"/> class.
- /// </summary>
- /// <param name="consumer">The URI of the Consumer endpoint to send this message to.</param>
- internal UserAuthorizationResponse(Uri consumer)
- : base(MessageProtections.None, MessageTransport.Indirect, new MessageReceivingEndpoint(consumer, HttpDeliveryMethods.GetRequest)) {
- }
-
- /// <summary>
- /// Gets or sets the Request or Access Token.
- /// </summary>
- string ITokenContainingMessage.Token {
- get { return this.RequestToken; }
- set { this.RequestToken = value; }
- }
-
- /// <summary>
- /// Gets or sets the Request Token.
- /// </summary>
- [MessagePart("oauth_token", IsRequired = true)]
- internal string RequestToken { get; set; }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="UserAuthorizationResponse.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth.Messages { + using System; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A message used to redirect the user from a Service Provider to a Consumer's web site. + /// </summary> + /// <remarks> + /// The class is sealed because extra parameters are determined by the callback URI provided by the Consumer. + /// </remarks> + public sealed class UserAuthorizationResponse : MessageBase, ITokenContainingMessage { + /// <summary> + /// Initializes a new instance of the <see cref="UserAuthorizationResponse"/> class. + /// </summary> + /// <param name="consumer">The URI of the Consumer endpoint to send this message to.</param> + internal UserAuthorizationResponse(Uri consumer) + : base(MessageProtections.None, MessageTransport.Indirect, new MessageReceivingEndpoint(consumer, HttpDeliveryMethods.GetRequest)) { + } + + /// <summary> + /// Gets or sets the Request or Access Token. + /// </summary> + string ITokenContainingMessage.Token { + get { return this.RequestToken; } + set { this.RequestToken = value; } + } + + /// <summary> + /// Gets or sets the Request Token. + /// </summary> + [MessagePart("oauth_token", IsRequired = true)] + internal string RequestToken { get; set; } + } +} diff --git a/src/DotNetOAuth/OAuth/Protocol.cs b/src/DotNetOpenAuth/OAuth/Protocol.cs index c738fc2..88615ff 100644 --- a/src/DotNetOAuth/OAuth/Protocol.cs +++ b/src/DotNetOpenAuth/OAuth/Protocol.cs @@ -1,87 +1,87 @@ -//-----------------------------------------------------------------------
-// <copyright file="Protocol.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOAuth.Messaging;
-
- /// <summary>
- /// Constants used in the OAuth protocol.
- /// </summary>
- /// <remarks>
- /// OAuth Protocol Parameter names and values are case sensitive. Each OAuth Protocol Parameters MUST NOT appear more than once per request, and are REQUIRED unless otherwise noted,
- /// per OAuth 1.0 section 5.
- /// </remarks>
- internal class Protocol {
- /// <summary>
- /// The namespace to use for V1.0 of the protocol.
- /// </summary>
- internal const string DataContractNamespaceV10 = "http://oauth.net/core/1.0/";
-
- /// <summary>
- /// Gets the <see cref="Protocol"/> instance with values initialized for V1.0 of the protocol.
- /// </summary>
- internal static readonly Protocol V10 = new Protocol {
- dataContractNamespace = DataContractNamespaceV10,
- };
-
- /// <summary>
- /// The namespace to use for this version of the protocol.
- /// </summary>
- private string dataContractNamespace;
-
- /// <summary>
- /// The prefix used for all key names in the protocol.
- /// </summary>
- private string parameterPrefix = "oauth_";
-
- /// <summary>
- /// The scheme to use in Authorization header message requests.
- /// </summary>
- private string authorizationHeaderScheme = "OAuth";
-
- /// <summary>
- /// Gets the default <see cref="Protocol"/> instance.
- /// </summary>
- internal static Protocol Default { get { return V10; } }
-
- /// <summary>
- /// Gets the namespace to use for this version of the protocol.
- /// </summary>
- internal string DataContractNamespace {
- get { return this.dataContractNamespace; }
- }
-
- /// <summary>
- /// Gets the prefix used for all key names in the protocol.
- /// </summary>
- internal string ParameterPrefix {
- get { return this.parameterPrefix; }
- }
-
- /// <summary>
- /// Gets the scheme to use in Authorization header message requests.
- /// </summary>
- internal string AuthorizationHeaderScheme {
- get { return this.authorizationHeaderScheme; }
- }
-
- /// <summary>
- /// Gets an instance of <see cref="Protocol"/> given a <see cref="Version"/>.
- /// </summary>
- /// <param name="version">The version of the protocol that is desired.</param>
- /// <returns>The <see cref="Protocol"/> instance representing the requested version.</returns>
- internal static Protocol Lookup(Version version) {
- switch (version.Major) {
- case 1: return Protocol.V10;
- default: throw new ArgumentOutOfRangeException("version");
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="Protocol.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// Constants used in the OAuth protocol. + /// </summary> + /// <remarks> + /// OAuth Protocol Parameter names and values are case sensitive. Each OAuth Protocol Parameters MUST NOT appear more than once per request, and are REQUIRED unless otherwise noted, + /// per OAuth 1.0 section 5. + /// </remarks> + internal class Protocol { + /// <summary> + /// The namespace to use for V1.0 of the protocol. + /// </summary> + internal const string DataContractNamespaceV10 = "http://oauth.net/core/1.0/"; + + /// <summary> + /// Gets the <see cref="Protocol"/> instance with values initialized for V1.0 of the protocol. + /// </summary> + internal static readonly Protocol V10 = new Protocol { + dataContractNamespace = DataContractNamespaceV10, + }; + + /// <summary> + /// The namespace to use for this version of the protocol. + /// </summary> + private string dataContractNamespace; + + /// <summary> + /// The prefix used for all key names in the protocol. + /// </summary> + private string parameterPrefix = "oauth_"; + + /// <summary> + /// The scheme to use in Authorization header message requests. + /// </summary> + private string authorizationHeaderScheme = "OAuth"; + + /// <summary> + /// Gets the default <see cref="Protocol"/> instance. + /// </summary> + internal static Protocol Default { get { return V10; } } + + /// <summary> + /// Gets the namespace to use for this version of the protocol. + /// </summary> + internal string DataContractNamespace { + get { return this.dataContractNamespace; } + } + + /// <summary> + /// Gets the prefix used for all key names in the protocol. + /// </summary> + internal string ParameterPrefix { + get { return this.parameterPrefix; } + } + + /// <summary> + /// Gets the scheme to use in Authorization header message requests. + /// </summary> + internal string AuthorizationHeaderScheme { + get { return this.authorizationHeaderScheme; } + } + + /// <summary> + /// Gets an instance of <see cref="Protocol"/> given a <see cref="Version"/>. + /// </summary> + /// <param name="version">The version of the protocol that is desired.</param> + /// <returns>The <see cref="Protocol"/> instance representing the requested version.</returns> + internal static Protocol Lookup(Version version) { + switch (version.Major) { + case 1: return Protocol.V10; + default: throw new ArgumentOutOfRangeException("version"); + } + } + } +} diff --git a/src/DotNetOAuth/OAuth/ServiceProvider.cs b/src/DotNetOpenAuth/OAuth/ServiceProvider.cs index 2dc1609..0bd7fe8 100644 --- a/src/DotNetOAuth/OAuth/ServiceProvider.cs +++ b/src/DotNetOpenAuth/OAuth/ServiceProvider.cs @@ -1,396 +1,396 @@ -//-----------------------------------------------------------------------
-// <copyright file="ServiceProvider.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth {
- using System;
- using System.Globalization;
- using System.ServiceModel.Channels;
- using System.Web;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.Messaging.Bindings;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// A web application that allows access via OAuth.
- /// </summary>
- /// <remarks>
- /// <para>The Service Provider’s documentation should include:</para>
- /// <list>
- /// <item>The URLs (Request URLs) the Consumer will use when making OAuth requests, and the HTTP methods (i.e. GET, POST, etc.) used in the Request Token URL and Access Token URL.</item>
- /// <item>Signature methods supported by the Service Provider.</item>
- /// <item>Any additional request parameters that the Service Provider requires in order to obtain a Token. Service Provider specific parameters MUST NOT begin with oauth_.</item>
- /// </list>
- /// </remarks>
- public class ServiceProvider {
- /// <summary>
- /// The field behind the <see cref="OAuthChannel"/> property.
- /// </summary>
- private OAuthChannel channel;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ServiceProvider"/> class.
- /// </summary>
- /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param>
- /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param>
- public ServiceProvider(ServiceProviderDescription serviceDescription, ITokenManager tokenManager)
- : this(serviceDescription, tokenManager, new OAuthServiceProviderMessageTypeProvider(tokenManager)) {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ServiceProvider"/> class.
- /// </summary>
- /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param>
- /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param>
- /// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param>
- public ServiceProvider(ServiceProviderDescription serviceDescription, ITokenManager tokenManager, OAuthServiceProviderMessageTypeProvider messageTypeProvider) {
- if (serviceDescription == null) {
- throw new ArgumentNullException("serviceDescription");
- }
- if (tokenManager == null) {
- throw new ArgumentNullException("tokenManager");
- }
- if (messageTypeProvider == null) {
- throw new ArgumentNullException("messageTypeProvider");
- }
-
- var signingElement = serviceDescription.CreateTamperProtectionElement();
- INonceStore store = new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge);
- this.ServiceDescription = serviceDescription;
- this.OAuthChannel = new OAuthChannel(signingElement, store, tokenManager, messageTypeProvider, new StandardWebRequestHandler());
- this.TokenGenerator = new StandardTokenGenerator();
- }
-
- /// <summary>
- /// Gets the description of this Service Provider.
- /// </summary>
- public ServiceProviderDescription ServiceDescription { get; private set; }
-
- /// <summary>
- /// Gets or sets the generator responsible for generating new tokens and secrets.
- /// </summary>
- public ITokenGenerator TokenGenerator { get; set; }
-
- /// <summary>
- /// Gets the persistence store for tokens and secrets.
- /// </summary>
- public ITokenManager TokenManager {
- get { return this.OAuthChannel.TokenManager; }
- }
-
- /// <summary>
- /// Gets the channel to use for sending/receiving messages.
- /// </summary>
- public Channel Channel {
- get { return this.OAuthChannel; }
- }
-
- /// <summary>
- /// Gets or sets the channel to use for sending/receiving messages.
- /// </summary>
- internal OAuthChannel OAuthChannel {
- get {
- return this.channel;
- }
-
- set {
- if (this.channel != null) {
- this.channel.Sending -= this.OAuthChannel_Sending;
- }
-
- this.channel = value;
-
- if (this.channel != null) {
- this.channel.Sending += this.OAuthChannel_Sending;
- }
- }
- }
-
- /// <summary>
- /// Reads any incoming OAuth message.
- /// </summary>
- /// <returns>The deserialized message.</returns>
- /// <remarks>
- /// Requires HttpContext.Current.
- /// </remarks>
- public IOAuthDirectedMessage ReadRequest() {
- return (IOAuthDirectedMessage)this.Channel.ReadFromRequest();
- }
-
- /// <summary>
- /// Reads any incoming OAuth message.
- /// </summary>
- /// <param name="request">The HTTP request to read the message from.</param>
- /// <returns>The deserialized message.</returns>
- public IOAuthDirectedMessage ReadRequest(HttpRequest request) {
- return (IOAuthDirectedMessage)this.Channel.ReadFromRequest(new HttpRequestInfo(request));
- }
-
- /// <summary>
- /// Gets the incoming request for an unauthorized token, if any.
- /// </summary>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- /// <remarks>
- /// Requires HttpContext.Current.
- /// </remarks>
- public UnauthorizedTokenRequest ReadTokenRequest() {
- return this.ReadTokenRequest(this.Channel.GetRequestFromContext());
- }
-
- /// <summary>
- /// Gets the incoming request for an unauthorized token, if any.
- /// </summary>
- /// <param name="request">The incoming HTTP request.</param>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- public UnauthorizedTokenRequest ReadTokenRequest(HttpRequest request) {
- return this.ReadTokenRequest(new HttpRequestInfo(request));
- }
-
- /// <summary>
- /// Reads a request for an unauthorized token from the incoming HTTP request.
- /// </summary>
- /// <param name="request">The HTTP request to read from.</param>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- public UnauthorizedTokenRequest ReadTokenRequest(HttpRequestInfo request) {
- UnauthorizedTokenRequest message;
- this.Channel.TryReadFromRequest(request, out message);
- return message;
- }
-
- /// <summary>
- /// Prepares a message containing an unauthorized token for the Consumer to use in a
- /// user agent redirect for subsequent authorization.
- /// </summary>
- /// <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) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- string token = this.TokenGenerator.GenerateRequestToken(request.ConsumerKey);
- string secret = this.TokenGenerator.GenerateSecret();
- UnauthorizedTokenResponse response = new UnauthorizedTokenResponse(request, token, secret);
-
- return response;
- }
-
- /// <summary>
- /// Gets the incoming request for the Service Provider to authorize a Consumer's
- /// access to some protected resources.
- /// </summary>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- /// <remarks>
- /// Requires HttpContext.Current.
- /// </remarks>
- public UserAuthorizationRequest ReadAuthorizationRequest() {
- return this.ReadAuthorizationRequest(this.Channel.GetRequestFromContext());
- }
-
- /// <summary>
- /// Gets the incoming request for the Service Provider to authorize a Consumer's
- /// access to some protected resources.
- /// </summary>
- /// <param name="request">The incoming HTTP request.</param>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- public UserAuthorizationRequest ReadAuthorizationRequest(HttpRequest request) {
- return this.ReadAuthorizationRequest(new HttpRequestInfo(request));
- }
-
- /// <summary>
- /// Reads in a Consumer's request for the Service Provider to obtain permission from
- /// the user to authorize the Consumer's access of some protected resource(s).
- /// </summary>
- /// <param name="request">The HTTP request to read from.</param>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- public UserAuthorizationRequest ReadAuthorizationRequest(HttpRequestInfo request) {
- UserAuthorizationRequest message;
- this.Channel.TryReadFromRequest(request, out message);
- return message;
- }
-
- /// <summary>
- /// Prepares the message to send back to the consumer following proper authorization of
- /// a token by an interactive user at the Service Provider's web site.
- /// </summary>
- /// <param name="request">The Consumer's original authorization request.</param>
- /// <returns>
- /// The message to send to the Consumer using <see cref="Channel"/> if one is necessary.
- /// Null if the Consumer did not request a callback.
- /// </returns>
- public UserAuthorizationResponse PrepareAuthorizationResponse(UserAuthorizationRequest request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- if (request.Callback != null) {
- var authorization = new UserAuthorizationResponse(request.Callback) {
- RequestToken = request.RequestToken,
- };
- return authorization;
- } else {
- return null;
- }
- }
-
- /// <summary>
- /// Gets the incoming request to exchange an authorized token for an access token.
- /// </summary>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- /// <remarks>
- /// Requires HttpContext.Current.
- /// </remarks>
- public AuthorizedTokenRequest ReadAccessTokenRequest() {
- return this.ReadAccessTokenRequest(this.Channel.GetRequestFromContext());
- }
-
- /// <summary>
- /// Gets the incoming request to exchange an authorized token for an access token.
- /// </summary>
- /// <param name="request">The incoming HTTP request.</param>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- public AuthorizedTokenRequest ReadAccessTokenRequest(HttpRequest request) {
- return this.ReadAccessTokenRequest(new HttpRequestInfo(request));
- }
-
- /// <summary>
- /// Reads in a Consumer's request to exchange an authorized request token for an access token.
- /// </summary>
- /// <param name="request">The HTTP request to read from.</param>
- /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
- /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
- public AuthorizedTokenRequest ReadAccessTokenRequest(HttpRequestInfo request) {
- AuthorizedTokenRequest message;
- this.Channel.TryReadFromRequest(request, out message);
- return message;
- }
-
- /// <summary>
- /// Prepares and sends an access token to a Consumer, and invalidates the request token.
- /// </summary>
- /// <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) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- if (!this.TokenManager.IsRequestTokenAuthorized(request.RequestToken)) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- Strings.AccessTokenNotAuthorized,
- request.RequestToken));
- }
-
- string accessToken = this.TokenGenerator.GenerateAccessToken(request.ConsumerKey);
- string tokenSecret = this.TokenGenerator.GenerateSecret();
- this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(request.ConsumerKey, request.RequestToken, accessToken, tokenSecret);
- var grantAccess = new AuthorizedTokenResponse {
- AccessToken = accessToken,
- TokenSecret = tokenSecret,
- };
-
- return grantAccess;
- }
-
- /// <summary>
- /// Gets the authorization (access token) for accessing some protected resource.
- /// </summary>
- /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns>
- /// <remarks>
- /// This method verifies that the access token and token secret are valid.
- /// It falls on the caller to verify that the access token is actually authorized
- /// to access the resources being requested.
- /// </remarks>
- /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception>
- public AccessProtectedResourceRequest ReadProtectedResourceAuthorization() {
- return this.ReadProtectedResourceAuthorization(this.Channel.GetRequestFromContext());
- }
-
- /// <summary>
- /// Gets the authorization (access token) for accessing some protected resource.
- /// </summary>
- /// <param name="request">The incoming HTTP request.</param>
- /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns>
- /// <remarks>
- /// This method verifies that the access token and token secret are valid.
- /// It falls on the caller to verify that the access token is actually authorized
- /// to access the resources being requested.
- /// </remarks>
- /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception>
- public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequest request) {
- return this.ReadProtectedResourceAuthorization(new HttpRequestInfo(request));
- }
-
- /// <summary>
- /// Gets the authorization (access token) for accessing some protected resource.
- /// </summary>
- /// <param name="request">HTTP details from an incoming WCF message.</param>
- /// <param name="requestUri">The URI of the WCF service endpoint.</param>
- /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns>
- /// <remarks>
- /// This method verifies that the access token and token secret are valid.
- /// It falls on the caller to verify that the access token is actually authorized
- /// to access the resources being requested.
- /// </remarks>
- /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception>
- public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestMessageProperty request, Uri requestUri) {
- return this.ReadProtectedResourceAuthorization(new HttpRequestInfo(request, requestUri));
- }
-
- /// <summary>
- /// Gets the authorization (access token) for accessing some protected resource.
- /// </summary>
- /// <param name="request">The incoming HTTP request.</param>
- /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns>
- /// <remarks>
- /// This method verifies that the access token and token secret are valid.
- /// It falls on the caller to verify that the access token is actually authorized
- /// to access the resources being requested.
- /// </remarks>
- /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception>
- public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestInfo request) {
- if (request == null) {
- throw new ArgumentNullException("request");
- }
-
- AccessProtectedResourceRequest accessMessage;
- if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(request, out accessMessage)) {
- if (this.TokenManager.GetTokenType(accessMessage.AccessToken) != TokenType.AccessToken) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
- Strings.BadAccessTokenInProtectedResourceRequest,
- accessMessage.AccessToken));
- }
- }
-
- return accessMessage;
- }
-
- /// <summary>
- /// Hooks the channel in order to perform some operations on some outgoing messages.
- /// </summary>
- /// <param name="sender">The source of the event.</param>
- /// <param name="e">The <see cref="DotNetOAuth.Messaging.ChannelEventArgs"/> instance containing the event data.</param>
- private void OAuthChannel_Sending(object sender, ChannelEventArgs e) {
- // Hook to store the token and secret on its way down to the Consumer.
- var grantRequestTokenResponse = e.Message as UnauthorizedTokenResponse;
- if (grantRequestTokenResponse != null) {
- this.TokenManager.StoreNewRequestToken(grantRequestTokenResponse.RequestMessage, grantRequestTokenResponse);
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ServiceProvider.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Globalization; + using System.ServiceModel.Channels; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// A web application that allows access via OAuth. + /// </summary> + /// <remarks> + /// <para>The Service Provider’s documentation should include:</para> + /// <list> + /// <item>The URLs (Request URLs) the Consumer will use when making OAuth requests, and the HTTP methods (i.e. GET, POST, etc.) used in the Request Token URL and Access Token URL.</item> + /// <item>Signature methods supported by the Service Provider.</item> + /// <item>Any additional request parameters that the Service Provider requires in order to obtain a Token. Service Provider specific parameters MUST NOT begin with oauth_.</item> + /// </list> + /// </remarks> + public class ServiceProvider { + /// <summary> + /// The field behind the <see cref="OAuthChannel"/> property. + /// </summary> + private OAuthChannel channel; + + /// <summary> + /// Initializes a new instance of the <see cref="ServiceProvider"/> class. + /// </summary> + /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param> + /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> + public ServiceProvider(ServiceProviderDescription serviceDescription, ITokenManager tokenManager) + : this(serviceDescription, tokenManager, new OAuthServiceProviderMessageTypeProvider(tokenManager)) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ServiceProvider"/> class. + /// </summary> + /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param> + /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> + /// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param> + public ServiceProvider(ServiceProviderDescription serviceDescription, ITokenManager tokenManager, OAuthServiceProviderMessageTypeProvider messageTypeProvider) { + if (serviceDescription == null) { + throw new ArgumentNullException("serviceDescription"); + } + if (tokenManager == null) { + throw new ArgumentNullException("tokenManager"); + } + if (messageTypeProvider == null) { + throw new ArgumentNullException("messageTypeProvider"); + } + + var signingElement = serviceDescription.CreateTamperProtectionElement(); + INonceStore store = new NonceMemoryStore(StandardExpirationBindingElement.DefaultMaximumMessageAge); + this.ServiceDescription = serviceDescription; + this.OAuthChannel = new OAuthChannel(signingElement, store, tokenManager, messageTypeProvider, new StandardWebRequestHandler()); + this.TokenGenerator = new StandardTokenGenerator(); + } + + /// <summary> + /// Gets the description of this Service Provider. + /// </summary> + public ServiceProviderDescription ServiceDescription { get; private set; } + + /// <summary> + /// Gets or sets the generator responsible for generating new tokens and secrets. + /// </summary> + public ITokenGenerator TokenGenerator { get; set; } + + /// <summary> + /// Gets the persistence store for tokens and secrets. + /// </summary> + public ITokenManager TokenManager { + get { return this.OAuthChannel.TokenManager; } + } + + /// <summary> + /// Gets the channel to use for sending/receiving messages. + /// </summary> + public Channel Channel { + get { return this.OAuthChannel; } + } + + /// <summary> + /// Gets or sets the channel to use for sending/receiving messages. + /// </summary> + internal OAuthChannel OAuthChannel { + get { + return this.channel; + } + + set { + if (this.channel != null) { + this.channel.Sending -= this.OAuthChannel_Sending; + } + + this.channel = value; + + if (this.channel != null) { + this.channel.Sending += this.OAuthChannel_Sending; + } + } + } + + /// <summary> + /// Reads any incoming OAuth message. + /// </summary> + /// <returns>The deserialized message.</returns> + /// <remarks> + /// Requires HttpContext.Current. + /// </remarks> + public IOAuthDirectedMessage ReadRequest() { + return (IOAuthDirectedMessage)this.Channel.ReadFromRequest(); + } + + /// <summary> + /// Reads any incoming OAuth message. + /// </summary> + /// <param name="request">The HTTP request to read the message from.</param> + /// <returns>The deserialized message.</returns> + public IOAuthDirectedMessage ReadRequest(HttpRequest request) { + return (IOAuthDirectedMessage)this.Channel.ReadFromRequest(new HttpRequestInfo(request)); + } + + /// <summary> + /// Gets the incoming request for an unauthorized token, if any. + /// </summary> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + /// <remarks> + /// Requires HttpContext.Current. + /// </remarks> + public UnauthorizedTokenRequest ReadTokenRequest() { + return this.ReadTokenRequest(this.Channel.GetRequestFromContext()); + } + + /// <summary> + /// Gets the incoming request for an unauthorized token, if any. + /// </summary> + /// <param name="request">The incoming HTTP request.</param> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public UnauthorizedTokenRequest ReadTokenRequest(HttpRequest request) { + return this.ReadTokenRequest(new HttpRequestInfo(request)); + } + + /// <summary> + /// Reads a request for an unauthorized token from the incoming HTTP request. + /// </summary> + /// <param name="request">The HTTP request to read from.</param> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public UnauthorizedTokenRequest ReadTokenRequest(HttpRequestInfo request) { + UnauthorizedTokenRequest message; + this.Channel.TryReadFromRequest(request, out message); + return message; + } + + /// <summary> + /// Prepares a message containing an unauthorized token for the Consumer to use in a + /// user agent redirect for subsequent authorization. + /// </summary> + /// <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) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + string token = this.TokenGenerator.GenerateRequestToken(request.ConsumerKey); + string secret = this.TokenGenerator.GenerateSecret(); + UnauthorizedTokenResponse response = new UnauthorizedTokenResponse(request, token, secret); + + return response; + } + + /// <summary> + /// Gets the incoming request for the Service Provider to authorize a Consumer's + /// access to some protected resources. + /// </summary> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + /// <remarks> + /// Requires HttpContext.Current. + /// </remarks> + public UserAuthorizationRequest ReadAuthorizationRequest() { + return this.ReadAuthorizationRequest(this.Channel.GetRequestFromContext()); + } + + /// <summary> + /// Gets the incoming request for the Service Provider to authorize a Consumer's + /// access to some protected resources. + /// </summary> + /// <param name="request">The incoming HTTP request.</param> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public UserAuthorizationRequest ReadAuthorizationRequest(HttpRequest request) { + return this.ReadAuthorizationRequest(new HttpRequestInfo(request)); + } + + /// <summary> + /// Reads in a Consumer's request for the Service Provider to obtain permission from + /// the user to authorize the Consumer's access of some protected resource(s). + /// </summary> + /// <param name="request">The HTTP request to read from.</param> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public UserAuthorizationRequest ReadAuthorizationRequest(HttpRequestInfo request) { + UserAuthorizationRequest message; + this.Channel.TryReadFromRequest(request, out message); + return message; + } + + /// <summary> + /// Prepares the message to send back to the consumer following proper authorization of + /// a token by an interactive user at the Service Provider's web site. + /// </summary> + /// <param name="request">The Consumer's original authorization request.</param> + /// <returns> + /// The message to send to the Consumer using <see cref="Channel"/> if one is necessary. + /// Null if the Consumer did not request a callback. + /// </returns> + public UserAuthorizationResponse PrepareAuthorizationResponse(UserAuthorizationRequest request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + if (request.Callback != null) { + var authorization = new UserAuthorizationResponse(request.Callback) { + RequestToken = request.RequestToken, + }; + return authorization; + } else { + return null; + } + } + + /// <summary> + /// Gets the incoming request to exchange an authorized token for an access token. + /// </summary> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + /// <remarks> + /// Requires HttpContext.Current. + /// </remarks> + public AuthorizedTokenRequest ReadAccessTokenRequest() { + return this.ReadAccessTokenRequest(this.Channel.GetRequestFromContext()); + } + + /// <summary> + /// Gets the incoming request to exchange an authorized token for an access token. + /// </summary> + /// <param name="request">The incoming HTTP request.</param> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public AuthorizedTokenRequest ReadAccessTokenRequest(HttpRequest request) { + return this.ReadAccessTokenRequest(new HttpRequestInfo(request)); + } + + /// <summary> + /// Reads in a Consumer's request to exchange an authorized request token for an access token. + /// </summary> + /// <param name="request">The HTTP request to read from.</param> + /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public AuthorizedTokenRequest ReadAccessTokenRequest(HttpRequestInfo request) { + AuthorizedTokenRequest message; + this.Channel.TryReadFromRequest(request, out message); + return message; + } + + /// <summary> + /// Prepares and sends an access token to a Consumer, and invalidates the request token. + /// </summary> + /// <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) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + if (!this.TokenManager.IsRequestTokenAuthorized(request.RequestToken)) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + Strings.AccessTokenNotAuthorized, + request.RequestToken)); + } + + string accessToken = this.TokenGenerator.GenerateAccessToken(request.ConsumerKey); + string tokenSecret = this.TokenGenerator.GenerateSecret(); + this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(request.ConsumerKey, request.RequestToken, accessToken, tokenSecret); + var grantAccess = new AuthorizedTokenResponse { + AccessToken = accessToken, + TokenSecret = tokenSecret, + }; + + return grantAccess; + } + + /// <summary> + /// Gets the authorization (access token) for accessing some protected resource. + /// </summary> + /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns> + /// <remarks> + /// This method verifies that the access token and token secret are valid. + /// It falls on the caller to verify that the access token is actually authorized + /// to access the resources being requested. + /// </remarks> + /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> + public AccessProtectedResourceRequest ReadProtectedResourceAuthorization() { + return this.ReadProtectedResourceAuthorization(this.Channel.GetRequestFromContext()); + } + + /// <summary> + /// Gets the authorization (access token) for accessing some protected resource. + /// </summary> + /// <param name="request">The incoming HTTP request.</param> + /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns> + /// <remarks> + /// This method verifies that the access token and token secret are valid. + /// It falls on the caller to verify that the access token is actually authorized + /// to access the resources being requested. + /// </remarks> + /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> + public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequest request) { + return this.ReadProtectedResourceAuthorization(new HttpRequestInfo(request)); + } + + /// <summary> + /// Gets the authorization (access token) for accessing some protected resource. + /// </summary> + /// <param name="request">HTTP details from an incoming WCF message.</param> + /// <param name="requestUri">The URI of the WCF service endpoint.</param> + /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns> + /// <remarks> + /// This method verifies that the access token and token secret are valid. + /// It falls on the caller to verify that the access token is actually authorized + /// to access the resources being requested. + /// </remarks> + /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> + public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestMessageProperty request, Uri requestUri) { + return this.ReadProtectedResourceAuthorization(new HttpRequestInfo(request, requestUri)); + } + + /// <summary> + /// Gets the authorization (access token) for accessing some protected resource. + /// </summary> + /// <param name="request">The incoming HTTP request.</param> + /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns> + /// <remarks> + /// This method verifies that the access token and token secret are valid. + /// It falls on the caller to verify that the access token is actually authorized + /// to access the resources being requested. + /// </remarks> + /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> + public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestInfo request) { + if (request == null) { + throw new ArgumentNullException("request"); + } + + AccessProtectedResourceRequest accessMessage; + if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(request, out accessMessage)) { + if (this.TokenManager.GetTokenType(accessMessage.AccessToken) != TokenType.AccessToken) { + throw new ProtocolException( + string.Format( + CultureInfo.CurrentCulture, + Strings.BadAccessTokenInProtectedResourceRequest, + accessMessage.AccessToken)); + } + } + + return accessMessage; + } + + /// <summary> + /// Hooks the channel in order to perform some operations on some outgoing messages. + /// </summary> + /// <param name="sender">The source of the event.</param> + /// <param name="e">The <see cref="DotNetOpenAuth.Messaging.ChannelEventArgs"/> instance containing the event data.</param> + private void OAuthChannel_Sending(object sender, ChannelEventArgs e) { + // Hook to store the token and secret on its way down to the Consumer. + var grantRequestTokenResponse = e.Message as UnauthorizedTokenResponse; + if (grantRequestTokenResponse != null) { + this.TokenManager.StoreNewRequestToken(grantRequestTokenResponse.RequestMessage, grantRequestTokenResponse); + } + } + } +} diff --git a/src/DotNetOAuth/OAuth/ServiceProviderDescription.cs b/src/DotNetOpenAuth/OAuth/ServiceProviderDescription.cs index 7e7e2d0..f0ed8a0 100644 --- a/src/DotNetOAuth/OAuth/ServiceProviderDescription.cs +++ b/src/DotNetOpenAuth/OAuth/ServiceProviderDescription.cs @@ -1,87 +1,87 @@ -//-----------------------------------------------------------------------
-// <copyright file="ServiceProviderDescription.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth {
- using System;
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System.Linq;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.ChannelElements;
-
- /// <summary>
- /// A description of the endpoints on a Service Provider.
- /// </summary>
- public class ServiceProviderDescription {
- /// <summary>
- /// The field used to store the value of the <see cref="RequestTokenEndpoint"/> property.
- /// </summary>
- [DebuggerBrowsable(DebuggerBrowsableState.Never)]
- private MessageReceivingEndpoint requestTokenEndpoint;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ServiceProviderDescription"/> class.
- /// </summary>
- public ServiceProviderDescription() {
- }
-
- /// <summary>
- /// Gets or sets the URL used to obtain an unauthorized Request Token,
- /// described in Section 6.1 (Obtaining an Unauthorized Request Token).
- /// </summary>
- /// <remarks>
- /// The request URL query MUST NOT contain any OAuth Protocol Parameters.
- /// This is the URL that <see cref="OAuth.Messages.UnauthorizedTokenRequest"/> messages are directed to.
- /// </remarks>
- /// <exception cref="ArgumentException">Thrown if this property is set to a URI with OAuth protocol parameters.</exception>
- public MessageReceivingEndpoint RequestTokenEndpoint {
- get {
- return this.requestTokenEndpoint;
- }
-
- set {
- if (value != null && UriUtil.QueryStringContainsOAuthParameters(value.Location)) {
- throw new ArgumentException(Strings.RequestUrlMustNotHaveOAuthParameters);
- }
-
- this.requestTokenEndpoint = value;
- }
- }
-
- /// <summary>
- /// Gets or sets the URL used to obtain User authorization for Consumer access,
- /// described in Section 6.2 (Obtaining User Authorization).
- /// </summary>
- /// <remarks>
- /// This is the URL that <see cref="OAuth.Messages.UserAuthorizationRequest"/> messages are
- /// indirectly (via the user agent) sent to.
- /// </remarks>
- public MessageReceivingEndpoint UserAuthorizationEndpoint { get; set; }
-
- /// <summary>
- /// Gets or sets the URL used to exchange the User-authorized Request Token
- /// for an Access Token, described in Section 6.3 (Obtaining an Access Token).
- /// </summary>
- /// <remarks>
- /// This is the URL that <see cref="OAuth.Messages.AuthorizedTokenRequest"/> messages are directed to.
- /// </remarks>
- public MessageReceivingEndpoint AccessTokenEndpoint { get; set; }
-
- /// <summary>
- /// Gets or sets the signing policies that apply to this Service Provider.
- /// </summary>
- [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Type initializers require this format.")]
- public ITamperProtectionChannelBindingElement[] TamperProtectionElements { get; set; }
-
- /// <summary>
- /// Creates a signing element that includes all the signing elements this service provider supports.
- /// </summary>
- /// <returns>The created signing element.</returns>
- internal ITamperProtectionChannelBindingElement CreateTamperProtectionElement() {
- return new SigningBindingElementChain(this.TamperProtectionElements.Select(el => (ITamperProtectionChannelBindingElement)el.Clone()).ToArray());
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="ServiceProviderDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; + using System.Linq; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth.ChannelElements; + + /// <summary> + /// A description of the endpoints on a Service Provider. + /// </summary> + public class ServiceProviderDescription { + /// <summary> + /// The field used to store the value of the <see cref="RequestTokenEndpoint"/> property. + /// </summary> + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private MessageReceivingEndpoint requestTokenEndpoint; + + /// <summary> + /// Initializes a new instance of the <see cref="ServiceProviderDescription"/> class. + /// </summary> + public ServiceProviderDescription() { + } + + /// <summary> + /// Gets or sets the URL used to obtain an unauthorized Request Token, + /// described in Section 6.1 (Obtaining an Unauthorized Request Token). + /// </summary> + /// <remarks> + /// The request URL query MUST NOT contain any OAuth Protocol Parameters. + /// This is the URL that <see cref="OAuth.Messages.UnauthorizedTokenRequest"/> messages are directed to. + /// </remarks> + /// <exception cref="ArgumentException">Thrown if this property is set to a URI with OAuth protocol parameters.</exception> + public MessageReceivingEndpoint RequestTokenEndpoint { + get { + return this.requestTokenEndpoint; + } + + set { + if (value != null && UriUtil.QueryStringContainsOAuthParameters(value.Location)) { + throw new ArgumentException(Strings.RequestUrlMustNotHaveOAuthParameters); + } + + this.requestTokenEndpoint = value; + } + } + + /// <summary> + /// Gets or sets the URL used to obtain User authorization for Consumer access, + /// described in Section 6.2 (Obtaining User Authorization). + /// </summary> + /// <remarks> + /// This is the URL that <see cref="OAuth.Messages.UserAuthorizationRequest"/> messages are + /// indirectly (via the user agent) sent to. + /// </remarks> + public MessageReceivingEndpoint UserAuthorizationEndpoint { get; set; } + + /// <summary> + /// Gets or sets the URL used to exchange the User-authorized Request Token + /// for an Access Token, described in Section 6.3 (Obtaining an Access Token). + /// </summary> + /// <remarks> + /// This is the URL that <see cref="OAuth.Messages.AuthorizedTokenRequest"/> messages are directed to. + /// </remarks> + public MessageReceivingEndpoint AccessTokenEndpoint { get; set; } + + /// <summary> + /// Gets or sets the signing policies that apply to this Service Provider. + /// </summary> + [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Type initializers require this format.")] + public ITamperProtectionChannelBindingElement[] TamperProtectionElements { get; set; } + + /// <summary> + /// Creates a signing element that includes all the signing elements this service provider supports. + /// </summary> + /// <returns>The created signing element.</returns> + internal ITamperProtectionChannelBindingElement CreateTamperProtectionElement() { + return new SigningBindingElementChain(this.TamperProtectionElements.Select(el => (ITamperProtectionChannelBindingElement)el.Clone()).ToArray()); + } + } +} diff --git a/src/DotNetOAuth/OAuth/WebConsumer.cs b/src/DotNetOpenAuth/OAuth/WebConsumer.cs index eed2168..e83be8b 100644 --- a/src/DotNetOAuth/OAuth/WebConsumer.cs +++ b/src/DotNetOpenAuth/OAuth/WebConsumer.cs @@ -1,97 +1,97 @@ -//-----------------------------------------------------------------------
-// <copyright file="WebConsumer.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth.OAuth {
- using System;
- using System.Collections.Generic;
- using System.Web;
- using DotNetOAuth.Messaging;
- using DotNetOAuth.OAuth.ChannelElements;
- using DotNetOAuth.OAuth.Messages;
-
- /// <summary>
- /// A website or application that uses OAuth to access the Service Provider on behalf of the User.
- /// </summary>
- /// <remarks>
- /// The methods on this class are thread-safe. Provided the properties are set and not changed
- /// afterward, a single instance of this class may be used by an entire web application safely.
- /// </remarks>
- public class WebConsumer : ConsumerBase {
- /// <summary>
- /// Initializes a new instance of the <see cref="WebConsumer"/> class.
- /// </summary>
- /// <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>
- public WebConsumer(ServiceProviderDescription serviceDescription, ITokenManager tokenManager)
- : base(serviceDescription, tokenManager) {
- }
-
- /// <summary>
- /// Begins an OAuth authorization request and redirects the user to the Service Provider
- /// to provide that authorization. Upon successful authorization, the user is redirected
- /// back to the current page.
- /// </summary>
- /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
- /// <remarks>
- /// Requires HttpContext.Current.
- /// </remarks>
- public UserAuthorizationRequest PrepareRequestUserAuthorization() {
- Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix(Protocol.Default.ParameterPrefix);
- return this.PrepareRequestUserAuthorization(callback, null, null);
- }
-
- /// <summary>
- /// Prepares an OAuth message that begins an authorization request that will
- /// redirect the user to the Service Provider to provide that authorization.
- /// </summary>
- /// <param name="callback">
- /// An optional Consumer URL that the Service Provider should redirect the
- /// User Agent to upon successful authorization.
- /// </param>
- /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param>
- /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param>
- /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
- public UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters) {
- string token;
- return this.PrepareRequestUserAuthorization(callback, requestParameters, redirectParameters, out token);
- }
-
- /// <summary>
- /// Processes an incoming authorization-granted message from an SP and obtains an access token.
- /// </summary>
- /// <returns>The access token, or null if no incoming authorization message was recognized.</returns>
- /// <remarks>
- /// Requires HttpContext.Current.
- /// </remarks>
- public AuthorizedTokenResponse ProcessUserAuthorization() {
- return this.ProcessUserAuthorization(this.Channel.GetRequestFromContext());
- }
-
- /// <summary>
- /// Processes an incoming authorization-granted message from an SP and obtains an access token.
- /// </summary>
- /// <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(HttpRequest request) {
- return this.ProcessUserAuthorization(new HttpRequestInfo(request));
- }
-
- /// <summary>
- /// Processes an incoming authorization-granted message from an SP and obtains an access token.
- /// </summary>
- /// <param name="request">The incoming HTTP request.</param>
- /// <returns>The access token, or null if no incoming authorization message was recognized.</returns>
- internal AuthorizedTokenResponse ProcessUserAuthorization(HttpRequestInfo request) {
- UserAuthorizationResponse authorizationMessage;
- if (this.Channel.TryReadFromRequest<UserAuthorizationResponse>(request, out authorizationMessage)) {
- string requestToken = authorizationMessage.RequestToken;
- return this.ProcessUserAuthorization(requestToken);
- } else {
- return null;
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="WebConsumer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + + /// <summary> + /// A website or application that uses OAuth to access the Service Provider on behalf of the User. + /// </summary> + /// <remarks> + /// The methods on this class are thread-safe. Provided the properties are set and not changed + /// afterward, a single instance of this class may be used by an entire web application safely. + /// </remarks> + public class WebConsumer : ConsumerBase { + /// <summary> + /// Initializes a new instance of the <see cref="WebConsumer"/> class. + /// </summary> + /// <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> + public WebConsumer(ServiceProviderDescription serviceDescription, ITokenManager tokenManager) + : base(serviceDescription, tokenManager) { + } + + /// <summary> + /// Begins an OAuth authorization request and redirects the user to the Service Provider + /// to provide that authorization. Upon successful authorization, the user is redirected + /// back to the current page. + /// </summary> + /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> + /// <remarks> + /// Requires HttpContext.Current. + /// </remarks> + public UserAuthorizationRequest PrepareRequestUserAuthorization() { + Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix(Protocol.Default.ParameterPrefix); + return this.PrepareRequestUserAuthorization(callback, null, null); + } + + /// <summary> + /// Prepares an OAuth message that begins an authorization request that will + /// redirect the user to the Service Provider to provide that authorization. + /// </summary> + /// <param name="callback"> + /// An optional Consumer URL that the Service Provider should redirect the + /// User Agent to upon successful authorization. + /// </param> + /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param> + /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param> + /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> + public UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters) { + string token; + return this.PrepareRequestUserAuthorization(callback, requestParameters, redirectParameters, out token); + } + + /// <summary> + /// Processes an incoming authorization-granted message from an SP and obtains an access token. + /// </summary> + /// <returns>The access token, or null if no incoming authorization message was recognized.</returns> + /// <remarks> + /// Requires HttpContext.Current. + /// </remarks> + public AuthorizedTokenResponse ProcessUserAuthorization() { + return this.ProcessUserAuthorization(this.Channel.GetRequestFromContext()); + } + + /// <summary> + /// Processes an incoming authorization-granted message from an SP and obtains an access token. + /// </summary> + /// <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(HttpRequest request) { + return this.ProcessUserAuthorization(new HttpRequestInfo(request)); + } + + /// <summary> + /// Processes an incoming authorization-granted message from an SP and obtains an access token. + /// </summary> + /// <param name="request">The incoming HTTP request.</param> + /// <returns>The access token, or null if no incoming authorization message was recognized.</returns> + internal AuthorizedTokenResponse ProcessUserAuthorization(HttpRequestInfo request) { + UserAuthorizationResponse authorizationMessage; + if (this.Channel.TryReadFromRequest<UserAuthorizationResponse>(request, out authorizationMessage)) { + string requestToken = authorizationMessage.RequestToken; + return this.ProcessUserAuthorization(requestToken); + } else { + return null; + } + } + } +} diff --git a/src/DotNetOAuth/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth/Properties/AssemblyInfo.cs index 725caf8..a4fda69 100644 --- a/src/DotNetOAuth/Properties/AssemblyInfo.cs +++ b/src/DotNetOpenAuth/Properties/AssemblyInfo.cs @@ -1,93 +1,93 @@ -//-----------------------------------------------------------------------
-// <copyright file="AssemblyInfo.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-// Uncomment this line to build a partially trusted assembly.
-// This has some security bonuses in that if there was a way to
-// hijack this assembly to do something it is not designed to do,
-// it will fail before doing much damage.
-// But a partially trusted assembly's events, handled by the hosting
-// web site, will also be under the partial trust restriction.
-// Also note that http://support.microsoft.com/kb/839300 states a
-// strong-name signed assembly must use AllowPartiallyTrustedCallers
-// to be called from a web page, but defining PARTIAL_TRUST below also
-// accomplishes this.
-////#define PARTIAL_TRUST
-
-// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build.
-
-using System;
-using System.Net;
-using System.Reflection;
-using System.Resources;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Security.Permissions;
-using System.Web.UI;
-
-[assembly: TagPrefix("DotNetOAuth", "oauth")]
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-[assembly: AssemblyTitle("DotNetOAuth")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("DotNetOAuth")]
-[assembly: AssemblyCopyright("Copyright © 2008")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-[assembly: NeutralResourcesLanguage("en-US")]
-[assembly: CLSCompliant(true)]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")]
-
-#if StrongNameSigned
-// See comment at top of this file. We need this so that strong-naming doesn't
-// keep this assembly from being useful to shared host (medium trust) web sites.
-[assembly: AllowPartiallyTrustedCallers]
-
-[assembly: InternalsVisibleTo("DotNetOAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")]
-#else
-[assembly: InternalsVisibleTo("DotNetOAuth.Test")]
-#endif
-
-// Specify what permissions are required and optional for the assembly.
-// In order for CAS to remove unnecessary privileges from this assembly (which is desirable
-// for security), we need at least one RequestMinimum and at least one RequestOptional.
-// These permissions were determined using PermCalc.exe
-
-// We need to be allowed to execute code. Besides, it gives a good baseline RequestMinimum permission.
-[assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)]
-
-// Allows the consumer to call out to the web server. This is unnecessary in provider-only scenarios.
-// Note: we don't use a single demand for https?://.* because the regex pattern must exactly
-// match the one used by hosting providers. Listing them individually seems to be more common.
-[assembly: WebPermission(SecurityAction.RequestMinimum, ConnectPattern = @"http://.*")]
-[assembly: WebPermission(SecurityAction.RequestMinimum, ConnectPattern = @"https://.*")]
-
-#if PARTIAL_TRUST
-// Allows hosting this assembly in an ASP.NET setting. Not all applications
-// will host this using ASP.NET, so this is optional. Besides, we need at least
-// one optional permission to activate CAS permission shrinking.
-[assembly: AspNetHostingPermission(SecurityAction.RequestOptional, Level = AspNetHostingPermissionLevel.Medium)]
-
-// The following are only required for diagnostic logging (Trace.Write, Debug.Assert, etc.).
-#if TRACE || DEBUG
-[assembly: KeyContainerPermission(SecurityAction.RequestOptional, Unrestricted = true)]
-[assembly: ReflectionPermission(SecurityAction.RequestOptional, MemberAccess = true)]
-[assembly: RegistryPermission(SecurityAction.RequestOptional, Unrestricted = true)]
-[assembly: SecurityPermission(SecurityAction.RequestOptional, ControlEvidence = true, UnmanagedCode = true, ControlThread = true)]
-[assembly: FileIOPermission(SecurityAction.RequestOptional, AllFiles = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read)]
-#endif
-#endif
+//----------------------------------------------------------------------- +// <copyright file="AssemblyInfo.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +// Uncomment this line to build a partially trusted assembly. +// This has some security bonuses in that if there was a way to +// hijack this assembly to do something it is not designed to do, +// it will fail before doing much damage. +// But a partially trusted assembly's events, handled by the hosting +// web site, will also be under the partial trust restriction. +// Also note that http://support.microsoft.com/kb/839300 states a +// strong-name signed assembly must use AllowPartiallyTrustedCallers +// to be called from a web page, but defining PARTIAL_TRUST below also +// accomplishes this. +////#define PARTIAL_TRUST + +// We DON'T put an AssemblyVersionAttribute in here because it is generated in the build. + +using System; +using System.Net; +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Permissions; +using System.Web.UI; + +[assembly: TagPrefix("DotNetOpenAuth", "oauth")] + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DotNetOpenAuth")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DotNetOpenAuth")] +[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: NeutralResourcesLanguage("en-US")] +[assembly: CLSCompliant(true)] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7d73990c-47c0-4256-9f20-a893add9e289")] + +#if StrongNameSigned +// See comment at top of this file. We need this so that strong-naming doesn't +// keep this assembly from being useful to shared host (medium trust) web sites. +[assembly: AllowPartiallyTrustedCallers] + +[assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] +#else +[assembly: InternalsVisibleTo("DotNetOpenAuth.Test")] +#endif + +// Specify what permissions are required and optional for the assembly. +// In order for CAS to remove unnecessary privileges from this assembly (which is desirable +// for security), we need at least one RequestMinimum and at least one RequestOptional. +// These permissions were determined using PermCalc.exe + +// We need to be allowed to execute code. Besides, it gives a good baseline RequestMinimum permission. +[assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] + +// Allows the consumer to call out to the web server. This is unnecessary in provider-only scenarios. +// Note: we don't use a single demand for https?://.* because the regex pattern must exactly +// match the one used by hosting providers. Listing them individually seems to be more common. +[assembly: WebPermission(SecurityAction.RequestMinimum, ConnectPattern = @"http://.*")] +[assembly: WebPermission(SecurityAction.RequestMinimum, ConnectPattern = @"https://.*")] + +#if PARTIAL_TRUST +// Allows hosting this assembly in an ASP.NET setting. Not all applications +// will host this using ASP.NET, so this is optional. Besides, we need at least +// one optional permission to activate CAS permission shrinking. +[assembly: AspNetHostingPermission(SecurityAction.RequestOptional, Level = AspNetHostingPermissionLevel.Medium)] + +// The following are only required for diagnostic logging (Trace.Write, Debug.Assert, etc.). +#if TRACE || DEBUG +[assembly: KeyContainerPermission(SecurityAction.RequestOptional, Unrestricted = true)] +[assembly: ReflectionPermission(SecurityAction.RequestOptional, MemberAccess = true)] +[assembly: RegistryPermission(SecurityAction.RequestOptional, Unrestricted = true)] +[assembly: SecurityPermission(SecurityAction.RequestOptional, ControlEvidence = true, UnmanagedCode = true, ControlThread = true)] +[assembly: FileIOPermission(SecurityAction.RequestOptional, AllFiles = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read)] +#endif +#endif diff --git a/src/DotNetOAuth/Settings.StyleCop b/src/DotNetOpenAuth/Settings.StyleCop index 2eaae96..9577b59 100644 --- a/src/DotNetOAuth/Settings.StyleCop +++ b/src/DotNetOpenAuth/Settings.StyleCop @@ -1,14 +1,14 @@ -<StyleCopSettings Version="4.3">
- <Analyzers>
- <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.DocumentationRules">
- <Rules>
- <Rule Name="ElementDocumentationMustNotBeCopiedAndPasted">
- <RuleSettings>
- <BooleanProperty Name="Enabled">False</BooleanProperty>
- </RuleSettings>
- </Rule>
- </Rules>
- <AnalyzerSettings />
- </Analyzer>
- </Analyzers>
+<StyleCopSettings Version="4.3"> + <Analyzers> + <Analyzer AnalyzerId="Microsoft.StyleCop.CSharp.DocumentationRules"> + <Rules> + <Rule Name="ElementDocumentationMustNotBeCopiedAndPasted"> + <RuleSettings> + <BooleanProperty Name="Enabled">False</BooleanProperty> + </RuleSettings> + </Rule> + </Rules> + <AnalyzerSettings /> + </Analyzer> + </Analyzers> </StyleCopSettings>
\ No newline at end of file diff --git a/src/DotNetOAuth/Strings.Designer.cs b/src/DotNetOpenAuth/Strings.Designer.cs index c312fe5..67f552e 100644 --- a/src/DotNetOAuth/Strings.Designer.cs +++ b/src/DotNetOpenAuth/Strings.Designer.cs @@ -1,135 +1,135 @@ -//------------------------------------------------------------------------------
-// <auto-generated>
-// This code was generated by a tool.
-// Runtime Version:2.0.50727.3053
-//
-// Changes to this file may cause incorrect behavior and will be lost if
-// the code is regenerated.
-// </auto-generated>
-//------------------------------------------------------------------------------
-
-namespace DotNetOAuth {
- using System;
-
-
- /// <summary>
- /// A strongly-typed resource class, for looking up localized strings, etc.
- /// </summary>
- // This class was auto-generated by the StronglyTypedResourceBuilder
- // class via a tool like ResGen or Visual Studio.
- // To add or remove a member, edit your .ResX file then rerun ResGen
- // with the /str option, or rebuild your VS project.
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- internal class Strings {
-
- private static global::System.Resources.ResourceManager resourceMan;
-
- private static global::System.Globalization.CultureInfo resourceCulture;
-
- [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal Strings() {
- }
-
- /// <summary>
- /// Returns the cached ResourceManager instance used by this class.
- /// </summary>
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Resources.ResourceManager ResourceManager {
- get {
- if (object.ReferenceEquals(resourceMan, null)) {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DotNetOAuth.Strings", typeof(Strings).Assembly);
- resourceMan = temp;
- }
- return resourceMan;
- }
- }
-
- /// <summary>
- /// Overrides the current thread's CurrentUICulture property for all
- /// resource lookups using this strongly typed resource class.
- /// </summary>
- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
- internal static global::System.Globalization.CultureInfo Culture {
- get {
- return resourceCulture;
- }
- set {
- resourceCulture = value;
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Cannot send access token to Consumer for request token '{0}' before it has been authorized..
- /// </summary>
- internal static string AccessTokenNotAuthorized {
- get {
- return ResourceManager.GetString("AccessTokenNotAuthorized", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The access token '{0}' is invalid or expired..
- /// </summary>
- internal static string BadAccessTokenInProtectedResourceRequest {
- get {
- return ResourceManager.GetString("BadAccessTokenInProtectedResourceRequest", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Failure looking up secret for consumer or token..
- /// </summary>
- internal static string ConsumerOrTokenSecretNotFound {
- get {
- return ResourceManager.GetString("ConsumerOrTokenSecretNotFound", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to An invalid OAuth message received and discarded..
- /// </summary>
- internal static string InvalidIncomingMessage {
- get {
- return ResourceManager.GetString("InvalidIncomingMessage", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The {0} message included extra data which is not allowed..
- /// </summary>
- internal static string MessageNotAllowedExtraParameters {
- get {
- return ResourceManager.GetString("MessageNotAllowedExtraParameters", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The request URL query MUST NOT contain any OAuth Protocol Parameters..
- /// </summary>
- internal static string RequestUrlMustNotHaveOAuthParameters {
- get {
- return ResourceManager.GetString("RequestUrlMustNotHaveOAuthParameters", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to The signing element already has been associated with a channel..
- /// </summary>
- internal static string SigningElementAlreadyAssociatedWithChannel {
- get {
- return ResourceManager.GetString("SigningElementAlreadyAssociatedWithChannel", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to All signing elements must offer the same message protection..
- /// </summary>
- internal static string SigningElementsMustShareSameProtection {
- get {
- return ResourceManager.GetString("SigningElementsMustShareSameProtection", resourceCulture);
- }
- }
- }
-}
+//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by a tool. +// Runtime Version:2.0.50727.3053 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// </auto-generated> +//------------------------------------------------------------------------------ + +namespace DotNetOpenAuth { + using System; + + + /// <summary> + /// A strongly-typed resource class, for looking up localized strings, etc. + /// </summary> + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Strings { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Strings() { + } + + /// <summary> + /// Returns the cached ResourceManager instance used by this class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DotNetOpenAuth.Strings", typeof(Strings).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// <summary> + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// <summary> + /// Looks up a localized string similar to Cannot send access token to Consumer for request token '{0}' before it has been authorized.. + /// </summary> + internal static string AccessTokenNotAuthorized { + get { + return ResourceManager.GetString("AccessTokenNotAuthorized", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The access token '{0}' is invalid or expired.. + /// </summary> + internal static string BadAccessTokenInProtectedResourceRequest { + get { + return ResourceManager.GetString("BadAccessTokenInProtectedResourceRequest", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to Failure looking up secret for consumer or token.. + /// </summary> + internal static string ConsumerOrTokenSecretNotFound { + get { + return ResourceManager.GetString("ConsumerOrTokenSecretNotFound", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to An invalid OAuth message received and discarded.. + /// </summary> + internal static string InvalidIncomingMessage { + get { + return ResourceManager.GetString("InvalidIncomingMessage", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The {0} message included extra data which is not allowed.. + /// </summary> + internal static string MessageNotAllowedExtraParameters { + get { + return ResourceManager.GetString("MessageNotAllowedExtraParameters", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The request URL query MUST NOT contain any OAuth Protocol Parameters.. + /// </summary> + internal static string RequestUrlMustNotHaveOAuthParameters { + get { + return ResourceManager.GetString("RequestUrlMustNotHaveOAuthParameters", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The signing element already has been associated with a channel.. + /// </summary> + internal static string SigningElementAlreadyAssociatedWithChannel { + get { + return ResourceManager.GetString("SigningElementAlreadyAssociatedWithChannel", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to All signing elements must offer the same message protection.. + /// </summary> + internal static string SigningElementsMustShareSameProtection { + get { + return ResourceManager.GetString("SigningElementsMustShareSameProtection", resourceCulture); + } + } + } +} diff --git a/src/DotNetOAuth/Strings.resx b/src/DotNetOpenAuth/Strings.resx index 252726e..3e59ca9 100644 --- a/src/DotNetOAuth/Strings.resx +++ b/src/DotNetOpenAuth/Strings.resx @@ -1,144 +1,144 @@ -<?xml version="1.0" encoding="utf-8"?>
-<root>
- <!--
- Microsoft ResX Schema
-
- Version 2.0
-
- The primary goals of this format is to allow a simple XML format
- that is mostly human readable. The generation and parsing of the
- various data types are done through the TypeConverter classes
- associated with the data types.
-
- Example:
-
- ... ado.net/XML headers & schema ...
- <resheader name="resmimetype">text/microsoft-resx</resheader>
- <resheader name="version">2.0</resheader>
- <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
- <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
- <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
- <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
- <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
- <value>[base64 mime encoded serialized .NET Framework object]</value>
- </data>
- <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
- <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
- <comment>This is a comment</comment>
- </data>
-
- There are any number of "resheader" rows that contain simple
- name/value pairs.
-
- Each data row contains a name, and value. The row also contains a
- type or mimetype. Type corresponds to a .NET class that support
- text/value conversion through the TypeConverter architecture.
- Classes that don't support this are serialized and stored with the
- mimetype set.
-
- The mimetype is used for serialized objects, and tells the
- ResXResourceReader how to depersist the object. This is currently not
- extensible. For a given mimetype the value must be set accordingly:
-
- Note - application/x-microsoft.net.object.binary.base64 is the format
- that the ResXResourceWriter will generate, however the reader can
- read any of the formats listed below.
-
- mimetype: application/x-microsoft.net.object.binary.base64
- value : The object must be serialized with
- : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
- : and then encoded with base64 encoding.
-
- mimetype: application/x-microsoft.net.object.soap.base64
- value : The object must be serialized with
- : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
- : and then encoded with base64 encoding.
-
- mimetype: application/x-microsoft.net.object.bytearray.base64
- value : The object must be serialized into a byte array
- : using a System.ComponentModel.TypeConverter
- : and then encoded with base64 encoding.
- -->
- <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
- <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
- <xsd:element name="root" msdata:IsDataSet="true">
- <xsd:complexType>
- <xsd:choice maxOccurs="unbounded">
- <xsd:element name="metadata">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element name="value" type="xsd:string" minOccurs="0" />
- </xsd:sequence>
- <xsd:attribute name="name" use="required" type="xsd:string" />
- <xsd:attribute name="type" type="xsd:string" />
- <xsd:attribute name="mimetype" type="xsd:string" />
- <xsd:attribute ref="xml:space" />
- </xsd:complexType>
- </xsd:element>
- <xsd:element name="assembly">
- <xsd:complexType>
- <xsd:attribute name="alias" type="xsd:string" />
- <xsd:attribute name="name" type="xsd:string" />
- </xsd:complexType>
- </xsd:element>
- <xsd:element name="data">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
- <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
- </xsd:sequence>
- <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
- <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
- <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
- <xsd:attribute ref="xml:space" />
- </xsd:complexType>
- </xsd:element>
- <xsd:element name="resheader">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
- </xsd:sequence>
- <xsd:attribute name="name" type="xsd:string" use="required" />
- </xsd:complexType>
- </xsd:element>
- </xsd:choice>
- </xsd:complexType>
- </xsd:element>
- </xsd:schema>
- <resheader name="resmimetype">
- <value>text/microsoft-resx</value>
- </resheader>
- <resheader name="version">
- <value>2.0</value>
- </resheader>
- <resheader name="reader">
- <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
- </resheader>
- <resheader name="writer">
- <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
- </resheader>
- <data name="AccessTokenNotAuthorized" xml:space="preserve">
- <value>Cannot send access token to Consumer for request token '{0}' before it has been authorized.</value>
- </data>
- <data name="BadAccessTokenInProtectedResourceRequest" xml:space="preserve">
- <value>The access token '{0}' is invalid or expired.</value>
- </data>
- <data name="ConsumerOrTokenSecretNotFound" xml:space="preserve">
- <value>Failure looking up secret for consumer or token.</value>
- </data>
- <data name="InvalidIncomingMessage" xml:space="preserve">
- <value>An invalid OAuth message received and discarded.</value>
- </data>
- <data name="MessageNotAllowedExtraParameters" xml:space="preserve">
- <value>The {0} message included extra data which is not allowed.</value>
- </data>
- <data name="RequestUrlMustNotHaveOAuthParameters" xml:space="preserve">
- <value>The request URL query MUST NOT contain any OAuth Protocol Parameters.</value>
- </data>
- <data name="SigningElementAlreadyAssociatedWithChannel" xml:space="preserve">
- <value>The signing element already has been associated with a channel.</value>
- </data>
- <data name="SigningElementsMustShareSameProtection" xml:space="preserve">
- <value>All signing elements must offer the same message protection.</value>
- </data>
+<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <data name="AccessTokenNotAuthorized" xml:space="preserve"> + <value>Cannot send access token to Consumer for request token '{0}' before it has been authorized.</value> + </data> + <data name="BadAccessTokenInProtectedResourceRequest" xml:space="preserve"> + <value>The access token '{0}' is invalid or expired.</value> + </data> + <data name="ConsumerOrTokenSecretNotFound" xml:space="preserve"> + <value>Failure looking up secret for consumer or token.</value> + </data> + <data name="InvalidIncomingMessage" xml:space="preserve"> + <value>An invalid OAuth message received and discarded.</value> + </data> + <data name="MessageNotAllowedExtraParameters" xml:space="preserve"> + <value>The {0} message included extra data which is not allowed.</value> + </data> + <data name="RequestUrlMustNotHaveOAuthParameters" xml:space="preserve"> + <value>The request URL query MUST NOT contain any OAuth Protocol Parameters.</value> + </data> + <data name="SigningElementAlreadyAssociatedWithChannel" xml:space="preserve"> + <value>The signing element already has been associated with a channel.</value> + </data> + <data name="SigningElementsMustShareSameProtection" xml:space="preserve"> + <value>All signing elements must offer the same message protection.</value> + </data> </root>
\ No newline at end of file diff --git a/src/DotNetOAuth/UriUtil.cs b/src/DotNetOpenAuth/UriUtil.cs index bec3561..04bbb0f 100644 --- a/src/DotNetOAuth/UriUtil.cs +++ b/src/DotNetOpenAuth/UriUtil.cs @@ -1,31 +1,31 @@ -//-----------------------------------------------------------------------
-// <copyright file="UriUtil.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOAuth {
- using System;
- using System.Collections.Specialized;
- using System.Linq;
- using System.Web;
-
- /// <summary>
- /// Utility methods for working with URIs.
- /// </summary>
- internal static class UriUtil {
- /// <summary>
- /// Tests a URI for the presence of an OAuth payload.
- /// </summary>
- /// <param name="uri">The URI to test.</param>
- /// <returns>True if the URI contains an OAuth message.</returns>
- internal static bool QueryStringContainsOAuthParameters(Uri uri) {
- if (uri == null) {
- return false;
- }
-
- NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query);
- return nvc.Keys.OfType<string>().Any(key => key.StartsWith(OAuth.Protocol.V10.ParameterPrefix, StringComparison.Ordinal));
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="UriUtil.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth { + using System; + using System.Collections.Specialized; + using System.Linq; + using System.Web; + + /// <summary> + /// Utility methods for working with URIs. + /// </summary> + internal static class UriUtil { + /// <summary> + /// Tests a URI for the presence of an OAuth payload. + /// </summary> + /// <param name="uri">The URI to test.</param> + /// <returns>True if the URI contains an OAuth message.</returns> + internal static bool QueryStringContainsOAuthParameters(Uri uri) { + if (uri == null) { + return false; + } + + NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query); + return nvc.Keys.OfType<string>().Any(key => key.StartsWith(OAuth.Protocol.V10.ParameterPrefix, StringComparison.Ordinal)); + } + } +} diff --git a/src/DotNetOAuth/Util.cs b/src/DotNetOpenAuth/Util.cs index 27d8299..b54ada9 100644 --- a/src/DotNetOAuth/Util.cs +++ b/src/DotNetOpenAuth/Util.cs @@ -1,30 +1,30 @@ -//-----------------------------------------------------------------------
-// <copyright file="Util.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-namespace DotNetOAuth {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Reflection;
-
- /// <summary>
- /// A grab-bag utility class.
- /// </summary>
- internal static class Util {
- /// <summary>
- /// Gets a human-readable description of the library name and version, including
- /// whether the build is an official or private one.
- /// </summary>
- public static string LibraryVersion {
- get {
- string assemblyFullName = Assembly.GetExecutingAssembly().FullName;
- bool official = assemblyFullName.Contains("PublicKeyToken=2780ccd10d57b246");
-
- // We use InvariantCulture since this is used for logging.
- return string.Format(CultureInfo.InvariantCulture, "{0} ({1})", assemblyFullName, official ? "official" : "private");
- }
- }
- }
-}
+//----------------------------------------------------------------------- +// <copyright file="Util.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- +namespace DotNetOpenAuth { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Reflection; + + /// <summary> + /// A grab-bag utility class. + /// </summary> + internal static class Util { + /// <summary> + /// Gets a human-readable description of the library name and version, including + /// whether the build is an official or private one. + /// </summary> + public static string LibraryVersion { + get { + string assemblyFullName = Assembly.GetExecutingAssembly().FullName; + bool official = assemblyFullName.Contains("PublicKeyToken=2780ccd10d57b246"); + + // We use InvariantCulture since this is used for logging. + return string.Format(CultureInfo.InvariantCulture, "{0} ({1})", assemblyFullName, official ? "official" : "private"); + } + } + } +} diff --git a/src/LocalTestRun.testrunconfig b/src/LocalTestRun.testrunconfig index bad921b..f037171 100644 --- a/src/LocalTestRun.testrunconfig +++ b/src/LocalTestRun.testrunconfig @@ -1,22 +1,22 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<TestRunConfiguration name="Local Test Run" id="abbd81c0-7d7b-4c98-878c-05dbead62c27" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2006">
- <Description>This is a default test run configuration for a local test run.</Description>
- <CodeCoverage enabled="true">
- <Regular>
- <CodeCoverageItem binaryFile="C:\git\dotnetoauth\bin\Debug\DotNetOAuth.dll" pdbFile="C:\git\dotnetoauth\bin\Debug\DotNetOAuth.pdb" instrumentInPlace="true" />
- </Regular>
- </CodeCoverage>
- <TestTypeSpecific>
- <WebTestRunConfiguration testTypeId="4e7599fa-5ecb-43e9-a887-cd63cf72d207">
- <Browser name="Internet Explorer 7.0">
- <Headers>
- <Header name="User-Agent" value="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)" />
- <Header name="Accept" value="*/*" />
- <Header name="Accept-Language" value="{{$IEAcceptLanguage}}" />
- <Header name="Accept-Encoding" value="GZIP" />
- </Headers>
- </Browser>
- <Network Name="LAN" BandwidthInKbps="0" />
- </WebTestRunConfiguration>
- </TestTypeSpecific>
+<?xml version="1.0" encoding="UTF-8"?> +<TestRunConfiguration name="Local Test Run" id="abbd81c0-7d7b-4c98-878c-05dbead62c27" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2006"> + <Description>This is a default test run configuration for a local test run.</Description> + <CodeCoverage enabled="true"> + <Regular> + <CodeCoverageItem binaryFile="C:\git\dotnetoauth\bin\Debug\DotNetOpenAuth.dll" pdbFile="C:\git\dotnetoauth\bin\Debug\DotNetOpenAuth.pdb" instrumentInPlace="true" /> + </Regular> + </CodeCoverage> + <TestTypeSpecific> + <WebTestRunConfiguration testTypeId="4e7599fa-5ecb-43e9-a887-cd63cf72d207"> + <Browser name="Internet Explorer 7.0"> + <Headers> + <Header name="User-Agent" value="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)" /> + <Header name="Accept" value="*/*" /> + <Header name="Accept-Language" value="{{$IEAcceptLanguage}}" /> + <Header name="Accept-Encoding" value="GZIP" /> + </Headers> + </Browser> + <Network Name="LAN" BandwidthInKbps="0" /> + </WebTestRunConfiguration> + </TestTypeSpecific> </TestRunConfiguration>
\ No newline at end of file |