public JsonRpcHttpBinding() : base() { transport = new HttpTransportBindingElement(); encoding = new WebMessageEncodingBindingElement(); encoding.ContentTypeMapper = new JsonRpcRawMapper(); }
private static void CreateHttpGetChannelDispatcher(ServiceHostBase host, Uri listenUri, MetadataSet metadata) { //创建Binding TextMessageEncodingBindingElement messageEncodingElement = new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.None }; HttpTransportBindingElement transportElement = new HttpTransportBindingElement(); Utility.SetPropertyValue(transportElement, "Method", "GET"); Binding binding = new CustomBinding(messageEncodingElement, transportElement); //创建ChannelListener IChannelListener listener = binding.BuildChannelListener<IReplyChannel>(listenUri, string.Empty, ListenUriMode.Explicit, new BindingParameterCollection()); ChannelDispatcher dispatcher = new ChannelDispatcher(listener, "ServiceMetadataBehaviorHttpGetBinding", binding) { MessageVersion = binding.MessageVersion }; //创建EndpointDispatcher EndpointDispatcher endpoint = new EndpointDispatcher(new EndpointAddress(listenUri), "IHttpGetMetadata", "http://www.artech.com/"); //创建DispatchOperation,并设置DispatchMessageFormatter和OperationInvoker DispatchOperation operation = new DispatchOperation(endpoint.DispatchRuntime, "Get", "*", "*"); operation.Formatter = Utility.CreateInstance<IDispatchMessageFormatter>(MessageOperationFormatterType, Type.EmptyTypes, new object[0]); MethodInfo method = typeof(IHttpGetMetadata).GetMethod("Get"); operation.Invoker = Utility.CreateInstance<IOperationInvoker>(SyncMethodInvokerType, new Type[] { typeof(MethodInfo) }, new object[] { method }); endpoint.DispatchRuntime.Operations.Add(operation); //设置SingletonInstanceContext和InstanceContextProvider MetadataProvisionService serviceInstance = new MetadataProvisionService(metadata); endpoint.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, serviceInstance); endpoint.DispatchRuntime.InstanceContextProvider = Utility.CreateInstance<IInstanceContextProvider>(SingletonInstanceContextProviderType, new Type[] { typeof(DispatchRuntime) }, new object[] { endpoint.DispatchRuntime }); dispatcher.Endpoints.Add(endpoint); //设置ContractFilter和AddressFilter endpoint.ContractFilter = new MatchAllMessageFilter(); endpoint.AddressFilter = new MatchAllMessageFilter(); host.ChannelDispatchers.Add(dispatcher); }
private static void ConfigureAuthentication(HttpTransportBindingElement http, HttpTransportSecurity transportSecurity) { transportSecurity.clientCredentialType = HttpClientCredentialTypeHelper.MapToClientCredentialType(http.AuthenticationScheme); transportSecurity.proxyCredentialType = HttpProxyCredentialTypeHelper.MapToProxyCredentialType(http.ProxyAuthenticationScheme); transportSecurity.Realm = http.Realm; transportSecurity.extendedProtectionPolicy = http.ExtendedProtectionPolicy; }
public static void Main () { HttpTransportBindingElement el = new HttpTransportBindingElement (); BindingContext bc = new BindingContext ( new CustomBinding (), new BindingParameterCollection (), new Uri ("http://localhost:37564"), String.Empty, ListenUriMode.Explicit); IChannelListener<IReplyChannel> listener = el.BuildChannelListener<IReplyChannel> (bc); listener.Open (); IReplyChannel reply = listener.AcceptChannel (); reply.Open (); if (!reply.WaitForRequest (TimeSpan.FromSeconds (10))) { Console.WriteLine ("No request reached here."); return; } Console.WriteLine ("Receiving request ..."); RequestContext ctx = reply.ReceiveRequest (); if (ctx == null) return; Console.WriteLine ("Starting reply ..."); ctx.Reply (Message.CreateMessage (MessageVersion.Default, "Ack")); }
public static void Main () { SymmetricSecurityBindingElement sbe = new SymmetricSecurityBindingElement (); sbe.ProtectionTokenParameters = new SslSecurityTokenParameters (); ServiceHost host = new ServiceHost (typeof (Foo)); HttpTransportBindingElement hbe = new HttpTransportBindingElement (); CustomBinding binding = new CustomBinding (sbe, hbe); binding.ReceiveTimeout = TimeSpan.FromSeconds (5); host.AddServiceEndpoint ("IFoo", binding, new Uri ("http://localhost:8080")); ServiceCredentials cred = new ServiceCredentials (); cred.SecureConversationAuthentication.SecurityStateEncoder = new MyEncoder (); cred.ServiceCertificate.Certificate = new X509Certificate2 ("test.pfx", "mono"); cred.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; host.Description.Behaviors.Add (cred); host.Description.Behaviors.Find<ServiceDebugBehavior> () .IncludeExceptionDetailInFaults = true; // foreach (ServiceEndpoint se in host.Description.Endpoints) // se.Behaviors.Add (new StdErrInspectionBehavior ()); ServiceMetadataBehavior smb = new ServiceMetadataBehavior (); smb.HttpGetEnabled = true; smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl"); host.Description.Behaviors.Add (smb); host.Open (); Console.WriteLine ("Hit [CR] key to close ..."); Console.ReadLine (); host.Close (); }
static void Main(string[] args) { try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); IChannelListener<IReplyChannel> listener=binding.BuildChannelListener<IReplyChannel>(new Uri("http://localhost:9090/RequestReplyService"),new BindingParameterCollection()); listener.Open(); IReplyChannel replyChannel = listener.AcceptChannel(); replyChannel.Open(); Console.WriteLine("starting to receive message...."); RequestContext requestContext = replyChannel.ReceiveRequest(); Console.WriteLine("Received a Message, action:{0},body:{1}", requestContext.RequestMessage.Headers.Action, requestContext.RequestMessage.GetBody<string>()); Message message = Message.CreateMessage(binding.MessageVersion, "response", "response Message"); requestContext.Reply(message); requestContext.Close(); replyChannel.Close(); listener.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.Read(); } }
static void Main(string[] args) { try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body")) { IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection()); factory.Open(); IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost:9090/RequestReplyService")); requestChannel.Open(); Message response = requestChannel.Request(message); Console.WriteLine("Successful send message!"); Console.WriteLine("Receive a return message, action: {0}, body: {1}", response.Headers.Action, response.GetBody<String>()); requestChannel.Close(); factory.Close(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.Read(); } }
private static bool GetSecurityModeFromTransport(HttpTransportBindingElement http, HttpTransportSecurity transportSecurity, out UnifiedSecurityMode mode) { mode = UnifiedSecurityMode.None; if (http == null) { return false; } if (http is HttpsTransportBindingElement) { mode = UnifiedSecurityMode.TransportWithMessageCredential | UnifiedSecurityMode.Transport; BasicHttpSecurity.EnableTransportSecurity((HttpsTransportBindingElement) http, transportSecurity); } else if (HttpTransportSecurity.IsDisabledTransportAuthentication(http)) { mode = UnifiedSecurityMode.Message | UnifiedSecurityMode.None; } else { if (!BasicHttpSecurity.IsEnabledTransportAuthentication(http, transportSecurity)) { return false; } mode = UnifiedSecurityMode.TransportCredentialOnly; } return true; }
public static CustomBinding GetBinding() { // Same binding should be used in both service and service client. //var binding = new BasicHttpBinding(); //binding.ReaderQuotas.MaxStringContentLength = int.MaxValue; //SetTimeOuts(binding); //return binding; // Instantiate message encoding element and configure TextMessageEncodingBindingElement text = new TextMessageEncodingBindingElement(); text.MessageVersion = MessageVersion.Soap11; text.ReaderQuotas.MaxStringContentLength = int.MaxValue; // Instantiate transport element and configure HttpTransportBindingElement http = new HttpTransportBindingElement(); http.TransferMode = TransferMode.Buffered; http.UseDefaultWebProxy = true; CustomBinding binding = new CustomBinding(); binding.Name = "MonoscapeHttpBinding"; binding.Elements.Add(text); binding.Elements.Add(http); SetTimeOuts(binding); return binding; }
public static void Main () { HttpTransportBindingElement el = new HttpTransportBindingElement (); IChannelFactory<IRequestChannel> factory = el.BuildChannelFactory<IRequestChannel> ( new BindingContext (new CustomBinding (), new BindingParameterCollection ())); factory.Open (); IRequestChannel request = factory.CreateChannel ( new EndpointAddress ("http://localhost:37564")); request.Open (); using (XmlWriter w = XmlWriter.Create (Console.Out)) { Message.CreateMessage (MessageVersion.Default, "Echo") .WriteMessage (w); } Console.WriteLine (); Message msg = request.Request ( Message.CreateMessage (MessageVersion.Default, "Echo"), TimeSpan.FromSeconds (15)); using (XmlWriter w = XmlWriter.Create (Console.Out)) { msg.WriteMessage (w); } }
public static DuplexServiceClient GetDuplexServiceProxyClient() { string baseServiceUrl = Application.Current.Resources["BaseServiceUrl"].ToString(); EndpointAddress address = new EndpointAddress(baseServiceUrl + "DuplexService/PhasorDataDuplexService.svc"); CustomBinding binding; if (HtmlPage.Document.DocumentUri.Scheme.ToLower().StartsWith("https")) { HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement(); httpsTransportBindingElement.MaxReceivedMessageSize = int.MaxValue; binding = new CustomBinding( new PollingDuplexBindingElement(), new BinaryMessageEncodingBindingElement(), httpsTransportBindingElement ); } else { HttpTransportBindingElement httpTransportBindingElement = new HttpTransportBindingElement(); httpTransportBindingElement.MaxReceivedMessageSize = int.MaxValue; // 65536 * 50; binding = new CustomBinding( new PollingDuplexBindingElement(), new BinaryMessageEncodingBindingElement(), httpTransportBindingElement ); } binding.CloseTimeout = new TimeSpan(0, 20, 0); binding.OpenTimeout = new TimeSpan(0, 20, 0); binding.ReceiveTimeout = new TimeSpan(0, 20, 0); binding.SendTimeout = new TimeSpan(0, 20, 0); return new DuplexServiceClient(binding, address); }
private void ConfigureAuthentication(HttpTransportBindingElement http) { http.AuthenticationScheme = HttpClientCredentialTypeHelper.MapToAuthenticationScheme(this.clientCredentialType); http.ProxyAuthenticationScheme = HttpProxyCredentialTypeHelper.MapToAuthenticationScheme(this.proxyCredentialType); http.Realm = this.Realm; http.ExtendedProtectionPolicy = this.extendedProtectionPolicy; }
private void InitializeFrom(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding, System.ServiceModel.Channels.TransactionFlowBindingElement txFlow, System.ServiceModel.Channels.ReliableSessionBindingElement session) { this.BypassProxyOnLocal = transport.BypassProxyOnLocal; this.HostNameComparisonMode = transport.HostNameComparisonMode; this.MaxBufferPoolSize = transport.MaxBufferPoolSize; this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize; this.ProxyAddress = transport.ProxyAddress; this.UseDefaultWebProxy = transport.UseDefaultWebProxy; if (encoding is TextMessageEncodingBindingElement) { this.MessageEncoding = WSMessageEncoding.Text; TextMessageEncodingBindingElement element = (TextMessageEncodingBindingElement) encoding; this.TextEncoding = element.WriteEncoding; this.ReaderQuotas = element.ReaderQuotas; } else if (encoding is MtomMessageEncodingBindingElement) { this.messageEncoding = WSMessageEncoding.Mtom; MtomMessageEncodingBindingElement element2 = (MtomMessageEncodingBindingElement) encoding; this.TextEncoding = element2.WriteEncoding; this.ReaderQuotas = element2.ReaderQuotas; } this.TransactionFlow = txFlow.Transactions; this.reliableSession.Enabled = session != null; if (session != null) { this.session.InactivityTimeout = session.InactivityTimeout; this.session.Ordered = session.Ordered; } }
private void DisableAuthentication(HttpTransportBindingElement http) { http.AuthenticationScheme = AuthenticationSchemes.Anonymous; http.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous; http.Realm = ""; http.ExtendedProtectionPolicy = this.extendedProtectionPolicy; }
public static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8000/servicesamplemodel/service"); using (ServiceHost host = new ServiceHost(typeof(Service), baseAddress)) { ReliableSessionBindingElement reliableBinding = new ReliableSessionBindingElement(); reliableBinding.Ordered = true; HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement(); httpBindingElement.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; CustomBinding customBinding = new CustomBinding(reliableBinding, httpBindingElement); host.AddServiceEndpoint(typeof(ICalculator), customBinding, ""); host.Open(); // The service can now be accessed. Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); } }
public void CanBuildChannelFactory () { // with HttpTransport var m = new WebMessageEncodingBindingElement (); Assert.IsTrue (m.CanBuildChannelFactory<IRequestChannel> (CreateBindingContext ()), "#1"); Assert.IsFalse (m.CanBuildChannelFactory<IReplyChannel> (CreateBindingContext ()), "#2"); Assert.IsFalse (m.CanBuildChannelFactory<IRequestSessionChannel> (CreateBindingContext ()), "#3"); Assert.IsFalse (m.CanBuildChannelFactory<IDuplexChannel> (CreateBindingContext ()), "#4"); // actually they are from transport var h = new HttpTransportBindingElement (); Assert.IsTrue (h.CanBuildChannelFactory<IRequestChannel> (CreateBindingContext ()), "#5"); Assert.IsFalse (h.CanBuildChannelFactory<IReplyChannel> (CreateBindingContext ()), "#6"); Assert.IsFalse (h.CanBuildChannelFactory<IRequestSessionChannel> (CreateBindingContext ()), "#7"); Assert.IsFalse (h.CanBuildChannelFactory<IDuplexChannel> (CreateBindingContext ()), "#8"); // with TcpTransport Assert.IsFalse (m.CanBuildChannelFactory<IRequestChannel> (CreateBindingContext2 ()), "#9"); Assert.IsFalse (m.CanBuildChannelFactory<IReplyChannel> (CreateBindingContext2 ()), "#10"); Assert.IsFalse (m.CanBuildChannelFactory<IRequestSessionChannel> (CreateBindingContext2 ()), "#11"); Assert.IsFalse (m.CanBuildChannelFactory<IDuplexChannel> (CreateBindingContext2 ()), "#12"); // ... yes, actually they are from transport var t = new TcpTransportBindingElement (); Assert.IsFalse (t.CanBuildChannelFactory<IRequestChannel> (CreateBindingContext2 ()), "#13"); Assert.IsFalse (t.CanBuildChannelFactory<IReplyChannel> (CreateBindingContext2 ()), "#14"); Assert.IsFalse (t.CanBuildChannelFactory<IRequestSessionChannel> (CreateBindingContext2 ()), "#15"); Assert.IsFalse (t.CanBuildChannelFactory<IDuplexChannel> (CreateBindingContext2 ()), "#16"); }
// Host the service within this EXE console application. public static void Main() { Uri baseAddress = new Uri("http://localhost:8000/servicemodelsamples/service"); // Create a ServiceHost for the CalculatorService type and provide the base address. using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress)) { // Create a custom binding containing two binding elements ReliableSessionBindingElement reliableSession = new ReliableSessionBindingElement(); reliableSession.Ordered = true; HttpTransportBindingElement httpTransport = new HttpTransportBindingElement(); httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; CustomBinding binding = new CustomBinding(reliableSession, httpTransport); // Add an endpoint using that binding serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, ""); // Open the ServiceHost to create listeners and start listening for messages. serviceHost.Open(); // The service can now be accessed. Console.WriteLine("The service is ready."); Console.WriteLine("Press <ENTER> to terminate service."); Console.WriteLine(); Console.ReadLine(); } }
private static HttpsTransportBindingElement CreateHttpsFromHttp(HttpTransportBindingElement http) { if (http == null) { return new HttpsTransportBindingElement(); } return HttpsTransportBindingElement.CreateFromHttpBindingElement(http); }
internal void ConfigureTransportAuthentication(HttpTransportBindingElement http) { if (this.clientCredentialType == HttpClientCredentialType.Certificate) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("CertificateUnsupportedForHttpTransportCredentialOnly"))); } this.ConfigureAuthentication(http); }
private void DisableAuthentication(HttpTransportBindingElement http) { http.AuthenticationScheme = AuthenticationSchemes.Anonymous; http.Realm = DefaultRealm; //ExtendedProtectionPolicy is always copied - even for security mode None, Message and TransportWithMessageCredential, //because the settings for ExtendedProtectionPolicy are always below the <security><transport> element //http.ExtendedProtectionPolicy = this.extendedProtectionPolicy; }
private static CustomBinding CreateGetBinding(HttpTransportBindingElement httpTransport) { TextMessageEncodingBindingElement element = new TextMessageEncodingBindingElement { MessageVersion = MessageVersion.None }; httpTransport.Method = "GET"; httpTransport.InheritBaseAddressSettings = true; return new CustomBinding(new BindingElement[] { element, httpTransport }); }
internal HttpBindingBase() { _httpTransport = new HttpTransportBindingElement(); _httpsTransport = new HttpsTransportBindingElement(); _textEncoding = new TextMessageEncodingBindingElement(); _textEncoding.MessageVersion = MessageVersion.Soap11; _httpsTransport.WebSocketSettings = _httpTransport.WebSocketSettings; }
private void Initialize() { _securityBindingElement = CreateSecurityBindingElement(); _textEncodingBindingElement = CreateTextEncodingBindingElement(); //_httpsTransportBindingElement = CreateHttpsTransportBindingElement(); _httpTransportBindingElement = CreateHttpTransportBindingElement(); }
internal static void DisableTransportAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpTransportBindingElement httpTransportBindingElement) { Debug.Assert(httpTransportSecurity != null, "httpTransportSecurity cannot be null"); Debug.Assert(httpTransportBindingElement != null, "httpTransportBindingElement cannot be null"); httpTransportBindingElement.AuthenticationScheme = AuthenticationSchemes.Anonymous; httpTransportBindingElement.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous; httpTransportBindingElement.Realm = String.Empty; httpTransportBindingElement.ExtendedProtectionPolicy = httpTransportSecurity.ExtendedProtectionPolicy; }
private static void ConfigureAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpTransportBindingElement httpTransportBindingElement) { Debug.Assert(httpTransportSecurity != null, "httpTransportSecurity cannot be null"); Debug.Assert(httpTransportBindingElement != null, "httpTransportBindingElement cannot be null"); httpTransportBindingElement.AuthenticationScheme = HttpClientCredentialTypeHelper.MapToAuthenticationScheme(httpTransportSecurity.ClientCredentialType); httpTransportBindingElement.ProxyAuthenticationScheme = HttpProxyCredentialTypeHelper.MapToAuthenticationScheme(httpTransportSecurity.ProxyCredentialType); httpTransportBindingElement.Realm = httpTransportSecurity.Realm; httpTransportBindingElement.ExtendedProtectionPolicy = httpTransportSecurity.ExtendedProtectionPolicy; }
private HttpTransportBindingElement CreateHttpTransportBindingElement() { HttpTransportBindingElement transportBindingElement = new HttpTransportBindingElement(); transportBindingElement.MaxBufferSize = 524288; transportBindingElement.MaxReceivedMessageSize = 200000000; transportBindingElement.MaxBufferSize = 200000000; return transportBindingElement; }
protected override void ApplyTransportSecurity(HttpTransportBindingElement transport) { transport.AuthenticationScheme = AuthenticationSchemes.Anonymous; var element = transport as HttpsTransportBindingElement; if (element != null) { element.RequireClientCertificate = true; } }
public static void IRequestChannel_Http_CustomBinding() { try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); // Create the channel factory for the request-reply message exchange pattern. IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>( new BindingParameterCollection()); factory.Open(); // Create the channel. IRequestChannel channel = factory.CreateChannel( new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); channel.Open(); // Create the Message object to send to the service. Message requestMessage = Message.CreateMessage( binding.MessageVersion, action, new CustomBodyWriter(clientMessage)); // Send the Message and receive the Response. Message replyMessage = channel.Request(requestMessage); string replyMessageAction = replyMessage.Headers.Action; if (!string.Equals(replyMessageAction, action + "Response")) { Assert.True(false, String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction)); } var replyReader = replyMessage.GetReaderAtBodyContents(); string actualResponse = replyReader.ReadElementContentAsString(); string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply."; if (!string.Equals(actualResponse, expectedResponse)) { Assert.True(false, String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse)); } replyMessage.Close(); channel.Close(); factory.Close(); } catch (Exception ex) { Assert.True(false, String.Format("Unexpected exception was caught: {0}", ex.ToString())); } }
public HttpCookieSessionBinding() : base() { sessionElement = new HttpCookieSessionBindingElement(); transportElement = new HttpTransportBindingElement(); transportElement.AllowCookies = true; encodingElement = new TextMessageEncodingBindingElement(); encodingElement.MessageVersion = MessageVersion.Soap11WSAddressing10; }
protected override void ApplyTransportSecurity(HttpTransportBindingElement transport) { if (this._clientCredentialType == HttpClientCredentialType.Basic) { transport.AuthenticationScheme = AuthenticationSchemes.Basic; } else { transport.AuthenticationScheme = AuthenticationSchemes.Digest; } }
internal static bool TryCreate(BindingElementCollection elements, out Binding binding) { binding = null; if (elements.Count > 4) { return(false); } ReliableSessionBindingElement session = null; SecurityBindingElement securityElement = null; MessageEncodingBindingElement encoding = null; HttpTransportBindingElement transport = null; foreach (BindingElement element in elements) { if (element is ReliableSessionBindingElement) { session = element as ReliableSessionBindingElement; } if (element is SecurityBindingElement) { securityElement = element as SecurityBindingElement; } else if (element is TransportBindingElement) { transport = element as HttpTransportBindingElement; } else if (element is MessageEncodingBindingElement) { encoding = element as MessageEncodingBindingElement; } else { return(false); } } if (transport == null || transport.WebSocketSettings.TransportUsage != WebSocketTransportUsage.Always) { return(false); } HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement; if ((securityElement != null) && (httpsTransport != null) && (httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate)) { return(false); } // process transport binding element UnifiedSecurityMode mode; HttpTransportSecurity transportSecurity = new HttpTransportSecurity(); if (!GetSecurityModeFromTransport(transport, transportSecurity, out mode)) { return(false); } if (encoding == null) { return(false); } if (!(encoding is TextMessageEncodingBindingElement || encoding is MtomMessageEncodingBindingElement || encoding is BinaryMessageEncodingBindingElement)) { return(false); } if (encoding.MessageVersion != MessageVersion.Soap12WSAddressing10) { return(false); } BasicHttpSecurity security; if (!TryCreateSecurity(securityElement, mode, transportSecurity, out security)) { return(false); } NetHttpBinding netHttpBinding = new NetHttpBinding(security); netHttpBinding.InitializeFrom(transport, encoding, session); // make sure all our defaults match if (!netHttpBinding.IsBindingElementsMatch(transport, encoding, session)) { return(false); } binding = netHttpBinding; return(true); }
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); }
internal static bool TryCreate(BindingElementCollection elements, out Binding binding) { binding = null; if (elements.Count > 6) { return(false); } PrivacyNoticeBindingElement privacy = null; System.ServiceModel.Channels.TransactionFlowBindingElement tfbe = null; System.ServiceModel.Channels.ReliableSessionBindingElement rsbe = null; SecurityBindingElement sbe = null; MessageEncodingBindingElement encoding = null; HttpTransportBindingElement transport = null; foreach (BindingElement element7 in elements) { if (element7 is SecurityBindingElement) { sbe = element7 as SecurityBindingElement; } else if (element7 is TransportBindingElement) { transport = element7 as HttpTransportBindingElement; } else if (element7 is MessageEncodingBindingElement) { encoding = element7 as MessageEncodingBindingElement; } else if (element7 is System.ServiceModel.Channels.TransactionFlowBindingElement) { tfbe = element7 as System.ServiceModel.Channels.TransactionFlowBindingElement; } else if (element7 is System.ServiceModel.Channels.ReliableSessionBindingElement) { rsbe = element7 as System.ServiceModel.Channels.ReliableSessionBindingElement; } else if (element7 is PrivacyNoticeBindingElement) { privacy = element7 as PrivacyNoticeBindingElement; } else { return(false); } } if (transport == null) { return(false); } if (encoding == null) { return(false); } if (((privacy != null) || !WSHttpBinding.TryCreate(sbe, transport, rsbe, tfbe, out binding)) && ((!WSFederationHttpBinding.TryCreate(sbe, transport, privacy, rsbe, tfbe, out binding) && !WS2007HttpBinding.TryCreate(sbe, transport, rsbe, tfbe, out binding)) && !WS2007FederationHttpBinding.TryCreate(sbe, transport, privacy, rsbe, tfbe, out binding))) { return(false); } if (tfbe == null) { tfbe = GetDefaultTransactionFlowBindingElement(); if ((binding is WS2007HttpBinding) || (binding is WS2007FederationHttpBinding)) { tfbe.TransactionProtocol = TransactionProtocol.WSAtomicTransaction11; } } WSHttpBindingBase base2 = binding as WSHttpBindingBase; base2.InitializeFrom(transport, encoding, tfbe, rsbe); if (!base2.IsBindingElementsMatch(transport, encoding, tfbe, rsbe)) { return(false); } return(true); }
private static void ConfigureAuthentication(HttpTransportBindingElement http, HttpTransportSecurity transportSecurity) { transportSecurity._clientCredentialType = HttpClientCredentialTypeHelper.MapToClientCredentialType(http.AuthenticationScheme); transportSecurity.Realm = http.Realm; }
internal void EnableTransportAuthentication(HttpTransportBindingElement http) { _transportSecurity.ConfigureTransportAuthentication(http); }
protected override void ApplyTransportSecurity(HttpTransportBindingElement transport) { transport.AuthenticationScheme = _clientCredentialType == HttpClientCredentialType.Basic ? AuthenticationSchemes.Basic : AuthenticationSchemes.Digest; }
// public bool IsInitialized { get { return m_initialised; } } public override async Task <bool> InitalizeAsync() { if (this.m_onVifDevice.ServicesResponse == null) { bool b = await this.m_onVifDevice.InitalizeDeviceAsync(); if (this.m_onVifDevice.ServicesResponse == null) { return(false); } } try { foreach (var service in this.m_onVifDevice.ServicesResponse.Service) { if (service.Namespace == "http://www.onvif.org/ver20/ptz/wsdl") { string serviceAdress = service.XAddr; m_ErrorMessage = ""; // m_profile = this.m_media10Services.ProfilesResponse.Profiles[0]; HttpTransportBindingElement httpBinding = new HttpTransportBindingElement(); httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest; var messageElement = new TextMessageEncodingBindingElement(); messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None); CustomBinding binding = new CustomBinding(messageElement, httpBinding); this.m_ptzClient = new PTZClient(binding, new EndpointAddress(serviceAdress)); /* * while (m_ptzClient.Endpoint.EndpointBehaviors.Count > 0) * { * m_ptzClient.Endpoint.EndpointBehaviors.RemoveAt(0); * } */ m_ptzClient.Endpoint.EndpointBehaviors.Add(m_onVifDevice.GetBasicBasicAuthBehaviour); m_ptzClient.Endpoint.EndpointBehaviors.Add(m_onVifDevice.GetPasswordDigestBehavior); m_configs = await m_ptzClient.GetConfigurationsAsync(); m_options = await m_ptzClient.GetConfigurationOptionsAsync(m_configs.PTZConfiguration[0].token); m_capabilities = await m_ptzClient.GetServiceCapabilitiesAsync(); m_velocity = new OnvifPTZService.PTZSpeed() { PanTilt = new OnvifPTZService.Vector2D() { x = 0, y = 0, space = m_options.Spaces.ContinuousPanTiltVelocitySpace[0].URI, } , Zoom = new OnvifPTZService.Vector1D() { x = 0, space = m_options.Spaces.ContinuousZoomVelocitySpace[0].URI, } }; m_vector = new PTZVector() { PanTilt = new OnvifPTZService.Vector2D() { x = 0, y = 0, space = m_options.Spaces.RelativePanTiltTranslationSpace[0].URI } }; m_initialised = true; m_bMoveActiv = false; if (m_relative) { m_velocity.PanTilt.space = m_options.Spaces.ContinuousPanTiltVelocitySpace[0].URI; m_velocity.PanTilt.space = m_configs.PTZConfiguration[0].DefaultPTZSpeed.PanTilt.space; m_panDistance = (m_options.Spaces.RelativePanTiltTranslationSpace[0].XRange.Max - m_options.Spaces.RelativePanTiltTranslationSpace[0].XRange.Min) / PanIncrements; m_tiltDistance = (m_options.Spaces.RelativePanTiltTranslationSpace[0].YRange.Max - m_options.Spaces.RelativePanTiltTranslationSpace[0].YRange.Min) / TiltIncrements; } break; } } } catch (Exception ex) { m_ErrorMessage = ex.Message; throw new OnVifException("OnVifPTZController.InitalizeAsync", ex); // return false; } return(m_initialised); }
// <snippet2> public override BindingElementCollection CreateBindingElements() { //SecurityBindingElement sbe = bec.Find<SecurityBindingElement>(); BindingElementCollection bec = new BindingElementCollection(); // By default http transport is used SecurityBindingElement securityBinding; BindingElement transport; switch (assertion) { case WseSecurityAssertion.UsernameOverTransport: transport = new HttpsTransportBindingElement(); securityBinding = (TransportSecurityBindingElement)SecurityBindingElement.CreateUserNameOverTransportBindingElement(); if (establishSecurityContext == true) { throw new InvalidOperationException("Secure Conversation is not supported for this Security Assertion Type"); } if (requireSignatureConfirmation == true) { throw new InvalidOperationException("Signature Confirmation is not supported for this Security Assertion Type"); } break; case WseSecurityAssertion.MutualCertificate10: transport = new HttpTransportBindingElement(); securityBinding = SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10); if (requireSignatureConfirmation == true) { throw new InvalidOperationException("Signature Confirmation is not supported for this Security Assertion Type"); } ((AsymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder = messageProtectionOrder; break; case WseSecurityAssertion.UsernameForCertificate: transport = new HttpTransportBindingElement(); securityBinding = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateUserNameForCertificateBindingElement(); // We want signatureconfirmation on the bootstrap process // either for the application messages or for the RST/RSTR ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation; ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder = messageProtectionOrder; break; case WseSecurityAssertion.AnonymousForCertificate: transport = new HttpTransportBindingElement(); securityBinding = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateAnonymousForCertificateBindingElement(); ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation; ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder = messageProtectionOrder; break; case WseSecurityAssertion.MutualCertificate11: transport = new HttpTransportBindingElement(); securityBinding = SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11); ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation; ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder = messageProtectionOrder; break; case WseSecurityAssertion.Kerberos: transport = new HttpTransportBindingElement(); securityBinding = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateKerberosBindingElement(); ((SymmetricSecurityBindingElement)securityBinding).RequireSignatureConfirmation = requireSignatureConfirmation; ((SymmetricSecurityBindingElement)securityBinding).MessageProtectionOrder = messageProtectionOrder; break; default: throw new NotSupportedException("This supplied Wse security assertion is not supported"); } //Set defaults for the security binding securityBinding.IncludeTimestamp = true; // Derived Keys // set the preference for derived keys before creating SecureConversationBindingElement securityBinding.SetKeyDerivation(requireDerivedKeys); //Secure Conversation if (establishSecurityContext == true) { SymmetricSecurityBindingElement secureconversation = (SymmetricSecurityBindingElement)SymmetricSecurityBindingElement.CreateSecureConversationBindingElement( securityBinding, false); // This is the default //secureconversation.DefaultProtectionLevel = ProtectionLevel.EncryptAndSign; //Set defaults for the secure conversation binding secureconversation.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256; // We do not want signature confirmation on the application level messages // when secure conversation is enabled. secureconversation.RequireSignatureConfirmation = false; secureconversation.MessageProtectionOrder = messageProtectionOrder; secureconversation.SetKeyDerivation(requireDerivedKeys); securityBinding = secureconversation; } // Add the security binding to the binding collection bec.Add(securityBinding); // Add the message encoder. TextMessageEncodingBindingElement textelement = new TextMessageEncodingBindingElement(); textelement.MessageVersion = MessageVersion.Soap11WSAddressingAugust2004; //These are the defaults required for WSE //textelement.MessageVersion = MessageVersion.Soap11Addressing1; //textelement.WriteEncoding = System.Text.Encoding.UTF8; bec.Add(textelement); // Add the transport bec.Add(transport); // return the binding elements return(bec); }
internal static bool IsEnabledTransportAuthentication(HttpTransportBindingElement http, HttpTransportSecurity transportSecurity) { return(HttpTransportSecurity.IsConfiguredTransportAuthentication(http, transportSecurity)); }
internal void DisableTransportAuthentication(HttpTransportBindingElement http) { this.DisableAuthentication(http); }
void ConfigureTransportBindingElement(HttpTransportBindingElement element) { element.AuthenticationScheme = Net.AuthenticationSchemes.Ntlm; }
private static bool IsDisabledAuthentication(HttpTransportBindingElement http) { return(((http.AuthenticationScheme == AuthenticationSchemes.Anonymous) && (http.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous)) && (http.Realm == "")); }
protected override void ApplyTransportSecurity(HttpTransportBindingElement transport) { transport.AuthenticationScheme = AuthenticationSchemes.Negotiate; }
public bool Initialise(string cameraAddress, string userName, string password) { bool result = false; cam_ip = cameraAddress; cam_id = userName; cam_pw = password; //ConnectCam(); try { var messageElement = new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.CreateVersion( EnvelopeVersion.Soap12, AddressingVersion.None) }; HttpTransportBindingElement httpBinding = new HttpTransportBindingElement(); httpBinding.AuthenticationScheme = System.Net.AuthenticationSchemes.Digest; CustomBinding bind = new CustomBinding(messageElement, httpBinding); //mediaClient = new Media2Client(bind, // new EndpointAddress($"http://{cameraAddress}/onvif/device_service")); //mediaClient.ClientCredentials.HttpDigest.AllowedImpersonationLevel = // System.Security.Principal.TokenImpersonationLevel.Impersonation; //mediaClient.ClientCredentials.HttpDigest.ClientCredential.UserName = userName; //mediaClient.ClientCredentials.HttpDigest.ClientCredential.Password = password; //ptzClient = new PTZClient(bind, // new EndpointAddress($"http://{cameraAddress}/onvif/device_service")); //ptzClient.ClientCredentials.HttpDigest.AllowedImpersonationLevel = // System.Security.Principal.TokenImpersonationLevel.Impersonation; //ptzClient.ClientCredentials.HttpDigest.ClientCredential.UserName = userName; //ptzClient.ClientCredentials.HttpDigest.ClientCredential.Password = password; deviceclient = new DeviceClient(bind, new EndpointAddress($"http://{cameraAddress}/onvif/device_service")); deviceclient.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; deviceclient.ClientCredentials.HttpDigest.ClientCredential.UserName = userName; deviceclient.ClientCredentials.HttpDigest.ClientCredential.Password = password; mediaClient10 = new MediaClient(bind, new EndpointAddress($"http://{cameraAddress}/onvif/media_service")); mediaClient10.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; mediaClient10.ClientCredentials.HttpDigest.ClientCredential.UserName = userName; mediaClient10.ClientCredentials.HttpDigest.ClientCredential.Password = password; //onvif ver 1.0 var profs = mediaClient10.GetProfiles(); profile10 = mediaClient10.GetProfile(profs[0].token); ONVIF_MediaProfilDashboard.Media10.StreamSetup streamSetup = new ONVIF_MediaProfilDashboard.Media10.StreamSetup() { }; streamSetup.Stream = StreamType.RTPUnicast; streamSetup.Transport = new Transport(); streamSetup.Transport.Protocol = TransportProtocol.RTSP; MediaUri mediaUri = mediaClient10.GetStreamUri(streamSetup, profs[0].token); //string string2222 = deviceclient.GetWsdlUrl(); var configs = ptzClient.GetConfigurations(); options = ptzClient.GetConfigurationOptions(configs[0].token); velocity = new OnvifPTZService.PTZSpeed() { PanTilt = new OnvifPTZService.Vector2D() { x = 0, y = 0, space = options.Spaces.ContinuousPanTiltVelocitySpace[0].URI, }, Zoom = new OnvifPTZService.Vector1D() { x = 0, space = options.Spaces.ContinuousZoomVelocitySpace[0].URI, } }; ErrorMessage = ""; result = initialised = true; } catch (Exception ex) { ErrorMessage = ex.Message; } return(result); }
internal static bool IsDisabledTransportAuthentication(HttpTransportBindingElement http) { return(IsDisabledAuthentication(http)); }
internal void DisableTransportAuthentication(HttpTransportBindingElement http) { _transportSecurity.DisableTransportAuthentication(http); }
public static ServiceEndpoint[] GetEndpoints(string mexAddress) { if (string.IsNullOrWhiteSpace(mexAddress)) { throw new ArgumentException("mexAddress"); } Uri address = new Uri(mexAddress); ServiceEndpointCollection endpoints = null; BindingElement bindingElement = null; //Try over HTTP-GET first if (address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps) { string getAddress = mexAddress; if (mexAddress.EndsWith("?wsdl") == false) { getAddress += "?wsdl"; } if (address.Scheme == Uri.UriSchemeHttp) { HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement(); httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier; bindingElement = httpBindingElement; } else { HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement(); httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier; bindingElement = httpsBindingElement; } CustomBinding binding = new CustomBinding(bindingElement); MetadataExchangeClient mexClient = new MetadataExchangeClient(binding); MetadataSet metadata = mexClient.GetMetadata(new Uri(getAddress), MetadataExchangeClientMode.HttpGet); MetadataImporter importer = new WsdlImporter(metadata); endpoints = importer.ImportAllEndpoints(); return(endpoints.ToArray()); } //Try MEX endpoint: if (address.Scheme == Uri.UriSchemeHttp) { bindingElement = new HttpTransportBindingElement(); } if (address.Scheme == Uri.UriSchemeHttps) { bindingElement = new HttpsTransportBindingElement(); } if (address.Scheme == Uri.UriSchemeNetTcp) { bindingElement = new TcpTransportBindingElement(); } if (address.Scheme == Uri.UriSchemeNetPipe) { bindingElement = new NamedPipeTransportBindingElement(); } endpoints = QueryMexEndpoint(mexAddress, bindingElement); return(endpoints.ToArray()); }
internal static bool TryCreate(BindingElementCollection elements, out Binding binding) { binding = null; if (elements.Count > 3) { return(false); } SecurityBindingElement securityElement = null; MessageEncodingBindingElement encoding = null; HttpTransportBindingElement transport = null; foreach (BindingElement element in elements) { if (element is SecurityBindingElement) { securityElement = element as SecurityBindingElement; } else if (element is TransportBindingElement) { transport = element as HttpTransportBindingElement; } else if (element is MessageEncodingBindingElement) { encoding = element as MessageEncodingBindingElement; } else { return(false); } } HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement; if ((securityElement != null) && (httpsTransport != null) && (httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate)) { return(false); } // process transport binding element UnifiedSecurityMode mode; HttpTransportSecurity transportSecurity = new HttpTransportSecurity(); if (!GetSecurityModeFromTransport(transport, transportSecurity, out mode)) { return(false); } if (encoding == null) { return(false); } // BasicHttpBinding only supports Soap11 if (!encoding.CheckEncodingVersion(EnvelopeVersion.Soap11)) { return(false); } BasicHttpSecurity security; if (!HttpBindingBase.TryCreateSecurity(securityElement, mode, transportSecurity, out security)) { return(false); } BasicHttpBinding basicHttpBinding = new BasicHttpBinding(security); basicHttpBinding.InitializeFrom(transport, encoding); // make sure all our defaults match if (!basicHttpBinding.IsBindingElementsMatch(transport, encoding)) { return(false); } binding = basicHttpBinding; return(true); }
public static ServiceEndpoint[] GetEndpoints(string mexAddress) { if (String.IsNullOrEmpty(mexAddress)) { Debug.Assert(false, "Empty address"); return(null); } Uri address = new Uri(mexAddress); ServiceEndpointCollection endpoints = null; if (address.Scheme == "http") { HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement(); httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier; //Try the HTTP MEX Endpoint try { endpoints = QueryMexEndpoint(mexAddress, httpBindingElement); } catch {} //Try over HTTP-GET if (endpoints == null) { string httpGetAddress = mexAddress; if (mexAddress.EndsWith("?wsdl") == false) { httpGetAddress += "?wsdl"; } CustomBinding binding = new CustomBinding(httpBindingElement); MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding); MetadataSet metadata = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet); MetadataImporter importer = new WsdlImporter(metadata); endpoints = importer.ImportAllEndpoints(); } } if (address.Scheme == "https") { HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement(); httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier; //Try the HTTPS MEX Endpoint try { endpoints = QueryMexEndpoint(mexAddress, httpsBindingElement); } catch {} //Try over HTTP-GET if (endpoints == null) { string httpsGetAddress = mexAddress; if (mexAddress.EndsWith("?wsdl") == false) { httpsGetAddress += "?wsdl"; } CustomBinding binding = new CustomBinding(httpsBindingElement); MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding); MetadataSet metadata = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet); MetadataImporter importer = new WsdlImporter(metadata); endpoints = importer.ImportAllEndpoints(); } } if (address.Scheme == "net.tcp") { TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement(); tcpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier; endpoints = QueryMexEndpoint(mexAddress, tcpBindingElement); } if (address.Scheme == "net.pipe") { NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement(); ipcBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier; endpoints = QueryMexEndpoint(mexAddress, ipcBindingElement); } return(endpoints.ToArray()); }
public static HttpTransportBindingElement BuildHttpTransport(BindingSecurity securityType, MessageSizeQuotas quotas) { if (quotas == null) { quotas = new MessageSizeQuotas() { MaxBufferPoolSize = 524288, MaxBufferSize = 15000000, MaxReceivedMessageSize = 15000000 }; } if (securityType == BindingSecurity.None) { HttpTransportBindingElement httpTransport = new HttpTransportBindingElement(); httpTransport.ManualAddressing = false; httpTransport.AllowCookies = false; httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpTransport.BypassProxyOnLocal = false; httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; httpTransport.KeepAliveEnabled = true; httpTransport.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpTransport.Realm = String.Empty; httpTransport.TransferMode = TransferMode.Buffered; httpTransport.UnsafeConnectionNtlmAuthentication = false; httpTransport.UseDefaultWebProxy = false; httpTransport.MaxBufferPoolSize = quotas.MaxBufferPoolSize; httpTransport.MaxReceivedMessageSize = quotas.MaxReceivedMessageSize; httpTransport.MaxBufferSize = quotas.MaxBufferSize; //httpTransport.ExtendedProtectionPolicy.PolicyEnforcement = System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never; return(httpTransport); } else if (securityType == BindingSecurity.TLS || securityType == BindingSecurity.TLSWithCertificate || securityType == BindingSecurity.Credentials) { HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement(); httpsTransportBindingElement.ManualAddressing = false; httpsTransportBindingElement.MaxBufferPoolSize = quotas.MaxBufferPoolSize; httpsTransportBindingElement.MaxReceivedMessageSize = quotas.MaxReceivedMessageSize; httpsTransportBindingElement.MaxBufferSize = quotas.MaxBufferSize; httpsTransportBindingElement.AllowCookies = false; httpsTransportBindingElement.BypassProxyOnLocal = false; httpsTransportBindingElement.Realm = string.Empty; httpsTransportBindingElement.KeepAliveEnabled = true; httpsTransportBindingElement.TransferMode = TransferMode.Buffered; httpsTransportBindingElement.UnsafeConnectionNtlmAuthentication = false; httpsTransportBindingElement.UseDefaultWebProxy = true; httpsTransportBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; if (securityType == BindingSecurity.TLSWithCertificate) { httpsTransportBindingElement.AuthenticationScheme = System.Net.AuthenticationSchemes.Digest; httpsTransportBindingElement.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Digest; httpsTransportBindingElement.RequireClientCertificate = true; } else { httpsTransportBindingElement.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpsTransportBindingElement.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpsTransportBindingElement.RequireClientCertificate = false; } return(httpsTransportBindingElement); } else { HttpTransportBindingElement httpTransport = new HttpTransportBindingElement(); httpTransport.ManualAddressing = false; httpTransport.MaxBufferPoolSize = quotas.MaxBufferPoolSize; httpTransport.MaxReceivedMessageSize = quotas.MaxReceivedMessageSize; httpTransport.MaxBufferSize = quotas.MaxBufferSize; httpTransport.AllowCookies = false; httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpTransport.BypassProxyOnLocal = false; httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; httpTransport.KeepAliveEnabled = true; httpTransport.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; httpTransport.Realm = String.Empty; httpTransport.TransferMode = TransferMode.Buffered; httpTransport.UnsafeConnectionNtlmAuthentication = false; httpTransport.UseDefaultWebProxy = false; //httpTransport.ExtendedProtectionPolicy.PolicyEnforcement = System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never; return(httpTransport); } }
internal HttpBindingBase() { _httpTransport = new HttpTransportBindingElement(); _textEncoding = new TextMessageEncodingBindingElement(); _textEncoding.MessageVersion = MessageVersion.Soap11; }
internal static void ConfigureTransportAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpTransportBindingElement httpTransportBindingElement) { Debug.Assert(httpTransportSecurity != null, "httpTransportSecurity cannot be null"); Debug.Assert(httpTransportBindingElement != null, "httpTransportBindingElement cannot be null"); if (httpTransportSecurity.ClientCredentialType == HttpClientCredentialType.Certificate) { throw Error.InvalidOperation(SRResources.CertificateUnsupportedForHttpTransportCredentialOnly); } httpTransportSecurity.ConfigureAuthentication(httpTransportBindingElement); }
public async Task <bool> InitalizeDeviceAsync() { try { if (m_services != null) { return(true); } HttpTransportBindingElement httpBinding = new HttpTransportBindingElement(); httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest; var messageElement = new TextMessageEncodingBindingElement(); messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None); CustomBinding binding = new CustomBinding(messageElement, httpBinding); EndpointAddress address = new EndpointAddress($@"http://{m_Hostname}/onvif/device_service"); binding.SendTimeout = binding.CloseTimeout = binding.ReceiveTimeout = binding.OpenTimeout = TimeSpan.FromSeconds(15); m_device = new DeviceClient(binding, address); // var discoverymode = m_device.GetRemoteDiscoveryModeAsync(); bool useAuth = !string.IsNullOrEmpty(m_BasicBasicAuthBehaviour.Username) && !string.IsNullOrEmpty(m_BasicBasicAuthBehaviour.Password); double diff = 0; if (useAuth) { m_device.Endpoint.EndpointBehaviors.Add(m_BasicBasicAuthBehaviour); m_device.Endpoint.EndpointBehaviors.Add(m_PasswordDigestBehavior); } //ensure date and time are in sync //add basic auth for compat with some cameras m_SystemDateTime = await m_device.GetSystemDateAndTimeAsync(); var d = m_SystemDateTime.UTCDateTime.Date; var t = m_SystemDateTime.UTCDateTime.Time; var dt = new System.DateTime(d.Year, d.Month, d.Day, t.Hour, t.Minute, t.Second); diff = (System.DateTime.UtcNow - dt).TotalSeconds; m_PasswordDigestBehavior.TimeOffset = diff; GetDeviceInformationRequest request = new GetDeviceInformationRequest(); m_deviceInformations = await m_device.GetDeviceInformationAsync(request); this.m_HostnameInformation = await m_device.GetHostnameAsync(); m_services = await m_device.GetServicesAsync(true); } catch (Exception ex) { m_ErrorMessage = ex.Message; throw new OnVifException("OnVifDevice.InitalizeDeviceAsync", ex); // return false; } return(m_services != null); }
protected override void ApplyTransportSecurity(HttpTransportBindingElement transport) { throw new NotSupportedException(); }
private static bool IsDisabledAuthentication(HttpTransportBindingElement http) { return(http.AuthenticationScheme == AuthenticationSchemes.Anonymous && http.Realm == DefaultRealm); }
public static void CheckBasicHttpBinding( Binding binding, string scheme, BasicHttpSecurityMode security, WSMessageEncoding encoding, HttpClientCredentialType clientCred, AuthenticationSchemes authScheme, TestLabel label) { label.EnterScope("http"); if (security == BasicHttpSecurityMode.Message) { Assert.That(binding, Is.InstanceOfType(typeof(CustomBinding)), label.Get()); } else { Assert.That(binding, Is.InstanceOfType(typeof(BasicHttpBinding)), label.Get()); var basicHttp = (BasicHttpBinding)binding; Assert.That(basicHttp.EnvelopeVersion, Is.EqualTo(EnvelopeVersion.Soap11), label.Get()); Assert.That(basicHttp.MessageVersion, Is.EqualTo(MessageVersion.Soap11), label.Get()); Assert.That(basicHttp.Scheme, Is.EqualTo(scheme), label.Get()); Assert.That(basicHttp.TransferMode, Is.EqualTo(TransferMode.Buffered), label.Get()); Assert.That(basicHttp.MessageEncoding, Is.EqualTo(encoding), label.Get()); Assert.That(basicHttp.Security, Is.Not.Null, label.Get()); Assert.That(basicHttp.Security.Mode, Is.EqualTo(security), label.Get()); Assert.That(basicHttp.Security.Transport.ClientCredentialType, Is.EqualTo(clientCred), label.Get()); Assert.That(basicHttp.Security.Message.AlgorithmSuite, Is.EqualTo(SecurityAlgorithmSuite.Basic256), label.Get()); } label.EnterScope("elements"); var elements = binding.CreateBindingElements(); Assert.That(elements, Is.Not.Null, label.Get()); if ((security == BasicHttpSecurityMode.Message) || (security == BasicHttpSecurityMode.TransportWithMessageCredential)) { Assert.That(elements.Count, Is.EqualTo(3), label.Get()); } else { Assert.That(elements.Count, Is.EqualTo(2), label.Get()); } TextMessageEncodingBindingElement textElement = null; TransportSecurityBindingElement securityElement = null; HttpTransportBindingElement transportElement = null; AsymmetricSecurityBindingElement asymmSecurityElement = null; MtomMessageEncodingBindingElement mtomElement = null; foreach (var element in elements) { if (element is TextMessageEncodingBindingElement) { textElement = (TextMessageEncodingBindingElement)element; } else if (element is HttpTransportBindingElement) { transportElement = (HttpTransportBindingElement)element; } else if (element is TransportSecurityBindingElement) { securityElement = (TransportSecurityBindingElement)element; } else if (element is AsymmetricSecurityBindingElement) { asymmSecurityElement = (AsymmetricSecurityBindingElement)element; } else if (element is MtomMessageEncodingBindingElement) { mtomElement = (MtomMessageEncodingBindingElement)element; } else { Assert.Fail(string.Format( "Unknown element: {0}", element.GetType()), label.Get()); } } label.EnterScope("text"); if (encoding == WSMessageEncoding.Text) { Assert.That(textElement, Is.Not.Null, label.Get()); Assert.That(textElement.WriteEncoding, Is.InstanceOfType(typeof(UTF8Encoding)), label.Get()); } else { Assert.That(textElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("mtom"); if (encoding == WSMessageEncoding.Mtom) { Assert.That(mtomElement, Is.Not.Null, label.Get()); } else { Assert.That(mtomElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("security"); if (security == BasicHttpSecurityMode.TransportWithMessageCredential) { Assert.That(securityElement, Is.Not.Null, label.Get()); Assert.That(securityElement.SecurityHeaderLayout, Is.EqualTo(SecurityHeaderLayout.Lax), label.Get()); } else { Assert.That(securityElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("asymmetric"); if (security == BasicHttpSecurityMode.Message) { Assert.That(asymmSecurityElement, Is.Not.Null, label.Get()); } else { Assert.That(asymmSecurityElement, Is.Null, label.Get()); } label.LeaveScope(); label.EnterScope("transport"); Assert.That(transportElement, Is.Not.Null, label.Get()); Assert.That(transportElement.Realm, Is.Empty, label.Get()); Assert.That(transportElement.Scheme, Is.EqualTo(scheme), label.Get()); Assert.That(transportElement.TransferMode, Is.EqualTo(TransferMode.Buffered), label.Get()); label.EnterScope("auth"); Assert.That(transportElement.AuthenticationScheme, Is.EqualTo(authScheme), label.Get()); label.LeaveScope(); // auth label.LeaveScope(); // transport label.LeaveScope(); // elements label.LeaveScope(); // http }
static void FillBindingInfo(BindingElement bindingElement, ref IWmiInstance instance) { Fx.Assert(null != bindingElement, ""); Fx.Assert(null != instance, ""); if (bindingElement is IWmiInstanceProvider) { IWmiInstanceProvider instanceProvider = (IWmiInstanceProvider)bindingElement; instance = instance.NewInstance(instanceProvider.GetInstanceType()); instanceProvider.FillInstance(instance); return; } Type elementType = AdministrationHelpers.GetServiceModelBaseType(bindingElement.GetType()); if (null != elementType) { instance = instance.NewInstance(elementType.Name); if (bindingElement is TransportBindingElement) { TransportBindingElement transport = (TransportBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.ManualAddressing, transport.ManualAddressing); instance.SetProperty(AdministrationStrings.MaxReceivedMessageSize, transport.MaxReceivedMessageSize); instance.SetProperty(AdministrationStrings.MaxBufferPoolSize, transport.MaxBufferPoolSize); instance.SetProperty(AdministrationStrings.Scheme, transport.Scheme); if (bindingElement is ConnectionOrientedTransportBindingElement) { ConnectionOrientedTransportBindingElement connectionOriented = (ConnectionOrientedTransportBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.ConnectionBufferSize, connectionOriented.ConnectionBufferSize); instance.SetProperty(AdministrationStrings.HostNameComparisonMode, connectionOriented.HostNameComparisonMode.ToString()); instance.SetProperty(AdministrationStrings.ChannelInitializationTimeout, connectionOriented.ChannelInitializationTimeout); instance.SetProperty(AdministrationStrings.MaxBufferSize, connectionOriented.MaxBufferSize); instance.SetProperty(AdministrationStrings.MaxPendingConnections, connectionOriented.MaxPendingConnections); instance.SetProperty(AdministrationStrings.MaxOutputDelay, connectionOriented.MaxOutputDelay); instance.SetProperty(AdministrationStrings.MaxPendingAccepts, connectionOriented.MaxPendingAccepts); instance.SetProperty(AdministrationStrings.TransferMode, connectionOriented.TransferMode.ToString()); if (bindingElement is TcpTransportBindingElement) { TcpTransportBindingElement tcp = (TcpTransportBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.ListenBacklog, tcp.ListenBacklog); instance.SetProperty(AdministrationStrings.PortSharingEnabled, tcp.PortSharingEnabled); instance.SetProperty(AdministrationStrings.TeredoEnabled, tcp.TeredoEnabled); IWmiInstance connectionPool = instance.NewInstance(AdministrationStrings.TcpConnectionPoolSettings); connectionPool.SetProperty(AdministrationStrings.GroupName, tcp.ConnectionPoolSettings.GroupName); connectionPool.SetProperty(AdministrationStrings.IdleTimeout, tcp.ConnectionPoolSettings.IdleTimeout); connectionPool.SetProperty(AdministrationStrings.LeaseTimeout, tcp.ConnectionPoolSettings.LeaseTimeout); connectionPool.SetProperty(AdministrationStrings.MaxOutboundConnectionsPerEndpoint, tcp.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint); instance.SetProperty(AdministrationStrings.ConnectionPoolSettings, connectionPool); FillExtendedProtectionPolicy(instance, tcp.ExtendedProtectionPolicy); } else if (bindingElement is NamedPipeTransportBindingElement) { NamedPipeTransportBindingElement namedPipe = (NamedPipeTransportBindingElement)bindingElement; IWmiInstance connectionPool = instance.NewInstance(AdministrationStrings.NamedPipeConnectionPoolSettings); connectionPool.SetProperty(AdministrationStrings.GroupName, namedPipe.ConnectionPoolSettings.GroupName); connectionPool.SetProperty(AdministrationStrings.IdleTimeout, namedPipe.ConnectionPoolSettings.IdleTimeout); connectionPool.SetProperty(AdministrationStrings.MaxOutboundConnectionsPerEndpoint, namedPipe.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint); instance.SetProperty(AdministrationStrings.ConnectionPoolSettings, connectionPool); } } else if (bindingElement is HttpTransportBindingElement) { HttpTransportBindingElement http = (HttpTransportBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.AllowCookies, http.AllowCookies); instance.SetProperty(AdministrationStrings.AuthenticationScheme, http.AuthenticationScheme.ToString()); instance.SetProperty(AdministrationStrings.BypassProxyOnLocal, http.BypassProxyOnLocal); instance.SetProperty(AdministrationStrings.DecompressionEnabled, http.DecompressionEnabled); instance.SetProperty(AdministrationStrings.HostNameComparisonMode, http.HostNameComparisonMode.ToString()); instance.SetProperty(AdministrationStrings.KeepAliveEnabled, http.KeepAliveEnabled); instance.SetProperty(AdministrationStrings.MaxBufferSize, http.MaxBufferSize); if (null != http.ProxyAddress) { instance.SetProperty(AdministrationStrings.ProxyAddress, http.ProxyAddress.AbsoluteUri.ToString()); } instance.SetProperty(AdministrationStrings.ProxyAuthenticationScheme, http.ProxyAuthenticationScheme.ToString()); instance.SetProperty(AdministrationStrings.Realm, http.Realm); instance.SetProperty(AdministrationStrings.TransferMode, http.TransferMode.ToString()); instance.SetProperty(AdministrationStrings.UnsafeConnectionNtlmAuthentication, http.UnsafeConnectionNtlmAuthentication); instance.SetProperty(AdministrationStrings.UseDefaultWebProxy, http.UseDefaultWebProxy); FillExtendedProtectionPolicy(instance, http.ExtendedProtectionPolicy); if (bindingElement is HttpsTransportBindingElement) { HttpsTransportBindingElement https = (HttpsTransportBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.RequireClientCertificate, https.RequireClientCertificate); } } else if (bindingElement is MsmqBindingElementBase) { MsmqBindingElementBase msmq = (MsmqBindingElementBase)bindingElement; if (null != msmq.CustomDeadLetterQueue) { instance.SetProperty(AdministrationStrings.CustomDeadLetterQueue, msmq.CustomDeadLetterQueue.AbsoluteUri.ToString()); } instance.SetProperty(AdministrationStrings.DeadLetterQueue, msmq.DeadLetterQueue); instance.SetProperty(AdministrationStrings.Durable, msmq.Durable); instance.SetProperty(AdministrationStrings.ExactlyOnce, msmq.ExactlyOnce); instance.SetProperty(AdministrationStrings.MaxRetryCycles, msmq.MaxRetryCycles); instance.SetProperty(AdministrationStrings.ReceiveContextEnabled, msmq.ReceiveContextEnabled); instance.SetProperty(AdministrationStrings.ReceiveErrorHandling, msmq.ReceiveErrorHandling); instance.SetProperty(AdministrationStrings.ReceiveRetryCount, msmq.ReceiveRetryCount); instance.SetProperty(AdministrationStrings.RetryCycleDelay, msmq.RetryCycleDelay); instance.SetProperty(AdministrationStrings.TimeToLive, msmq.TimeToLive); instance.SetProperty(AdministrationStrings.UseSourceJournal, msmq.UseSourceJournal); instance.SetProperty(AdministrationStrings.UseMsmqTracing, msmq.UseMsmqTracing); instance.SetProperty(AdministrationStrings.ValidityDuration, msmq.ValidityDuration); MsmqTransportBindingElement msmqTransport = msmq as MsmqTransportBindingElement; if (null != msmqTransport) { instance.SetProperty(AdministrationStrings.MaxPoolSize, msmqTransport.MaxPoolSize); instance.SetProperty(AdministrationStrings.QueueTransferProtocol, msmqTransport.QueueTransferProtocol); instance.SetProperty(AdministrationStrings.UseActiveDirectory, msmqTransport.UseActiveDirectory); } MsmqIntegrationBindingElement msmqIntegration = msmq as MsmqIntegrationBindingElement; if (null != msmqIntegration) { instance.SetProperty(AdministrationStrings.SerializationFormat, msmqIntegration.SerializationFormat.ToString()); } } #pragma warning disable 0618 else if (bindingElement is PeerTransportBindingElement) { PeerTransportBindingElement peer = (PeerTransportBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.ListenIPAddress, peer.ListenIPAddress); instance.SetProperty(AdministrationStrings.Port, peer.Port); IWmiInstance securitySettings = instance.NewInstance(AdministrationStrings.PeerSecuritySettings); securitySettings.SetProperty(AdministrationStrings.PeerSecurityMode, peer.Security.Mode.ToString()); IWmiInstance transportSecuritySettings = securitySettings.NewInstance(AdministrationStrings.PeerTransportSecuritySettings); transportSecuritySettings.SetProperty(AdministrationStrings.PeerTransportCredentialType, peer.Security.Transport.CredentialType.ToString()); securitySettings.SetProperty(AdministrationStrings.Transport, transportSecuritySettings); instance.SetProperty(AdministrationStrings.Security, securitySettings); } } else if (bindingElement is PeerResolverBindingElement) { PeerResolverBindingElement baseResolver = (PeerResolverBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.ReferralPolicy, baseResolver.ReferralPolicy.ToString()); if (bindingElement is PeerCustomResolverBindingElement) { PeerCustomResolverBindingElement specificElement = (PeerCustomResolverBindingElement)bindingElement; if (specificElement.Address != null) { instance.SetProperty(AdministrationStrings.Address, specificElement.Address.ToString()); } if (specificElement.Binding != null) { instance.SetProperty(AdministrationStrings.Binding, specificElement.Binding.ToString()); } } } #pragma warning restore 0618 else if (bindingElement is ReliableSessionBindingElement) { ReliableSessionBindingElement specificElement = (ReliableSessionBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.AcknowledgementInterval, specificElement.AcknowledgementInterval); instance.SetProperty(AdministrationStrings.FlowControlEnabled, specificElement.FlowControlEnabled); instance.SetProperty(AdministrationStrings.InactivityTimeout, specificElement.InactivityTimeout); instance.SetProperty(AdministrationStrings.MaxPendingChannels, specificElement.MaxPendingChannels); instance.SetProperty(AdministrationStrings.MaxRetryCount, specificElement.MaxRetryCount); instance.SetProperty(AdministrationStrings.MaxTransferWindowSize, specificElement.MaxTransferWindowSize); instance.SetProperty(AdministrationStrings.Ordered, specificElement.Ordered); instance.SetProperty(AdministrationStrings.ReliableMessagingVersion, specificElement.ReliableMessagingVersion.ToString()); } else if (bindingElement is SecurityBindingElement) { SecurityBindingElement specificElement = (SecurityBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.AllowInsecureTransport, specificElement.AllowInsecureTransport); instance.SetProperty(AdministrationStrings.DefaultAlgorithmSuite, specificElement.DefaultAlgorithmSuite.ToString()); instance.SetProperty(AdministrationStrings.EnableUnsecuredResponse, specificElement.EnableUnsecuredResponse); instance.SetProperty(AdministrationStrings.IncludeTimestamp, specificElement.IncludeTimestamp); instance.SetProperty(AdministrationStrings.KeyEntropyMode, specificElement.KeyEntropyMode.ToString()); instance.SetProperty(AdministrationStrings.SecurityHeaderLayout, specificElement.SecurityHeaderLayout.ToString()); instance.SetProperty(AdministrationStrings.MessageSecurityVersion, specificElement.MessageSecurityVersion.ToString()); IWmiInstance localServiceSecuritySettings = instance.NewInstance(AdministrationStrings.LocalServiceSecuritySettings); localServiceSecuritySettings.SetProperty(AdministrationStrings.DetectReplays, specificElement.LocalServiceSettings.DetectReplays); localServiceSecuritySettings.SetProperty(AdministrationStrings.InactivityTimeout, specificElement.LocalServiceSettings.InactivityTimeout); localServiceSecuritySettings.SetProperty(AdministrationStrings.IssuedCookieLifetime, specificElement.LocalServiceSettings.IssuedCookieLifetime); localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxCachedCookies, specificElement.LocalServiceSettings.MaxCachedCookies); localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxClockSkew, specificElement.LocalServiceSettings.MaxClockSkew); localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxPendingSessions, specificElement.LocalServiceSettings.MaxPendingSessions); localServiceSecuritySettings.SetProperty(AdministrationStrings.MaxStatefulNegotiations, specificElement.LocalServiceSettings.MaxStatefulNegotiations); localServiceSecuritySettings.SetProperty(AdministrationStrings.NegotiationTimeout, specificElement.LocalServiceSettings.NegotiationTimeout); localServiceSecuritySettings.SetProperty(AdministrationStrings.ReconnectTransportOnFailure, specificElement.LocalServiceSettings.ReconnectTransportOnFailure); localServiceSecuritySettings.SetProperty(AdministrationStrings.ReplayCacheSize, specificElement.LocalServiceSettings.ReplayCacheSize); localServiceSecuritySettings.SetProperty(AdministrationStrings.ReplayWindow, specificElement.LocalServiceSettings.ReplayWindow); localServiceSecuritySettings.SetProperty(AdministrationStrings.SessionKeyRenewalInterval, specificElement.LocalServiceSettings.SessionKeyRenewalInterval); localServiceSecuritySettings.SetProperty(AdministrationStrings.SessionKeyRolloverInterval, specificElement.LocalServiceSettings.SessionKeyRolloverInterval); localServiceSecuritySettings.SetProperty(AdministrationStrings.TimestampValidityDuration, specificElement.LocalServiceSettings.TimestampValidityDuration); instance.SetProperty(AdministrationStrings.LocalServiceSecuritySettings, localServiceSecuritySettings); if (bindingElement is AsymmetricSecurityBindingElement) { AsymmetricSecurityBindingElement specificElement1 = (AsymmetricSecurityBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.MessageProtectionOrder, specificElement1.MessageProtectionOrder.ToString()); instance.SetProperty(AdministrationStrings.RequireSignatureConfirmation, specificElement1.RequireSignatureConfirmation); } else if (bindingElement is SymmetricSecurityBindingElement) { SymmetricSecurityBindingElement specificElement1 = (SymmetricSecurityBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.MessageProtectionOrder, specificElement1.MessageProtectionOrder.ToString()); instance.SetProperty(AdministrationStrings.RequireSignatureConfirmation, specificElement1.RequireSignatureConfirmation); } } else if (bindingElement is WindowsStreamSecurityBindingElement) { WindowsStreamSecurityBindingElement specificElement = (WindowsStreamSecurityBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.ProtectionLevel, specificElement.ProtectionLevel.ToString()); } else if (bindingElement is SslStreamSecurityBindingElement) { SslStreamSecurityBindingElement specificElement = (SslStreamSecurityBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.RequireClientCertificate, specificElement.RequireClientCertificate); } else if (bindingElement is CompositeDuplexBindingElement) { CompositeDuplexBindingElement specificElement = (CompositeDuplexBindingElement)bindingElement; if (specificElement.ClientBaseAddress != null) { instance.SetProperty(AdministrationStrings.ClientBaseAddress, specificElement.ClientBaseAddress.AbsoluteUri); } } else if (bindingElement is OneWayBindingElement) { OneWayBindingElement oneWay = (OneWayBindingElement)bindingElement; IWmiInstance channelPoolSettings = instance.NewInstance(AdministrationStrings.ChannelPoolSettings); channelPoolSettings.SetProperty(AdministrationStrings.IdleTimeout, oneWay.ChannelPoolSettings.IdleTimeout); channelPoolSettings.SetProperty(AdministrationStrings.LeaseTimeout, oneWay.ChannelPoolSettings.LeaseTimeout); channelPoolSettings.SetProperty(AdministrationStrings.MaxOutboundChannelsPerEndpoint, oneWay.ChannelPoolSettings.MaxOutboundChannelsPerEndpoint); instance.SetProperty(AdministrationStrings.ChannelPoolSettings, channelPoolSettings); instance.SetProperty(AdministrationStrings.PacketRoutable, oneWay.PacketRoutable); instance.SetProperty(AdministrationStrings.MaxAcceptedChannels, oneWay.MaxAcceptedChannels); } else if (bindingElement is MessageEncodingBindingElement) { MessageEncodingBindingElement encodingElement = (MessageEncodingBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.MessageVersion, encodingElement.MessageVersion.ToString()); if (bindingElement is BinaryMessageEncodingBindingElement) { BinaryMessageEncodingBindingElement specificElement = (BinaryMessageEncodingBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.MaxSessionSize, specificElement.MaxSessionSize); instance.SetProperty(AdministrationStrings.MaxReadPoolSize, specificElement.MaxReadPoolSize); instance.SetProperty(AdministrationStrings.MaxWritePoolSize, specificElement.MaxWritePoolSize); if (null != specificElement.ReaderQuotas) { FillReaderQuotas(instance, specificElement.ReaderQuotas); } instance.SetProperty(AdministrationStrings.CompressionFormat, specificElement.CompressionFormat.ToString()); } else if (bindingElement is TextMessageEncodingBindingElement) { TextMessageEncodingBindingElement specificElement = (TextMessageEncodingBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.Encoding, specificElement.WriteEncoding.WebName); instance.SetProperty(AdministrationStrings.MaxReadPoolSize, specificElement.MaxReadPoolSize); instance.SetProperty(AdministrationStrings.MaxWritePoolSize, specificElement.MaxWritePoolSize); if (null != specificElement.ReaderQuotas) { FillReaderQuotas(instance, specificElement.ReaderQuotas); } } else if (bindingElement is MtomMessageEncodingBindingElement) { MtomMessageEncodingBindingElement specificElement = (MtomMessageEncodingBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.Encoding, specificElement.WriteEncoding.WebName); instance.SetProperty(AdministrationStrings.MessageVersion, specificElement.MessageVersion.ToString()); instance.SetProperty(AdministrationStrings.MaxReadPoolSize, specificElement.MaxReadPoolSize); instance.SetProperty(AdministrationStrings.MaxWritePoolSize, specificElement.MaxWritePoolSize); if (null != specificElement.ReaderQuotas) { FillReaderQuotas(instance, specificElement.ReaderQuotas); } } } else if (bindingElement is TransactionFlowBindingElement) { TransactionFlowBindingElement specificElement = (TransactionFlowBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.TransactionFlow, specificElement.Transactions); instance.SetProperty(AdministrationStrings.TransactionProtocol, specificElement.TransactionProtocol.ToString()); instance.SetProperty(AdministrationStrings.AllowWildcardAction, specificElement.AllowWildcardAction); } else if (bindingElement is PrivacyNoticeBindingElement) { PrivacyNoticeBindingElement specificElement = (PrivacyNoticeBindingElement)bindingElement; instance.SetProperty(AdministrationStrings.Url, specificElement.Url.ToString()); instance.SetProperty(AdministrationStrings.PrivacyNoticeVersion, specificElement.Version); } } }
// It is almost identical to http-low-level-binding public void LowLevelHttpConnection() { HttpTransportBindingElement lel = new HttpTransportBindingElement(); // Service BindingContext lbc = new BindingContext( new CustomBinding(), new BindingParameterCollection(), new Uri("http://localhost:" + NetworkHelpers.FindFreePort()), String.Empty, ListenUriMode.Explicit); listener = lel.BuildChannelListener <IReplyChannel> (lbc); try { listener.Open(); svcret = ""; Thread svc = new Thread(delegate() { try { svcret = LowLevelHttpConnection_SetupService(); } catch (Exception ex) { svcret = ex.ToString(); } }); svc.Start(); // Client code goes here. HttpTransportBindingElement el = new HttpTransportBindingElement(); BindingContext ctx = new BindingContext( new CustomBinding(), new BindingParameterCollection()); IChannelFactory <IRequestChannel> factory = el.BuildChannelFactory <IRequestChannel> (ctx); factory.Open(); IRequestChannel request = factory.CreateChannel( new EndpointAddress("http://localhost:" + NetworkHelpers.FindFreePort())); request.Open(); try { try { Message reqmsg = Message.CreateMessage( MessageVersion.Default, "Echo"); // sync version does not work here. Message msg = request.Request(reqmsg, TimeSpan.FromSeconds(5)); using (XmlWriter w = XmlWriter.Create(TextWriter.Null)) { msg.WriteMessage(w); } if (svcret != null) { Assert.Fail(svcret.Length > 0 ? svcret : "service code did not finish until this test expected."); } } finally { if (request.State == CommunicationState.Opened) { request.Close(); } } } finally { if (factory.State == CommunicationState.Opened) { factory.Close(); } } } finally { if (listener.State == CommunicationState.Opened) { listener.Close(); } } }