Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,43 @@
//
// ActionNotSupportedException.cs
//
// Author: Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace System.ServiceModel
{
[Serializable]
public class ActionNotSupportedException : CommunicationException
{
public ActionNotSupportedException () : base () {}
public ActionNotSupportedException (string msg) : base (msg) {}
public ActionNotSupportedException (string msg, Exception inner) : base (msg, inner) {}
protected ActionNotSupportedException (SerializationInfo info, StreamingContext context) :
base (info, context) {}
}
}

View File

@ -0,0 +1,44 @@
//
// System.ServiceModel.AddressAccessDeniedException.cs
//
// Author: Duncan Mak (duncan@novell.com)
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace System.ServiceModel {
[Serializable]
public class AddressAccessDeniedException : CommunicationException
{
public AddressAccessDeniedException () : base () {}
public AddressAccessDeniedException (string msg) : base (msg) {}
public AddressAccessDeniedException (string msg, Exception inner) : base (msg, inner) {}
protected AddressAccessDeniedException (SerializationInfo info, StreamingContext context) :
base (info, context) {}
}
}

View File

@ -0,0 +1,44 @@
//
// System.ServiceModel.AddressAlreadyInUseException.cs
//
// Author: Duncan Mak (duncan@novell.com)
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace System.ServiceModel {
[Serializable]
public class AddressAlreadyInUseException : CommunicationException
{
public AddressAlreadyInUseException () : base () {}
public AddressAlreadyInUseException (string msg) : base (msg) {}
public AddressAlreadyInUseException (string msg, Exception inner) : base (msg, inner) {}
protected AddressAlreadyInUseException (SerializationInfo info, StreamingContext context) :
base (info, context) {}
}
}

View File

@ -0,0 +1,442 @@
//
// AllEnums.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.ServiceModel.Activation
{
public enum AspNetCompatibilityRequirementsMode
{
NotAllowed,
Allowed,
Required,
}
}
namespace System.ServiceModel
{
public enum AddressFilterMode
{
Exact,
Prefix,
Any
}
public enum AuditLevel
{
None,
Success,
Failure,
SuccessOrFailure,
}
public enum AuditLogLocation
{
Default,
Application,
Security,
}
public enum BasicHttpMessageCredentialType
{
UserName,
Certificate,
}
public enum BasicHttpSecurityMode
{
None,
Transport,
Message,
TransportWithMessageCredential,
TransportCredentialOnly,
}
#if NET_4_5
public enum BasicHttpsSecurityMode
{
Transport,
TransportWithMessageCredential
}
#endif
public enum CommunicationState
{
Created,
Opening,
Opened,
Closing,
Closed,
Faulted,
}
public enum ConcurrencyMode
{
Single,
Reentrant,
Multiple,
}
public enum HostNameComparisonMode
{
StrongWildcard,
Exact,
WeakWildcard,
}
public enum ImpersonationOption
{
NotAllowed,
Allowed,
Required,
}
public enum InstanceContextMode
{
PerSession,
PerCall,
Single,
}
public enum NetMsmqSecurityMode
{
None,
Transport,
Message,
Both,
}
public enum NetNamedPipeSecurityMode
{
None,
Transport,
}
public enum OperationFormatStyle
{
Document,
Rpc,
}
public enum OperationFormatUse
{
Literal,
Encoded,
}
public enum PeerMessageOrigination
{
Local,
Remote,
}
public enum PeerMessagePropagation
{
None,
Local,
Remote,
LocalAndRemote,
}
public enum QueuedDeliveryRequirementsMode
{
Allowed,
Required,
NotAllowed,
}
public enum PeerTransportCredentialType
{
Password,
Certificate,
}
public enum ReceiveErrorHandling
{
Fault,
Drop,
Reject,
Move,
}
public enum ReleaseInstanceMode
{
None,
BeforeCall,
AfterCall,
BeforeAndAfterCall,
}
public enum SessionMode
{
Allowed,
Required,
NotAllowed,
}
public enum TransactionFlowOption
{
NotAllowed,
Allowed,
Mandatory,
}
public enum WSDualHttpSecurityMode
{
None,
Message,
}
public enum WSFederationHttpSecurityMode
{
None,
Message,
TransportWithMessageCredential,
}
public enum WSMessageEncoding
{
Text,
Mtom,
}
}
namespace System.ServiceModel // used to be S.SM.Ch
{
public enum DeadLetterQueue
{
None,
System,
Custom,
}
public enum HttpClientCredentialType
{
None,
Basic,
Digest,
Ntlm,
Windows,
Certificate,
#if NET_4_5
InheritedFromHost
#endif
}
public enum HttpProxyCredentialType
{
None,
Basic,
Digest,
Ntlm,
Windows,
}
public enum MessageCredentialType
{
None,
Windows,
UserName,
Certificate,
IssuedToken,
}
public enum MsmqAuthenticationMode
{
None,
WindowsDomain,
Certificate,
}
public enum MsmqEncryptionAlgorithm
{
RC4Stream,
Aes,
}
public enum MsmqSecureHashAlgorithm
{
MD5,
Sha1,
Sha256,
Sha512,
}
public enum QueueTransferProtocol
{
Native,
Srmp,
SrmpSecure,
}
public enum SecurityMode
{
None,
Transport,
Message,
TransportWithMessageCredential,
}
public enum TcpClientCredentialType
{
None,
Windows,
Certificate,
}
}
namespace System.ServiceModel.Channels
{
public enum MessageState
{
Created,
Read,
Written,
Copied,
Closed,
}
public enum SecurityHeaderLayout
{
Strict,
Lax,
LaxTimestampFirst,
LaxTimestampLast,
}
public enum SupportedAddressingMode
{
Anonymous,
NonAnonymous,
Mixed
}
public enum TransferSession
{
None,
Ordered,
Unordered,
}
}
namespace System.ServiceModel.Description
{
public enum PrincipalPermissionMode
{
None,
UseWindowsGroups,
UseAspNetRoles,
Custom,
}
public enum MessageDirection
{
Input,
Output,
}
public enum ListenUriMode
{
Explicit,
Unique,
}
public enum MetadataExchangeClientMode
{
MetadataExchange,
HttpGet
}
[Flags]
public enum ServiceContractGenerationOptions
{
None,
AsynchronousMethods = 1,
ChannelInterface = 2,
InternalTypes = 4,
ClientClass = 8,
TypedMessages = 16,
EventBasedAsynchronousMethods = 32,
}
}
namespace System.ServiceModel.MsmqIntegration
{
public enum MsmqIntegrationSecurityMode
{
None,
Transport,
}
public enum MsmqMessageSerializationFormat
{
Xml,
Binary,
ActiveX,
ByteArray,
Stream,
}
}
namespace System.ServiceModel.Security
{
public enum UserNamePasswordValidationMode
{
Windows,
MembershipProvider,
Custom,
}
public enum X509CertificateValidationMode
{
None,
PeerTrust,
ChainTrust,
PeerOrChainTrust,
Custom,
}
}
namespace System.ServiceModel.Security.Tokens
{
public enum SecurityTokenInclusionMode
{
AlwaysToRecipient,
Never,
Once,
AlwaysToInitiator,
}
public enum X509KeyIdentifierClauseType
{
Any,
Thumbprint,
IssuerSerial,
SubjectKeyIdentifier,
RawDataKeyIdentifier,
}
}

View File

@ -0,0 +1,330 @@
//
// BasicHttpBinding.cs
//
// See BasicHttpBinding_4_5.cs and HttpBindingBase.cs for the .NET 4.5
// version of this class.
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005-2006 Novell, Inc. http://www.novell.com
// Copyright 2011 Xamarin Inc (http://www.xamarin.com).
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !NET_4_5 && !MOBILE
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Xml;
using System.ServiceModel.Configuration;
namespace System.ServiceModel
{
public class BasicHttpBinding : Binding,
IBindingRuntimePreferences
{
bool allow_cookies, bypass_proxy_on_local;
HostNameComparisonMode host_name_comparison_mode
= HostNameComparisonMode.StrongWildcard;
long max_buffer_pool_size = 0x80000;
int max_buffer_size = 0x10000;
long max_recv_message_size = 0x10000;
WSMessageEncoding message_encoding
= WSMessageEncoding.Text;
Uri proxy_address;
XmlDictionaryReaderQuotas reader_quotas
= new XmlDictionaryReaderQuotas ();
EnvelopeVersion env_version = EnvelopeVersion.Soap11;
static readonly Encoding default_text_encoding = new UTF8Encoding ();
Encoding text_encoding = default_text_encoding;
TransferMode transfer_mode
= TransferMode.Buffered;
bool use_default_web_proxy = true;
BasicHttpSecurity security;
public BasicHttpBinding ()
: this (BasicHttpSecurityMode.None)
{
}
#if !NET_2_1
public BasicHttpBinding (string configurationName)
: this ()
{
BindingsSection bindingsSection = ConfigUtil.BindingsSection;
BasicHttpBindingElement el =
bindingsSection.BasicHttpBinding.Bindings [configurationName];
el.ApplyConfiguration (this);
}
#endif
public BasicHttpBinding (
BasicHttpSecurityMode securityMode)
{
security = new BasicHttpSecurity (securityMode);
}
public bool AllowCookies {
get { return allow_cookies; }
set { allow_cookies = value; }
}
public bool BypassProxyOnLocal {
get { return bypass_proxy_on_local; }
set { bypass_proxy_on_local = value; }
}
#if NET_2_1
public bool EnableHttpCookieContainer {
get; set;
}
#elif NET_4_5
[Obsolete ("Use AllowCookies.")]
public bool EnableHttpCookieContainer {
get { return AllowCookies; }
set { AllowCookies = value; }
}
#endif
public HostNameComparisonMode HostNameComparisonMode {
get { return host_name_comparison_mode; }
set { host_name_comparison_mode = value; }
}
public long MaxBufferPoolSize {
get { return max_buffer_pool_size; }
set {
if (value <= 0)
throw new ArgumentOutOfRangeException ();
max_buffer_pool_size = value;
}
}
public int MaxBufferSize {
get { return max_buffer_size; }
set {
if (value <= 0)
throw new ArgumentOutOfRangeException ();
max_buffer_size = value;
}
}
public long MaxReceivedMessageSize {
get { return max_recv_message_size; }
set {
if (value <= 0)
throw new ArgumentOutOfRangeException ();
max_recv_message_size = value;
}
}
public WSMessageEncoding MessageEncoding {
get { return message_encoding; }
set { message_encoding = value; }
}
public Uri ProxyAddress {
get { return proxy_address; }
set { proxy_address = value; }
}
public XmlDictionaryReaderQuotas ReaderQuotas {
get { return reader_quotas; }
set { reader_quotas = value; }
}
public override string Scheme {
get {
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
case BasicHttpSecurityMode.TransportWithMessageCredential:
return Uri.UriSchemeHttps;
default:
return Uri.UriSchemeHttp;
}
}
}
public BasicHttpSecurity Security {
get { return security; }
}
public EnvelopeVersion EnvelopeVersion {
get { return env_version; }
}
internal static Encoding DefaultTextEncoding {
get { return default_text_encoding; }
}
public Encoding TextEncoding {
get { return text_encoding; }
set { text_encoding = value; }
}
public TransferMode TransferMode {
get { return transfer_mode; }
set { transfer_mode = value; }
}
public bool UseDefaultWebProxy {
get { return use_default_web_proxy; }
set { use_default_web_proxy = value; }
}
public override BindingElementCollection
CreateBindingElements ()
{
var list = new List<BindingElement> ();
var security = CreateSecurityBindingElement ();
if (security != null)
list.Add (security);
#if NET_2_1
if (EnableHttpCookieContainer)
list.Add (new HttpCookieContainerBindingElement ());
#endif
list.Add (BuildMessageEncodingBindingElement ());
list.Add (GetTransport ());
return new BindingElementCollection (list.ToArray ());
}
SecurityBindingElement CreateSecurityBindingElement ()
{
SecurityBindingElement element;
switch (Security.Mode) {
#if !NET_2_1
case BasicHttpSecurityMode.Message:
if (Security.Message.ClientCredentialType != BasicHttpMessageCredentialType.Certificate)
throw new InvalidOperationException ("When Message security is enabled in a BasicHttpBinding, the message security credential type must be BasicHttpMessageCredentialType.Certificate.");
element = SecurityBindingElement.CreateMutualCertificateBindingElement (
MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
break;
case BasicHttpSecurityMode.TransportWithMessageCredential:
if (Security.Message.ClientCredentialType != BasicHttpMessageCredentialType.Certificate)
// FIXME: pass proper security token parameters.
element = SecurityBindingElement.CreateCertificateOverTransportBindingElement ();
else
element = new AsymmetricSecurityBindingElement ();
break;
#endif
default:
return null;
}
#if !NET_2_1
element.SetKeyDerivation (false);
element.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
#endif
return element;
}
MessageEncodingBindingElement BuildMessageEncodingBindingElement ()
{
if (MessageEncoding == WSMessageEncoding.Text) {
TextMessageEncodingBindingElement tm = new TextMessageEncodingBindingElement (
MessageVersion.CreateVersion (EnvelopeVersion, AddressingVersion.None), TextEncoding);
#if !NET_2_1
ReaderQuotas.CopyTo (tm.ReaderQuotas);
#endif
return tm;
}
else
#if NET_2_1
throw new SystemException ("INTERNAL ERROR: should not happen");
#else
return new MtomMessageEncodingBindingElement (
MessageVersion.CreateVersion (EnvelopeVersion, AddressingVersion.None), TextEncoding);
#endif
}
TransportBindingElement GetTransport ()
{
HttpTransportBindingElement h;
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
case BasicHttpSecurityMode.TransportWithMessageCredential:
h = new HttpsTransportBindingElement ();
break;
default:
h = new HttpTransportBindingElement ();
break;
}
h.AllowCookies = AllowCookies;
h.BypassProxyOnLocal = BypassProxyOnLocal;
h.HostNameComparisonMode = HostNameComparisonMode;
h.MaxBufferPoolSize = MaxBufferPoolSize;
h.MaxBufferSize = MaxBufferSize;
h.MaxReceivedMessageSize = MaxReceivedMessageSize;
h.ProxyAddress = ProxyAddress;
h.UseDefaultWebProxy = UseDefaultWebProxy;
h.TransferMode = TransferMode;
#if NET_4_0
h.ExtendedProtectionPolicy = Security.Transport.ExtendedProtectionPolicy;
#endif
#if !NET_2_1 || MOBILE
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
break;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
(h as HttpsTransportBindingElement).RequireClientCertificate = true;
break;
case BasicHttpSecurityMode.TransportCredentialOnly:
throw new InvalidOperationException ("Certificate-based client authentication is not supported by 'TransportCredentialOnly' mode.");
}
break;
}
#endif
return h;
}
// explicit interface implementations
bool IBindingRuntimePreferences.ReceiveSynchronously {
get { return false; }
}
}
}
#endif

View File

@ -0,0 +1,215 @@
//
// BasicHttpBinding_4_5.cs
//
// Authors:
// Atsushi Enomoto <atsushi@ximian.com>
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (C) 2005-2006 Novell, Inc. http://www.novell.com
// Copyright 2011-2012 Xamarin Inc (http://www.xamarin.com).
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Xml;
using System.ServiceModel.Configuration;
namespace System.ServiceModel
{
public class BasicHttpBinding : HttpBindingBase,
IBindingRuntimePreferences
{
WSMessageEncoding message_encoding = WSMessageEncoding.Text;
BasicHttpSecurity security;
public BasicHttpBinding ()
: this (BasicHttpSecurityMode.None)
{
}
#if !NET_2_1
public BasicHttpBinding (string configurationName)
: this ()
{
BindingsSection bindingsSection = ConfigUtil.BindingsSection;
BasicHttpBindingElement el =
bindingsSection.BasicHttpBinding.Bindings [configurationName];
el.ApplyConfiguration (this);
}
#endif
public BasicHttpBinding (
BasicHttpSecurityMode securityMode)
{
security = new BasicHttpSecurity (securityMode);
}
public WSMessageEncoding MessageEncoding {
get { return message_encoding; }
set { message_encoding = value; }
}
public override string Scheme {
get {
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
case BasicHttpSecurityMode.TransportWithMessageCredential:
return Uri.UriSchemeHttps;
default:
return Uri.UriSchemeHttp;
}
}
}
public BasicHttpSecurity Security {
get { return security; }
set { security = value; }
}
public override BindingElementCollection
CreateBindingElements ()
{
var list = new List<BindingElement> ();
var security = CreateSecurityBindingElement ();
if (security != null)
list.Add (security);
list.Add (BuildMessageEncodingBindingElement ());
list.Add (GetTransport ());
return new BindingElementCollection (list.ToArray ());
}
SecurityBindingElement CreateSecurityBindingElement ()
{
SecurityBindingElement element;
switch (Security.Mode) {
case BasicHttpSecurityMode.Message:
#if NET_2_1
throw new NotImplementedException ();
#else
if (Security.Message.ClientCredentialType != BasicHttpMessageCredentialType.Certificate)
throw new InvalidOperationException ("When Message security is enabled in a BasicHttpBinding, the message security credential type must be BasicHttpMessageCredentialType.Certificate.");
element = SecurityBindingElement.CreateMutualCertificateBindingElement (
MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
break;
#endif
case BasicHttpSecurityMode.TransportWithMessageCredential:
#if NET_2_1
throw new NotImplementedException ();
#else
if (Security.Message.ClientCredentialType != BasicHttpMessageCredentialType.Certificate)
// FIXME: pass proper security token parameters.
element = SecurityBindingElement.CreateCertificateOverTransportBindingElement ();
else
element = new AsymmetricSecurityBindingElement ();
break;
#endif
default:
return null;
}
#if !NET_2_1
element.SetKeyDerivation (false);
element.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
#endif
return element;
}
MessageEncodingBindingElement BuildMessageEncodingBindingElement ()
{
if (MessageEncoding == WSMessageEncoding.Text) {
TextMessageEncodingBindingElement tm = new TextMessageEncodingBindingElement (
MessageVersion.CreateVersion (EnvelopeVersion, AddressingVersion.None), TextEncoding);
ReaderQuotas.CopyTo (tm.ReaderQuotas);
return tm;
} else {
#if NET_2_1
throw new NotImplementedException ();
#else
return new MtomMessageEncodingBindingElement (
MessageVersion.CreateVersion (EnvelopeVersion, AddressingVersion.None), TextEncoding);
#endif
}
}
TransportBindingElement GetTransport ()
{
HttpTransportBindingElement h;
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
case BasicHttpSecurityMode.TransportWithMessageCredential:
h = new HttpsTransportBindingElement ();
break;
default:
h = new HttpTransportBindingElement ();
break;
}
h.AllowCookies = AllowCookies;
h.BypassProxyOnLocal = BypassProxyOnLocal;
h.HostNameComparisonMode = HostNameComparisonMode;
h.MaxBufferPoolSize = MaxBufferPoolSize;
h.MaxBufferSize = MaxBufferSize;
h.MaxReceivedMessageSize = MaxReceivedMessageSize;
h.ProxyAddress = ProxyAddress;
h.UseDefaultWebProxy = UseDefaultWebProxy;
h.TransferMode = TransferMode;
#if NET_4_0
h.ExtendedProtectionPolicy = Security.Transport.ExtendedProtectionPolicy;
#endif
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
break;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
switch (Security.Mode) {
case BasicHttpSecurityMode.Transport:
(h as HttpsTransportBindingElement).RequireClientCertificate = true;
break;
case BasicHttpSecurityMode.TransportCredentialOnly:
throw new InvalidOperationException ("Certificate-based client authentication is not supported by 'TransportCredentialOnly' mode.");
}
break;
}
return h;
}
}
}

View File

@ -0,0 +1,58 @@
//
// BasicHttpMessageSecurity.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006 Novell, Inc. http://www.novell.com
// Copyright 2011 Xamarin Inc (http://www.xamarin.com).
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net.Security;
using System.ServiceModel.Security;
namespace System.ServiceModel
{
[MonoTODO]
public sealed class BasicHttpMessageSecurity
{
internal BasicHttpMessageSecurity ()
{
}
#if !MOBILE
SecurityAlgorithmSuite alg = SecurityAlgorithmSuite.Default;
public SecurityAlgorithmSuite AlgorithmSuite {
get { return alg; }
set { alg = value; }
}
#endif
BasicHttpMessageCredentialType ctype;
public BasicHttpMessageCredentialType ClientCredentialType {
get { return ctype; }
set { ctype = value; }
}
}
}

View File

@ -0,0 +1,75 @@
//
// BasicHttpSecurity.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net.Security;
using System.ServiceModel.Channels;
namespace System.ServiceModel
{
public sealed class BasicHttpSecurity
{
#if NET_4_0
public BasicHttpSecurity ()
{
this.mode = BasicHttpSecurityMode.None;
this.message = new BasicHttpMessageSecurity ();
this.transport = new HttpTransportSecurity ();
}
#endif
internal BasicHttpSecurity (BasicHttpSecurityMode mode)
{
this.mode = mode;
this.message = new BasicHttpMessageSecurity ();
this.transport = new HttpTransportSecurity ();
}
BasicHttpMessageSecurity message;
BasicHttpSecurityMode mode;
HttpTransportSecurity transport;
public BasicHttpMessageSecurity Message {
get { return message; }
#if NET_4_0
set { message = value; }
#endif
}
public BasicHttpSecurityMode Mode {
get { return mode; }
set { mode = value; }
}
public HttpTransportSecurity Transport {
get { return transport; }
#if NET_4_0
set { transport = value; }
#endif
}
}
}

View File

@ -0,0 +1,181 @@
//
// BasicHttpsBinding.cs
//
// Authors:
// Atsushi Enomoto <atsushi@ximian.com>
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (C) 2005-2006 Novell, Inc. http://www.novell.com
// Copyright 2011-2012 Xamarin Inc (http://www.xamarin.com).
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Security;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Xml;
using System.ServiceModel.Configuration;
namespace System.ServiceModel
{
public class BasicHttpsBinding : HttpBindingBase,
IBindingRuntimePreferences
{
WSMessageEncoding message_encoding = WSMessageEncoding.Text;
BasicHttpsSecurity security;
public BasicHttpsBinding ()
: this (BasicHttpsSecurityMode.Transport)
{
}
#if !NET_2_1
public BasicHttpsBinding (string configurationName)
: this ()
{
BindingsSection bindingsSection = ConfigUtil.BindingsSection;
BasicHttpsBindingElement el =
bindingsSection.BasicHttpsBinding.Bindings [configurationName];
el.ApplyConfiguration (this);
}
#endif
public BasicHttpsBinding (
BasicHttpsSecurityMode securityMode)
{
security = new BasicHttpsSecurity (securityMode);
}
public WSMessageEncoding MessageEncoding {
get { return message_encoding; }
set { message_encoding = value; }
}
public override string Scheme {
get { return Uri.UriSchemeHttps; }
}
public BasicHttpsSecurity Security {
get { return security; }
}
public override BindingElementCollection
CreateBindingElements ()
{
var list = new List<BindingElement> ();
var security = CreateSecurityBindingElement ();
if (security != null)
list.Add (security);
list.Add (BuildMessageEncodingBindingElement ());
list.Add (GetTransport ());
return new BindingElementCollection (list.ToArray ());
}
SecurityBindingElement CreateSecurityBindingElement ()
{
SecurityBindingElement element;
switch (Security.Mode) {
case BasicHttpsSecurityMode.TransportWithMessageCredential:
#if NET_2_1
throw new NotImplementedException ();
#else
if (Security.Message.ClientCredentialType != BasicHttpMessageCredentialType.Certificate)
// FIXME: pass proper security token parameters.
element = SecurityBindingElement.CreateCertificateOverTransportBindingElement ();
else
element = new AsymmetricSecurityBindingElement ();
break;
#endif
default:
return null;
}
#if !NET_2_1
element.SetKeyDerivation (false);
element.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
#endif
return element;
}
MessageEncodingBindingElement BuildMessageEncodingBindingElement ()
{
if (MessageEncoding == WSMessageEncoding.Text) {
TextMessageEncodingBindingElement tm = new TextMessageEncodingBindingElement (
MessageVersion.CreateVersion (EnvelopeVersion, AddressingVersion.None), TextEncoding);
ReaderQuotas.CopyTo (tm.ReaderQuotas);
return tm;
} else {
#if NET_2_1
throw new NotImplementedException ();
#else
return new MtomMessageEncodingBindingElement (
MessageVersion.CreateVersion (EnvelopeVersion, AddressingVersion.None), TextEncoding);
#endif
}
}
TransportBindingElement GetTransport ()
{
HttpsTransportBindingElement h = new HttpsTransportBindingElement ();
h.AllowCookies = AllowCookies;
h.BypassProxyOnLocal = BypassProxyOnLocal;
h.HostNameComparisonMode = HostNameComparisonMode;
h.MaxBufferPoolSize = MaxBufferPoolSize;
h.MaxBufferSize = MaxBufferSize;
h.MaxReceivedMessageSize = MaxReceivedMessageSize;
h.ProxyAddress = ProxyAddress;
h.UseDefaultWebProxy = UseDefaultWebProxy;
h.TransferMode = TransferMode;
#if NET_4_0
h.ExtendedProtectionPolicy = Security.Transport.ExtendedProtectionPolicy;
#endif
switch (Security.Transport.ClientCredentialType) {
case HttpClientCredentialType.Basic:
h.AuthenticationScheme = AuthenticationSchemes.Basic;
break;
case HttpClientCredentialType.Ntlm:
h.AuthenticationScheme = AuthenticationSchemes.Ntlm;
break;
case HttpClientCredentialType.Windows:
h.AuthenticationScheme = AuthenticationSchemes.Negotiate;
break;
case HttpClientCredentialType.Digest:
h.AuthenticationScheme = AuthenticationSchemes.Digest;
break;
case HttpClientCredentialType.Certificate:
h.RequireClientCertificate = true;
break;
}
return h;
}
}
}

View File

@ -0,0 +1,69 @@
//
// BasicHttpsSecurity.cs
//
// Authors:
// Atsushi Enomoto <atsushi@ximian.com>
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (C) 2006 Novell, Inc. http://www.novell.com
// Copyright 2012 Xamarin Inc (http://www.xamarin.com).
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net.Security;
using System.ServiceModel.Channels;
namespace System.ServiceModel
{
public sealed class BasicHttpsSecurity
{
public BasicHttpsSecurity ()
{
this.mode = BasicHttpsSecurityMode.Transport;
this.message = new BasicHttpMessageSecurity ();
this.transport = new HttpTransportSecurity ();
}
internal BasicHttpsSecurity (BasicHttpsSecurityMode mode)
{
this.mode = mode;
this.message = new BasicHttpMessageSecurity ();
this.transport = new HttpTransportSecurity ();
}
BasicHttpMessageSecurity message;
BasicHttpsSecurityMode mode;
HttpTransportSecurity transport;
public BasicHttpMessageSecurity Message {
get { return message; }
}
public BasicHttpsSecurityMode Mode {
get { return mode; }
set { mode = value; }
}
public HttpTransportSecurity Transport {
get { return transport; }
}
}
}

View File

@ -0,0 +1,109 @@
//
// CallbackBehaviorAttribute.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006,2009 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Transactions;
namespace System.ServiceModel
{
[AttributeUsage (AttributeTargets.Class)]
public sealed class CallbackBehaviorAttribute : Attribute,
IEndpointBehavior
{
public CallbackBehaviorAttribute ()
{
AutomaticSessionShutdown = true;
ConcurrencyMode = ConcurrencyMode.Single;
// LAMESPEC: it is documented as int.MaxValue, but wrong.
MaxItemsInObjectGraph = 0x10000;
UseSynchronizationContext = true;
ValidateMustUnderstand = true;
TransactionIsolationLevel = IsolationLevel.Unspecified;
}
[MonoTODO]
public bool AutomaticSessionShutdown { get; set; }
[MonoTODO]
public ConcurrencyMode ConcurrencyMode { get; set; }
[MonoTODO]
public bool IgnoreExtensionDataObject { get; set; }
[MonoTODO]
public bool IncludeExceptionDetailInFaults { get; set; }
[MonoTODO]
public int MaxItemsInObjectGraph { get; set; }
[MonoTODO]
public IsolationLevel TransactionIsolationLevel { get; set; }
[MonoTODO]
public string TransactionTimeout { get; set; }
[MonoTODO]
public bool UseSynchronizationContext { get; set; }
[MonoTODO]
public bool ValidateMustUnderstand { get; set; }
void IEndpointBehavior.AddBindingParameters (
ServiceEndpoint endpoint,
BindingParameterCollection parameters)
{
}
void IEndpointBehavior.ApplyDispatchBehavior (
ServiceEndpoint serviceEndpoint,
EndpointDispatcher dispatcher)
{
throw new InvalidOperationException ("This attribute cannot be applied to service endpoint dispatcher");
}
[MonoTODO]
void IEndpointBehavior.ApplyClientBehavior (
ServiceEndpoint serviceEndpoint,
ClientRuntime behavior)
{
if (serviceEndpoint.Contract.CallbackContractType == null)
throw new InvalidOperationException ("This attribute can be applied only to duplex service endpoint");
throw new NotImplementedException ();
}
[MonoTODO]
void IEndpointBehavior.Validate (
ServiceEndpoint serviceEndpoint)
{
throw new NotImplementedException ();
}
}
}

View File

@ -0,0 +1 @@
6c3d35532b4482669445418747f8b9439b7ab2a9

View File

@ -0,0 +1,403 @@
//
// ChannelFactory.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.Configuration;
using System.ServiceModel.Configuration;
using System.Xml;
namespace System.ServiceModel
{
public abstract class ChannelFactory : CommunicationObject,
IChannelFactory, ICommunicationObject, IDisposable
{
// instance members
ServiceEndpoint service_endpoint;
IChannelFactory factory;
List<IClientChannel> opened_channels = new List<IClientChannel> ();
protected ChannelFactory ()
{
}
internal IChannelFactory OpenedChannelFactory {
get {
if (factory == null) {
factory = CreateFactory ();
factory.Open ();
}
return factory;
}
private set {
factory = value;
}
}
internal List<IClientChannel> OpenedChannels {
get { return opened_channels; }
}
public ServiceEndpoint Endpoint {
get { return service_endpoint; }
}
public ClientCredentials Credentials {
get { return Endpoint.Behaviors.Find<ClientCredentials> (); }
}
protected internal override TimeSpan DefaultCloseTimeout {
get { return Endpoint.Binding.CloseTimeout; }
}
protected internal override TimeSpan DefaultOpenTimeout {
get { return Endpoint.Binding.OpenTimeout; }
}
protected virtual void ApplyConfiguration (string endpointConfig)
{
if (endpointConfig == null)
return;
#if NET_2_1
try {
// It should automatically use XmlXapResolver
var cfg = new SilverlightClientConfigLoader ().Load (XmlReader.Create ("ServiceReferences.ClientConfig"));
SilverlightClientConfigLoader.ServiceEndpointConfiguration se = null;
if (endpointConfig == "*")
se = cfg.GetServiceEndpointConfiguration (Endpoint.Contract.Name);
if (se == null)
se = cfg.GetServiceEndpointConfiguration (endpointConfig);
if (se.Binding != null && Endpoint.Binding == null)
Endpoint.Binding = se.Binding;
else // ignore it
Console.WriteLine ("WARNING: Configured binding not found in configuration {0}", endpointConfig);
if (se.Address != null && Endpoint.Address == null)
Endpoint.Address = se.Address;
else // ignore it
Console.WriteLine ("WARNING: Configured endpoint address not found in configuration {0}", endpointConfig);
} catch (Exception) {
// ignore it.
Console.WriteLine ("WARNING: failed to load endpoint configuration for {0}", endpointConfig);
}
#else
string contractName = Endpoint.Contract.ConfigurationName;
ClientSection client = ConfigUtil.ClientSection;
ChannelEndpointElement endpoint = null;
foreach (ChannelEndpointElement el in client.Endpoints) {
if (el.Contract == contractName && (endpointConfig == el.Name || endpointConfig == "*")) {
if (endpoint != null)
throw new InvalidOperationException (String.Format ("More then one endpoint matching contract {0} was found.", contractName));
endpoint = el;
}
}
if (endpoint == null)
throw new InvalidOperationException (String.Format ("Client endpoint configuration '{0}' was not found in {1} endpoints.", endpointConfig, client.Endpoints.Count));
#if NET_4_0
var binding = String.IsNullOrEmpty (endpoint.Binding) ? null : ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration);
var contractType = ConfigUtil.GetTypeFromConfigString (endpoint.Contract, NamedConfigCategory.Contract);
if (contractType == null)
throw new ArgumentException (String.Format ("Contract '{0}' was not found", endpoint.Contract));
var contract = String.IsNullOrEmpty (endpoint.Contract) ? Endpoint.Contract : ContractDescription.GetContract (contractType);
if (!String.IsNullOrEmpty (endpoint.Kind)) {
var se = ConfigUtil.ConfigureStandardEndpoint (contract, endpoint);
if (se.Binding == null)
se.Binding = binding;
if (se.Address == null && se.Binding != null) // standard endpoint might have empty address
se.Address = new EndpointAddress (endpoint.Address);
if (se.Binding == null && se.Address != null) // look for protocol mapping
se.Binding = ConfigUtil.GetBindingByProtocolMapping (se.Address.Uri);
service_endpoint = se;
} else {
if (binding == null && endpoint.Address != null) // look for protocol mapping
Endpoint.Binding = ConfigUtil.GetBindingByProtocolMapping (endpoint.Address);
}
#endif
if (Endpoint.Binding == null)
Endpoint.Binding = ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration);
if (Endpoint.Address == null)
Endpoint.Address = new EndpointAddress (endpoint.Address);
if (endpoint.BehaviorConfiguration != "")
ApplyBehavior (endpoint.BehaviorConfiguration);
#endif
}
#if !NET_2_1
private void ApplyBehavior (string behaviorConfig)
{
BehaviorsSection behaviorsSection = ConfigUtil.BehaviorsSection;
EndpointBehaviorElement behaviorElement = behaviorsSection.EndpointBehaviors [behaviorConfig];
int i = 0;
foreach (BehaviorExtensionElement el in behaviorElement) {
IEndpointBehavior behavior = (IEndpointBehavior) el.CreateBehavior ();
Endpoint.Behaviors.Remove (behavior.GetType ());
Endpoint.Behaviors.Add (behavior);
}
}
#endif
protected virtual IChannelFactory CreateFactory ()
{
bool isOneWay = true; // check OperationDescription.IsOneWay
foreach (var od in Endpoint.Contract.Operations)
if (!od.IsOneWay) {
isOneWay = false;
break;
}
BindingParameterCollection pl = CreateBindingParameters ();
// the assumption on the type of created channel could
// be wrong, but would mostly fit the actual
// requirements. No books have explained how it is done.
// try duplex
switch (Endpoint.Contract.SessionMode) {
case SessionMode.Required:
if (Endpoint.Binding.CanBuildChannelFactory<IDuplexSessionChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IDuplexSessionChannel> (pl);
break;
case SessionMode.Allowed:
if (Endpoint.Binding.CanBuildChannelFactory<IDuplexChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IDuplexChannel> (pl);
if (Endpoint.Binding.CanBuildChannelFactory<IDuplexSessionChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IDuplexSessionChannel> (pl);
break;
default:
if (Endpoint.Binding.CanBuildChannelFactory<IDuplexChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IDuplexChannel> (pl);
break;
}
if (Endpoint.Contract.CallbackContractType != null)
throw new InvalidOperationException ("The binding does not support duplex channel types that the contract requies for CallbackContractType.");
if (isOneWay) {
switch (Endpoint.Contract.SessionMode) {
case SessionMode.Required:
if (Endpoint.Binding.CanBuildChannelFactory<IOutputSessionChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IOutputSessionChannel> (pl);
if (Endpoint.Binding.CanBuildChannelFactory<IDuplexSessionChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IDuplexSessionChannel> (pl);
break;
case SessionMode.Allowed:
if (Endpoint.Binding.CanBuildChannelFactory<IOutputChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IOutputChannel> (pl);
if (Endpoint.Binding.CanBuildChannelFactory<IDuplexChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IDuplexChannel> (pl);
goto case SessionMode.Required;
default:
if (Endpoint.Binding.CanBuildChannelFactory<IOutputChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IOutputChannel> (pl);
if (Endpoint.Binding.CanBuildChannelFactory<IDuplexChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IDuplexChannel> (pl);
break;
}
}
// both OneWay and non-OneWay contracts fall into here.
{
switch (Endpoint.Contract.SessionMode) {
case SessionMode.Required:
if (Endpoint.Binding.CanBuildChannelFactory<IRequestSessionChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IRequestSessionChannel> (pl);
break;
case SessionMode.Allowed:
if (Endpoint.Binding.CanBuildChannelFactory<IRequestChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IRequestChannel> (pl);
if (Endpoint.Binding.CanBuildChannelFactory<IRequestSessionChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IRequestSessionChannel> (pl);
break;
default:
if (Endpoint.Binding.CanBuildChannelFactory<IRequestChannel> (pl))
return Endpoint.Binding.BuildChannelFactory<IRequestChannel> (pl);
break;
}
}
throw new InvalidOperationException (String.Format ("The binding does not support any of the channel types that the contract '{0}' allows.", Endpoint.Contract.Name));
}
BindingParameterCollection CreateBindingParameters ()
{
BindingParameterCollection pl =
new BindingParameterCollection ();
ContractDescription cd = Endpoint.Contract;
#if !NET_2_1
pl.Add (ChannelProtectionRequirements.CreateFromContract (cd));
#endif
foreach (IEndpointBehavior behavior in Endpoint.Behaviors)
behavior.AddBindingParameters (Endpoint, pl);
return pl;
}
protected abstract ServiceEndpoint CreateDescription ();
void IDisposable.Dispose ()
{
Close ();
}
public T GetProperty<T> () where T : class
{
if (OpenedChannelFactory != null)
return OpenedChannelFactory.GetProperty<T> ();
return null;
}
protected void EnsureOpened ()
{
if (Endpoint == null)
throw new InvalidOperationException ("A service endpoint must be configured for this channel factory");
if (Endpoint.Contract == null)
throw new InvalidOperationException ("A service Contract must be configured for this channel factory");
if (Endpoint.Binding == null)
throw new InvalidOperationException ("A Binding must be configured for this channel factory");
if (State != CommunicationState.Opened)
Open ();
}
protected void InitializeEndpoint (
string endpointConfigurationName,
EndpointAddress remoteAddress)
{
InitializeEndpoint (CreateDescription ());
if (remoteAddress != null)
service_endpoint.Address = remoteAddress;
ApplyConfiguration (endpointConfigurationName);
}
protected void InitializeEndpoint (Binding binding,
EndpointAddress remoteAddress)
{
InitializeEndpoint (CreateDescription ());
if (binding != null)
service_endpoint.Binding = binding;
if (remoteAddress != null)
service_endpoint.Address = remoteAddress;
}
protected void InitializeEndpoint (ServiceEndpoint endpoint)
{
if (endpoint == null)
throw new ArgumentNullException ("endpoint");
service_endpoint = endpoint;
}
protected override void OnAbort ()
{
if (OpenedChannelFactory != null)
OpenedChannelFactory.Abort ();
}
Action<TimeSpan> close_delegate;
Action<TimeSpan> open_delegate;
protected override IAsyncResult OnBeginClose (
TimeSpan timeout, AsyncCallback callback, object state)
{
if (close_delegate == null)
close_delegate = new Action<TimeSpan> (OnClose);
return close_delegate.BeginInvoke (timeout, callback, state);
}
protected override IAsyncResult OnBeginOpen (
TimeSpan timeout, AsyncCallback callback, object state)
{
if (open_delegate == null)
open_delegate = new Action<TimeSpan> (OnClose);
return open_delegate.BeginInvoke (timeout, callback, state);
}
protected override void OnEndClose (IAsyncResult result)
{
if (close_delegate == null)
throw new InvalidOperationException ("Async close operation has not started");
close_delegate.EndInvoke (result);
}
protected override void OnEndOpen (IAsyncResult result)
{
if (open_delegate == null)
throw new InvalidOperationException ("Async close operation has not started");
open_delegate.EndInvoke (result);
}
protected override void OnClose (TimeSpan timeout)
{
DateTime start = DateTime.Now;
foreach (var ch in opened_channels.ToArray ())
ch.Close (timeout - (DateTime.Now - start));
if (OpenedChannelFactory != null)
OpenedChannelFactory.Close (timeout - (DateTime.Now - start));
}
protected override void OnOpen (TimeSpan timeout)
{
}
protected override void OnOpening ()
{
base.OnOpening ();
OpenedChannelFactory = CreateFactory ();
}
protected override void OnOpened ()
{
base.OnOpened ();
OpenedChannelFactory.Open ();
}
}
#if obsolete
[ServiceContract]
interface UninitializedContract
{
[OperationContract]
void ItShouldReallyGone ();
}
#endif
}

View File

@ -0,0 +1,199 @@
//
// generic ChannelFactory_1.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.Remoting;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.MonoInternal;
namespace System.ServiceModel
{
// LAMESPEC: TChannel should have been defined as "where TChannel : IClientChannel".
// The returned channel is actually used as IClientChannel.
// (That's also likely why the type parameter name is TChannel, not TContract.)
public class ChannelFactory<TChannel>
: ChannelFactory, IChannelFactory<TChannel>
{
public ChannelFactory ()
{
}
protected ChannelFactory (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
if (!type.IsInterface)
throw new InvalidOperationException ("The type argument to the generic ChannelFactory constructor must be an interface type.");
InitializeEndpoint (CreateDescription ());
}
public ChannelFactory (string endpointConfigurationName)
{
if (endpointConfigurationName == null)
throw new ArgumentNullException ("endpointConfigurationName");
InitializeEndpoint (endpointConfigurationName, null);
}
public ChannelFactory (string endpointConfigurationName,
EndpointAddress remoteAddress)
{
if (endpointConfigurationName == null)
throw new ArgumentNullException ("endpointConfigurationName");
InitializeEndpoint (endpointConfigurationName, remoteAddress);
}
public ChannelFactory (ServiceEndpoint endpoint)
{
if (endpoint == null)
throw new ArgumentNullException ("serviceEndpoint");
InitializeEndpoint (endpoint);
}
public ChannelFactory (Binding binding, string remoteAddress)
: this (binding, new EndpointAddress (remoteAddress))
{
}
public ChannelFactory (Binding binding)
: this (binding, (EndpointAddress) null)
{
}
public ChannelFactory (Binding binding, EndpointAddress remoteAddress)
: this (typeof (TChannel))
{
if (binding == null)
throw new ArgumentNullException ();
Endpoint.Binding = binding;
Endpoint.Address = remoteAddress;
}
internal object OwnerClientBase { get; set; }
public TChannel CreateChannel ()
{
EnsureOpened ();
return CreateChannel (Endpoint.Address);
}
public TChannel CreateChannel (EndpointAddress address)
{
return CreateChannel (address, null);
}
static TChannel CreateChannelCore (ChannelFactory<TChannel> cf, Func<ChannelFactory<TChannel>, TChannel> f)
{
var ch = f (cf);
((ICommunicationObject) (object) ch).Closed += delegate {
if (cf.State == CommunicationState.Opened)
cf.Close ();
};
return ch;
}
public static TChannel CreateChannel (Binding binding, EndpointAddress address)
{
return CreateChannelCore (new ChannelFactory<TChannel> (binding, address), f => f.CreateChannel ());
}
public static TChannel CreateChannel (Binding binding, EndpointAddress address, Uri via)
{
return CreateChannelCore (new ChannelFactory<TChannel> (binding), f => f.CreateChannel (address, via));
}
public virtual TChannel CreateChannel (EndpointAddress address, Uri via)
{
#if FULL_AOT_RUNTIME
throw new InvalidOperationException ("MonoTouch does not support dynamic proxy code generation. Override this method or its caller to return specific client proxy instance");
#else
var existing = Endpoint.Address;
try {
Endpoint.Address = address;
EnsureOpened ();
Endpoint.Validate ();
#if DISABLE_REAL_PROXY
Type type = ClientProxyGenerator.CreateProxyType (typeof (TChannel), Endpoint.Contract, false);
// in .NET and SL2, it seems that the proxy is RealProxy.
// But since there is no remoting in SL2 (and we have
// no special magic), we have to use different approach
// that should work either.
var proxy = (IClientChannel) Activator.CreateInstance (type, new object [] {Endpoint, this, address ?? Endpoint.Address, via});
#else
var proxy = (IClientChannel) new ClientRealProxy (typeof (TChannel), new ClientRuntimeChannel (Endpoint, this, address ?? Endpoint.Address, via), false).GetTransparentProxy ();
#endif
proxy.Opened += delegate {
OpenedChannels.Add (proxy);
};
proxy.Closing += delegate {
OpenedChannels.Remove (proxy);
};
return (TChannel) proxy;
} catch (TargetInvocationException ex) {
if (ex.InnerException != null)
throw ex.InnerException;
else
throw;
} finally {
Endpoint.Address = existing;
}
#endif
}
protected static TChannel CreateChannel (string endpointConfigurationName)
{
return CreateChannelCore (new ChannelFactory<TChannel> (endpointConfigurationName), f => f.CreateChannel ());
}
protected override ServiceEndpoint CreateDescription ()
{
ContractDescription cd = ContractDescription.GetContract (typeof (TChannel));
ServiceEndpoint ep = new ServiceEndpoint (cd);
ep.Behaviors.Add (new ClientCredentials ());
return ep;
}
}
class DummyClientBase<T> : ClientBase<T> where T : class
{
public DummyClientBase (ChannelFactory<T> factory)
: base (factory)
{
}
}
}

View File

@ -0,0 +1,43 @@
//
// ChannelTerminatedException.cs
//
// Author: Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace System.ServiceModel
{
[Serializable]
public class ChannelTerminatedException : CommunicationException
{
public ChannelTerminatedException () : base () {}
public ChannelTerminatedException (string msg) : base (msg) {}
public ChannelTerminatedException (string msg, Exception inner) : base (msg, inner) {}
protected ChannelTerminatedException (SerializationInfo info, StreamingContext context) :
base (info, context) {}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,345 @@
//
// ClientCredentialsSecurityTokenManager.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net.Security;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using ReqType = System.ServiceModel.Security.Tokens.ServiceModelSecurityTokenRequirement;
namespace System.ServiceModel
{
[MonoTODO]
public class ClientCredentialsSecurityTokenManager : SecurityTokenManager
{
ClientCredentials credentials;
public ClientCredentialsSecurityTokenManager (ClientCredentials credentials)
{
if (credentials == null)
throw new ArgumentNullException ("credentials");
this.credentials = credentials;
}
public ClientCredentials ClientCredentials {
get { return credentials; }
}
[MonoTODO]
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator (
SecurityTokenRequirement requirement,
out SecurityTokenResolver outOfBandTokenResolver)
{
outOfBandTokenResolver = null;
if (requirement == null)
throw new ArgumentNullException ("requirement");
if (requirement.TokenType == SecurityTokenTypes.UserName) {
// unsupported
}
else if (requirement.TokenType == SecurityTokenTypes.Rsa)
return new RsaSecurityTokenAuthenticator ();
else if (requirement.TokenType == SecurityTokenTypes.X509Certificate)
return CreateX509Authenticator (requirement);
else if (requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego)
return new SspiClientSecurityTokenAuthenticator (this, requirement);
else
throw new NotImplementedException ("Security token type " + requirement.TokenType);
throw new NotSupportedException (String.Format ("Security token requirement '{0}' is not supported to create SecurityTokenAuthenticator.", requirement));
}
X509SecurityTokenAuthenticator CreateX509Authenticator (SecurityTokenRequirement requirement)
{
X509CertificateRecipientClientCredential c = ClientCredentials.ServiceCertificate;
switch (c.Authentication.CertificateValidationMode) {
case X509CertificateValidationMode.Custom:
if (c.Authentication.CustomCertificateValidator == null)
throw new InvalidOperationException ("For Custom certificate validation mode, CustomCertificateValidator is required to create a token authenticator for X509 certificate.");
return new X509SecurityTokenAuthenticator (c.Authentication.CustomCertificateValidator);
case X509CertificateValidationMode.None:
return new X509SecurityTokenAuthenticator (X509CertificateValidator.None);
case X509CertificateValidationMode.PeerOrChainTrust:
return new X509SecurityTokenAuthenticator (X509CertificateValidator.PeerOrChainTrust);
case X509CertificateValidationMode.ChainTrust:
return new X509SecurityTokenAuthenticator (X509CertificateValidator.ChainTrust);
default:
return new X509SecurityTokenAuthenticator (X509CertificateValidator.PeerTrust);
}
}
#region CreateSecurityTokenProvider()
[MonoTODO]
public override SecurityTokenProvider CreateSecurityTokenProvider (SecurityTokenRequirement requirement)
{
if (IsIssuedSecurityTokenRequirement (requirement))
return CreateIssuedTokenProvider (requirement);
bool isInitiator;
// huh, they are not constants but properties.
if (requirement.TokenType == SecurityTokenTypes.X509Certificate)
return CreateX509SecurityTokenProvider (requirement);
else if (requirement.TokenType == ServiceModelSecurityTokenTypes.SecureConversation)
return CreateSecureConversationProvider (requirement);
else if (requirement.TokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego) {
if (requirement.TryGetProperty<bool> (ReqType.IsInitiatorProperty, out isInitiator) && isInitiator)
return CreateSslnegoProvider (requirement);
} else if (requirement.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego) {
if (requirement.TryGetProperty<bool> (ReqType.IsInitiatorProperty, out isInitiator) && isInitiator)
return CreateSslnegoProvider (requirement);
} else if (requirement.TokenType == ServiceModelSecurityTokenTypes.SecurityContext) {
// FIXME: implement
} else if (requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego) {
return CreateSpnegoProvider (requirement);
} else if (requirement.TokenType == ServiceModelSecurityTokenTypes.SspiCredential) {
// FIXME: implement
} else if (requirement.TokenType == SecurityTokenTypes.Rsa) {
// FIXME: implement
} else if (requirement.TokenType == SecurityTokenTypes.Saml) {
// FIXME: implement
} else if (requirement.TokenType == SecurityTokenTypes.UserName)
return CreateUserNameProvider (requirement);
else if (requirement.TokenType == SecurityTokenTypes.Kerberos) {
return CreateKerberosProvider (requirement);
}
throw new NotSupportedException (String.Format ("Token type '{0}' is not supported", requirement.TokenType));
}
UserNameSecurityTokenProvider CreateUserNameProvider (
SecurityTokenRequirement requirement)
{
UserNamePasswordClientCredential c =
credentials.UserName;
if (c.UserName == null)
throw new InvalidOperationException ("User name is not specified in ClientCredentials.");
UserNameSecurityTokenProvider p =
new UserNameSecurityTokenProvider (c.UserName, c.Password);
return p;
}
KerberosSecurityTokenProvider CreateKerberosProvider (SecurityTokenRequirement requirement)
{
// FIXME: how to get SPN?
return new KerberosSecurityTokenProvider (
"", credentials.Windows.AllowedImpersonationLevel, credentials.Windows.ClientCredential);
}
X509SecurityTokenProvider CreateX509SecurityTokenProvider (SecurityTokenRequirement requirement)
{
// - When the request is as an initiator, then
// - if the purpose is key exchange, then
// the initiator wants the service certificate
// to encrypt the message with its public key.
// - otherwise, the initiator wants the client
// certificate to sign the message with the
// private key.
// - otherwise
// - if the purpose is key exchange, then
// the recipient wants the client certificate
// to encrypt the message with its public key.
// - otherwise, the recipient wants the service
// certificate to sign the message with the
// private key.
bool isInitiator;
if (!requirement.TryGetProperty<bool> (ReqType.IsInitiatorProperty, out isInitiator))
isInitiator = false;
X509Certificate2 cert;
bool isClient;
if (isInitiator)
isClient = requirement.KeyUsage == SecurityKeyUsage.Signature;
else {
if (!requirement.Properties.ContainsKey (SecurityTokenRequirement.KeyUsageProperty))
throw new NotSupportedException (String.Format ("Cannot create a security token provider from this requirement '{0}'", requirement));
isClient = requirement.KeyUsage == SecurityKeyUsage.Exchange;
}
if (isClient)
cert = credentials.ClientCertificate.Certificate;
else
cert = GetServiceCertificate (requirement);
if (cert == null) {
if (isClient)
throw new InvalidOperationException ("Client certificate is not provided in ClientCredentials.");
else
throw new InvalidOperationException ("Service certificate is not provided.");
}
X509SecurityTokenProvider p =
new X509SecurityTokenProvider (cert);
return p;
}
X509Certificate2 GetServiceCertificate (SecurityTokenRequirement requirement)
{
// try X509CertificateEndpointIdentity,
// ServiceCertificate.ScopedCertificate and
// ServiceCertificate.DefaultCertificate.
X509Certificate2 cert = null;
EndpointAddress address = null;
requirement.TryGetProperty (ReqType.TargetAddressProperty, out address);
if (address != null) {
X509CertificateEndpointIdentity ident = address.Identity as X509CertificateEndpointIdentity;
if (ident != null && ident.Certificates.Count > 0)
cert = ident.Certificates [0];
if (cert == null)
credentials.ServiceCertificate.ScopedCertificates.TryGetValue (address.Uri, out cert);
}
if (cert == null)
cert = credentials.ServiceCertificate.DefaultCertificate;
return cert;
}
void InitializeProviderCommunicationObject (ProviderCommunicationObject p, SecurityTokenRequirement r)
{
p.TargetAddress = r.GetProperty<EndpointAddress> (ReqType.TargetAddressProperty);
// FIXME: use it somewhere, probably to build
// IssuerBinding. However, there is also IssuerBinding
// property. SecureConversationSecurityBindingElement
// as well.
SecurityBindingElement sbe =
r.GetProperty<SecurityBindingElement> (ReqType.SecurityBindingElementProperty);
// I doubt the binding is acquired this way ...
Binding binding;
if (!r.TryGetProperty<Binding> (ReqType.IssuerBindingProperty, out binding))
binding = new CustomBinding (
new TextMessageEncodingBindingElement (),
new HttpTransportBindingElement ());
p.IssuerBinding = binding;
// not sure if it is used only for this purpose though ...
BindingContext ctx = r.GetProperty<BindingContext> (ReqType.IssuerBindingContextProperty);
foreach (IEndpointBehavior b in ctx.BindingParameters.FindAll<IEndpointBehavior> ())
p.IssuerChannelBehaviors.Add (b);
SecurityTokenVersion ver =
r.GetProperty<SecurityTokenVersion> (ReqType.MessageSecurityVersionProperty);
p.SecurityTokenSerializer =
CreateSecurityTokenSerializer (ver);
// seems like they are optional here ... (but possibly
// used later)
EndpointAddress address;
if (!r.TryGetProperty<EndpointAddress> (ReqType.IssuerAddressProperty, out address))
address = p.TargetAddress;
p.IssuerAddress = address;
// It is somehow not checked as mandatory ...
SecurityAlgorithmSuite suite = null;
r.TryGetProperty<SecurityAlgorithmSuite> (ReqType.SecurityAlgorithmSuiteProperty, out suite);
p.SecurityAlgorithmSuite = suite;
}
// FIXME: it is far from done.
SecurityTokenProvider CreateSecureConversationProvider (SecurityTokenRequirement r)
{
IssuedSecurityTokenProvider p =
new IssuedSecurityTokenProvider ();
InitializeProviderCommunicationObject (p.Communication, r);
// FIXME: use it somewhere.
int keySize = r.KeySize;
return p;
}
SecurityTokenProvider CreateSslnegoProvider (SecurityTokenRequirement r)
{
SslSecurityTokenProvider p = new SslSecurityTokenProvider (this, r.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego);
InitializeProviderCommunicationObject (p.Communication, r);
return p;
}
SecurityTokenProvider CreateSpnegoProvider (SecurityTokenRequirement r)
{
SpnegoSecurityTokenProvider p = new SpnegoSecurityTokenProvider (this, r);
InitializeProviderCommunicationObject (p.Communication, r);
return p;
}
IssuedSecurityTokenProvider CreateIssuedTokenProvider (SecurityTokenRequirement requirement)
{
IssuedSecurityTokenProvider p =
new IssuedSecurityTokenProvider ();
// FIXME: fill properties
EndpointAddress address;
if (requirement.TryGetProperty<EndpointAddress> (ReqType.IssuerAddressProperty, out address))
p.IssuerAddress = address;
if (requirement.TryGetProperty<EndpointAddress> (ReqType.TargetAddressProperty, out address))
p.TargetAddress = address;
Binding binding;
if (requirement.TryGetProperty<Binding> (ReqType.IssuerBindingProperty, out binding))
p.IssuerBinding = binding;
MessageSecurityVersion ver;
if (requirement.TryGetProperty<MessageSecurityVersion> (ReqType.MessageSecurityVersionProperty, out ver))
p.SecurityTokenSerializer = CreateSecurityTokenSerializer (ver.SecurityVersion);
SecurityAlgorithmSuite suite;
if (requirement.TryGetProperty<SecurityAlgorithmSuite> (ReqType.SecurityAlgorithmSuiteProperty, out suite))
p.SecurityAlgorithmSuite = suite;
return p;
}
#endregion
public override SecurityTokenSerializer CreateSecurityTokenSerializer (SecurityTokenVersion version)
{
bool bsp = version.GetSecuritySpecifications ().Contains (Constants.WSBasicSecurityProfileCore1);
SecurityVersion ver =
version.GetSecuritySpecifications ().Contains (Constants.Wss11Namespace) ?
SecurityVersion.WSSecurity11 :
SecurityVersion.WSSecurity10;
return new WSSecurityTokenSerializer (ver, bsp);
}
protected SecurityTokenSerializer CreateSecurityTokenSerializer (SecurityVersion version)
{
return new WSSecurityTokenSerializer (version);
}
protected internal bool IsIssuedSecurityTokenRequirement (
SecurityTokenRequirement requirement)
{
SecurityTokenParameters ret;
if (!requirement.TryGetProperty<SecurityTokenParameters> (ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty, out ret))
return false;
return ret is IssuedSecurityTokenParameters;
}
}
}

View File

@ -0,0 +1,311 @@
#if DISABLE_REAL_PROXY
//
// ClientProxyGenerator.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2006 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !FULL_AOT_RUNTIME
using System;
using System.Collections.Generic;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Mono.CodeGeneration;
using System.ServiceModel.MonoInternal;
namespace System.ServiceModel
{
internal class ClientProxyKey {
Type contractInterface;
ContractDescription cd;
bool duplex;
public ClientProxyKey (Type contractInterface, ContractDescription cd, bool duplex) {
this.contractInterface = contractInterface;
this.cd = cd;
this.duplex = duplex;
}
public override int GetHashCode () {
return contractInterface.GetHashCode () ^ cd.GetHashCode ();
}
public override bool Equals (object o) {
ClientProxyKey key = o as ClientProxyKey;
if (key == null)
return false;
return contractInterface == key.contractInterface && cd == key.cd && duplex == key.duplex;
}
}
internal class ClientProxyGenerator : ProxyGeneratorBase
{
static Dictionary<ClientProxyKey, Type> proxy_cache = new Dictionary<ClientProxyKey, Type> ();
public static Type CreateProxyType (Type requestedType, ContractDescription cd, bool duplex)
{
ClientProxyKey key = new ClientProxyKey (requestedType, cd, duplex);
Type res;
lock (proxy_cache) {
if (proxy_cache.TryGetValue (key, out res))
return res;
}
string modname = "dummy";
Type crtype =
#if !NET_2_1
duplex ? typeof (DuplexClientRuntimeChannel) :
#endif
typeof (ClientRuntimeChannel);
// public class __clientproxy_MyContract : (Duplex)ClientRuntimeChannel, [ContractType]
var types = new List<Type> ();
types.Add (requestedType);
if (!cd.ContractType.IsAssignableFrom (requestedType))
types.Add (cd.ContractType);
if (cd.CallbackContractType != null && !cd.CallbackContractType.IsAssignableFrom (requestedType))
types.Add (cd.CallbackContractType);
CodeClass c = new CodeModule (modname).CreateClass ("__clientproxy_" + cd.Name, crtype, types.ToArray ());
//
// public __clientproxy_MyContract (
// ServiceEndpoint arg1, ChannelFactory arg2, EndpointAddress arg3, Uri arg4)
// : base (arg1, arg2, arg3, arg4)
// {
// }
//
Type [] ctorargs = new Type [] {typeof (ServiceEndpoint), typeof (ChannelFactory), typeof (EndpointAddress), typeof (Uri)};
CodeMethod ctor = c.CreateConstructor (
MethodAttributes.Public, ctorargs);
CodeBuilder b = ctor.CodeBuilder;
MethodBase baseCtor = crtype.GetConstructors (
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) [0];
if (baseCtor == null) throw new Exception ("INTERNAL ERROR: ClientRuntimeChannel.ctor() was not found.");
b.Call (
ctor.GetThis (),
baseCtor,
new CodeArgumentReference (typeof (ServiceEndpoint), 1, "arg0"),
new CodeArgumentReference (typeof (ChannelFactory), 2, "arg1"),
new CodeArgumentReference (typeof (EndpointAddress), 3, "arg2"),
new CodeArgumentReference (typeof (Uri), 4, "arg3"));
res = CreateProxyTypeOperations (crtype, c, cd);
lock (proxy_cache) {
proxy_cache [key] = res;
}
return res;
}
}
internal class ProxyGeneratorBase
{
protected static Type CreateProxyTypeOperations (Type crtype, CodeClass c, ContractDescription cd)
{
// member implementation
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (OperationDescription od in cd.Operations) {
// FIXME: handle properties and events.
#if !NET_2_1
if (od.SyncMethod != null)
GenerateMethodImpl (c, crtype.GetMethod ("Process", bf), od.Name, od.SyncMethod);
#endif
if (od.BeginMethod != null)
GenerateBeginMethodImpl (c, crtype.GetMethod ("BeginProcess", bf), od.Name, od.BeginMethod);
if (od.EndMethod != null)
GenerateEndMethodImpl (c, crtype.GetMethod ("EndProcess", bf), od.Name, od.EndMethod);
}
Type ret = c.CreateType ();
return ret;
}
static void GenerateMethodImpl (CodeClass c, MethodInfo processMethod, string name, MethodInfo mi)
{
CodeMethod m = c.ImplementMethod (mi);
CodeBuilder b = m.CodeBuilder;
// object [] parameters = new object [x];
// parameters [0] = arg1;
// parameters [1] = arg2;
// ...
// (return) Process (Contract.Operations [operName].SyncMethod, operName, parameters);
ParameterInfo [] pinfos = mi.GetParameters ();
CodeVariableDeclaration paramsDecl = new CodeVariableDeclaration (typeof (object []), "parameters");
b.CurrentBlock.Add (paramsDecl);
CodeVariableReference paramsRef = paramsDecl.Variable;
b.Assign (paramsRef,
new CodeNewArray (typeof (object), new CodeLiteral (pinfos.Length)));
for (int i = 0; i < pinfos.Length; i++) {
ParameterInfo par = pinfos [i];
if (!par.IsOut)
b.Assign (
new CodeArrayItem (paramsRef, new CodeLiteral (i)),
new CodeCast (typeof (object),
new CodeArgumentReference (par.ParameterType, par.Position + 1, "arg" + i)));
}
#if USE_OD_REFERENCE_IN_PROXY
CodePropertyReference argMethodInfo = GetOperationMethod (m, b, name, "SyncMethod");
#else
CodeMethodCall argMethodInfo = new CodeMethodCall (typeof (MethodBase), "GetCurrentMethod");
#endif
CodeLiteral argOperName = new CodeLiteral (name);
CodeVariableReference retValue = null;
if (mi.ReturnType == typeof (void))
b.Call (m.GetThis (), processMethod, argMethodInfo, argOperName, paramsRef);
else {
CodeVariableDeclaration retValueDecl = new CodeVariableDeclaration (mi.ReturnType, "retValue");
b.CurrentBlock.Add (retValueDecl);
retValue = retValueDecl.Variable;
b.Assign (retValue,
new CodeCast (mi.ReturnType,
b.CallFunc (m.GetThis (), processMethod, argMethodInfo, argOperName, paramsRef)));
}
for (int i = 0; i < pinfos.Length; i++) {
ParameterInfo par = pinfos [i];
if (par.IsOut || par.ParameterType.IsByRef)
b.Assign (
new CodeArgumentReference (par.ParameterType, par.Position + 1, "arg" + i),
new CodeCast (par.ParameterType.GetElementType (),
new CodeArrayItem (paramsRef, new CodeLiteral (i))));
}
if (retValue != null)
b.Return (retValue);
}
static CodePropertyReference GetOperationMethod (CodeMethod m, CodeBuilder b, string name, string methodPropertyName)
{
return new CodePropertyReference (
b.CallFunc (
// this.Contract.Operations
new CodePropertyReference (
new CodePropertyReference (
m.GetThis (),
typeof (ClientRuntimeChannel).GetProperty ("Contract")),
typeof (ContractDescription).GetProperty ("Operations")),
// .Find (name)
typeof (OperationDescriptionCollection).GetMethod ("Find"),
new CodeLiteral (name)),
// .SyncMethod
typeof (OperationDescription).GetProperty (methodPropertyName));
}
static void GenerateBeginMethodImpl (CodeClass c, MethodInfo beginProcessMethod, string name, MethodInfo mi)
{
CodeMethod m = c.ImplementMethod (mi);
CodeBuilder b = m.CodeBuilder;
// object [] parameters = new object [x];
// parameters [0] = arg1;
// parameters [1] = arg2;
// ...
// (return) BeginProcess (Contract.Operations [operName].BeginMethod, operName, parameters, asyncCallback, userState);
ParameterInfo [] pinfos = mi.GetParameters ();
CodeVariableDeclaration paramsDecl = new CodeVariableDeclaration (typeof (object []), "parameters");
b.CurrentBlock.Add (paramsDecl);
CodeVariableReference paramsRef = paramsDecl.Variable;
b.Assign (paramsRef,
new CodeNewArray (typeof (object), new CodeLiteral (pinfos.Length - 2)));
for (int i = 0; i < pinfos.Length - 2; i++) {
ParameterInfo par = pinfos [i];
if (!par.IsOut)
b.Assign (
new CodeArrayItem (paramsRef, new CodeLiteral (i)),
new CodeCast (typeof (object), m.GetArg (i)));
}
#if USE_OD_REFERENCE_IN_PROXY
CodePropertyReference argMethodInfo = GetOperationMethod (m, b, name, "BeginMethod");
#else
CodeMethodCall argMethodInfo = new CodeMethodCall (typeof (MethodBase), "GetCurrentMethod");
#endif
CodeLiteral argOperName = new CodeLiteral (name);
ParameterInfo p = pinfos [pinfos.Length - 2];
CodeArgumentReference callbackRef = new CodeArgumentReference (typeof (AsyncCallback), p.Position + 1, p.Name);
p = pinfos [pinfos.Length - 1];
CodeArgumentReference stateRef = new CodeArgumentReference (typeof (object), p.Position + 1, p.Name);
CodeVariableDeclaration retValueDecl = new CodeVariableDeclaration (mi.ReturnType, "retValue");
b.CurrentBlock.Add (retValueDecl);
CodeVariableReference retValue = retValueDecl.Variable;
b.Assign (retValue,
new CodeCast (mi.ReturnType,
b.CallFunc (m.GetThis (), beginProcessMethod, argMethodInfo, argOperName, paramsRef, callbackRef, stateRef)));
b.Return (retValue);
}
static void GenerateEndMethodImpl (CodeClass c, MethodInfo endProcessMethod, string name, MethodInfo mi)
{
CodeMethod m = c.ImplementMethod (mi);
CodeBuilder b = m.CodeBuilder;
ParameterInfo [] pinfos = mi.GetParameters ();
ParameterInfo p = pinfos [0];
CodeArgumentReference asyncResultRef = m.GetArg (0);
CodeVariableDeclaration paramsDecl = new CodeVariableDeclaration (typeof (object []), "parameters");
b.CurrentBlock.Add (paramsDecl);
CodeVariableReference paramsRef = paramsDecl.Variable;
b.Assign (paramsRef,
new CodeNewArray (typeof (object), new CodeLiteral (pinfos.Length - 1)));
/*
for (int i = 0; i < pinfos.Length - 2; i++) {
ParameterInfo par = pinfos [i];
if (!par.IsOut)
b.Assign (
new CodeArrayItem (paramsRef, new CodeLiteral (i)),
new CodeCast (typeof (object),
new CodeArgumentReference (par.ParameterType, par.Position + 1, "arg" + i)));
}
*/
#if USE_OD_REFERENCE_IN_PROXY
CodePropertyReference argMethodInfo = GetOperationMethod (m, b, name, "EndMethod");
#else
CodeMethodCall argMethodInfo = new CodeMethodCall (typeof (MethodBase), "GetCurrentMethod");
#endif
CodeLiteral argOperName = new CodeLiteral (name);
CodeVariableReference retValue = null;
if (mi.ReturnType == typeof (void))
b.Call (m.GetThis (), endProcessMethod, argMethodInfo, argOperName, paramsRef, asyncResultRef);
else {
CodeVariableDeclaration retValueDecl = new CodeVariableDeclaration (mi.ReturnType, "retValue");
b.CurrentBlock.Add (retValueDecl);
retValue = retValueDecl.Variable;
b.Assign (retValue,
new CodeCast (mi.ReturnType,
b.CallFunc (m.GetThis (), endProcessMethod, argMethodInfo, argOperName, paramsRef, asyncResultRef)));
}
// FIXME: fill out parameters
if (retValue != null)
b.Return (retValue);
}
}
}
#endif
#endif

View File

@ -0,0 +1,143 @@
//
// ClientRealProxy.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2011 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !DISABLE_REAL_PROXY
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.MonoInternal;
using System.Threading;
namespace System.ServiceModel
{
class ClientRealProxy : RealProxy, IRemotingTypeInfo
{
public ClientRealProxy (Type type, IInternalContextChannel channel, bool isDuplex)
: base (type)
{
this.channel = channel;
this.isDuplex = isDuplex;
}
bool isDuplex;
IInternalContextChannel channel;
Dictionary<object,object[]> saved_params = new Dictionary<object,object[]> ();
// It is used for such case that EndProcess() gets invoked
// before storing params is done after BeginProcess().
ManualResetEvent wait = new ManualResetEvent (false);
#region IRemotingTypeInfo
public virtual string TypeName { get; set; }
static bool CanCastTo<T> (Type type)
{
return typeof (T) == type || typeof (T).GetInterfaces ().Contains (type);
}
public virtual bool CanCastTo (Type t, object o)
{
if (CanCastTo<IClientChannel> (t))
return true;
#if !NET_2_1
if (isDuplex && CanCastTo<IDuplexContextChannel> (t))
return true;
#endif
return false;
}
#endregion
public override IMessage Invoke (IMessage inputMessage)
{
try {
return DoInvoke (inputMessage);
} catch (TargetInvocationException ex) {
if (ex.InnerException != null)
throw ex.InnerException;
throw;
}
}
IMessage DoInvoke (IMessage inputMessage)
{
var inmsg = (IMethodCallMessage) inputMessage;
var od = channel.Contract.Operations.FirstOrDefault (o => inmsg.MethodBase.Equals (o.SyncMethod) || inmsg.MethodBase.Equals (o.BeginMethod) || inmsg.MethodBase.Equals (o.EndMethod));
if (od == null) {
// Then IContextChannel methods.
var ret = inmsg.MethodBase.Invoke (channel, inmsg.InArgs);
return new ReturnMessage (ret, null, 0, null, inmsg);
} else {
object [] pl;
MethodBase method = null;
List<object> outArgs = null;
object ret;
if (inmsg.MethodBase.Equals (od.SyncMethod)) {
// sync invocation
pl = new object [inmsg.MethodBase.GetParameters ().Length];
Array.Copy (inmsg.Args, pl, inmsg.ArgCount);
channel.Context = OperationContext.Current;
ret = channel.Process (inmsg.MethodBase, od.Name, pl);
method = od.SyncMethod;
} else if (inmsg.MethodBase.Equals (od.BeginMethod)) {
// async invocation
pl = new object [inmsg.ArgCount - 2];
Array.Copy (inmsg.Args, 0, pl, 0, pl.Length);
ret = channel.BeginProcess (inmsg.MethodBase, od.Name, pl, (AsyncCallback) inmsg.Args [inmsg.ArgCount - 2], inmsg.Args [inmsg.ArgCount - 1]);
saved_params [ret] = pl;
wait.Set ();
} else {
var result = (IAsyncResult) inmsg.InArgs [0];
wait.WaitOne ();
pl = saved_params [result];
wait.Reset ();
saved_params.Remove (result);
ret = channel.EndProcess (inmsg.MethodBase, od.Name, pl, result);
method = od.BeginMethod;
}
if (method != null && method.GetParameters ().Any (pi => pi.IsOut || pi.ParameterType.IsByRef))
return new ReturnMessage (ret, pl, pl.Length, null, inmsg);
else
return new ReturnMessage (ret, outArgs != null ? outArgs.ToArray () : null, outArgs != null ? outArgs.Count : 0, null, inmsg);
}
}
}
}
#endif

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More