//initialize a SampleProfileUdpBinding from the info collected in a ReliableSessionBindingElement if one is present. void InitializeFrom(UdpTransportBindingElement udpTransportBindingElement, TextMessageEncodingBindingElement textMessageEncodingBindingElement, ReliableSessionBindingElement reliableSessionBindingElement, CompositeDuplexBindingElement compositeDuplexBindingElement) { this.transport.Multicast = udpTransportBindingElement.Multicast; this.transport.MaxBufferPoolSize = udpTransportBindingElement.MaxBufferPoolSize; this.transport.MaxReceivedMessageSize = udpTransportBindingElement.MaxReceivedMessageSize; ((TextMessageEncodingBindingElement)this.encoding).WriteEncoding = textMessageEncodingBindingElement.WriteEncoding; textMessageEncodingBindingElement.ReaderQuotas.CopyTo(((TextMessageEncodingBindingElement)this.encoding).ReaderQuotas); this.ReliableSessionEnabled = reliableSessionBindingElement != null; if (reliableSessionBindingElement != null) { this.SessionInactivityTimeout = reliableSessionBindingElement.InactivityTimeout; this.OrderedSession = reliableSessionBindingElement.Ordered; } if (compositeDuplexBindingElement != null) { this.ClientBaseAddress = compositeDuplexBindingElement.ClientBaseAddress; } }
internal static void SyncUpEncodingBindingElementProperties(TextMessageEncodingBindingElement textEncoding, MtomMessageEncodingBindingElement mtomEncoding) { // textEncoding provides the backing store for ReaderQuotas and WriteEncoding, // we must ensure same values propogate to mtomEncoding textEncoding.ReaderQuotas.CopyTo(mtomEncoding.ReaderQuotas); mtomEncoding.WriteEncoding = textEncoding.WriteEncoding; }
public static Binding GetIssuedTokenBindingSSL() { var textmessageEncoding = new TextMessageEncodingBindingElement(); textmessageEncoding.WriteEncoding = Encoding.UTF8; textmessageEncoding.MessageVersion = MessageVersion.Soap11WSAddressing10; var messageSecurity = new AsymmetricSecurityBindingElement(); messageSecurity.AllowSerializedSigningTokenOnReply = true; messageSecurity.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10; var x509SecurityParamter = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.RawDataKeyIdentifier, SecurityTokenInclusionMode.AlwaysToInitiator); messageSecurity.RecipientTokenParameters = x509SecurityParamter; messageSecurity.RecipientTokenParameters.RequireDerivedKeys = false; var initiator = new X509SecurityTokenParameters(X509KeyIdentifierClauseType.RawDataKeyIdentifier, SecurityTokenInclusionMode.AlwaysToRecipient); initiator.RequireDerivedKeys = false; messageSecurity.InitiatorTokenParameters = initiator; messageSecurity.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt; return(new CustomBinding( messageSecurity, textmessageEncoding, new HttpsTransportBindingElement())); }
public static void Main(string[] args) { var transportBinding = new HttpTransportBindingElement(); var textEncodingBinding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, System.Text.Encoding.UTF8); var binding = new CustomBinding(textEncodingBinding, transportBinding); var endpoint = new EndpointAddress(new Uri("http://webservices.nbgz.me/Services.svc")); //var endpoint = new EndpointAddress(new Uri(string.Format("http://{0}:5000/Services.svc", Environment.MachineName))); var channelFactory = new ChannelFactory <IServices>(binding, endpoint); var serviceClient = channelFactory.CreateChannel(); var result = serviceClient.EnviarMensaje("hola"); Console.WriteLine("Resultado de metodo de EnviarMensaje: {0}", result); var input = new PedidoModelInput { Productos = new List <Producto>() { { new Producto() { NombreProducto = "Coca Cola", Cantidad = 10, PrecioUnitario = 12.7m } }, { new Producto() { NombreProducto = "Pepsi", Cantidad = 5, PrecioUnitario = 12 } } } }; var resultado = serviceClient.CalcularPedido(input); Console.WriteLine($"Calculo del pedido, Subtotal: {resultado.SubTotal}, Impuestos: {resultado.Impuestos}, Total: {resultado.Total}"); Console.ReadKey(); }
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); }
public TextMessageEncoderFactory ( TextMessageEncodingBindingElement owner) { this.owner = owner; encoder = new TextMessageEncoder ( MessageVersion, owner.WriteEncoding); }
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(); } }
private void InitializeFrom(HttpRelayTransportBindingElement transport, MessageEncodingBindingElement encoding, System.ServiceModel.Channels.ReliableSessionBindingElement session) { 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 textMessageEncodingBindingElement = (TextMessageEncodingBindingElement)encoding; this.TextEncoding = textMessageEncodingBindingElement.WriteEncoding; this.ReaderQuotas = textMessageEncodingBindingElement.ReaderQuotas; } else if (encoding is MtomMessageEncodingBindingElement) { this.messageEncoding = WSMessageEncoding.Mtom; MtomMessageEncodingBindingElement mtomMessageEncodingBindingElement = (MtomMessageEncodingBindingElement)encoding; this.TextEncoding = mtomMessageEncodingBindingElement.WriteEncoding; this.ReaderQuotas = mtomMessageEncodingBindingElement.ReaderQuotas; } this.reliableSession.Enabled = session != null; if (session != null) { this.session.InactivityTimeout = session.InactivityTimeout; this.session.Ordered = session.Ordered; } }
private static IEnumerable<BindingElement> CreateBindingElements(bool mtomEncoding, bool wsAddressing, bool securityToken, bool useTls){ var msgVer = wsAddressing ? MessageVersion.Soap12WSAddressing10 : MessageVersion.Soap12; if(mtomEncoding){ var encoding = new MtomMessageEncodingBindingElement(msgVer, Encoding.UTF8); encoding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue; encoding.MaxBufferSize = Int32.MaxValue; yield return encoding; }else{ var encoding = new TextMessageEncodingBindingElement(msgVer, Encoding.UTF8); encoding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue; //100 * 1024 * 1024 yield return encoding; } //var security = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); //security..M .MessageSecurityVersion = MessageSecurityVersion. HttpTransportBindingElement transport = CreateTransportBindingElement(useTls); transport.MaxReceivedMessageSize = Int32.MaxValue; //100L * 1024L * 1024L transport.KeepAliveEnabled = false; transport.MaxBufferSize = Int32.MaxValue; transport.ProxyAddress = null; transport.BypassProxyOnLocal = true; //transport.ManualAddressing = true transport.UseDefaultWebProxy = false; transport.TransferMode =TransferMode.StreamedResponse; //transport.TransferMode = TransfeStreamedResponse transport.AuthenticationScheme = AuthenticationSchemes.Basic; //transport.AuthenticationScheme = AuthenticationSchemes.Digest; yield return transport; }
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; }
static void Main(string[] args) { try { //建立和发送端相同的通道栈 BindingElement[] bindingElements = new BindingElement[3]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new OneWayBindingElement(); bindingElements[2] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); //建立ChannelListner IChannelListener <IInputChannel> listener = binding.BuildChannelListener <IInputChannel>(new Uri("http://localhost/InputService"), new BindingParameterCollection()); listener.Open(); //创建IInputChannel IInputChannel inputChannel = listener.AcceptChannel(); inputChannel.Open(); Console.WriteLine("开始接受消息。。。"); //接受并打印消息 Message message = inputChannel.Receive(); Console.WriteLine("接受到一条消息,action为:{0},body为:{1}", message.Headers.Action, message.GetBody <String>()); message.Close(); inputChannel.Close(); listener.Close(); Console.Read(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.Read(); } }
public void ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context) { BindingElementCollection bindingElements = context.Endpoint.Binding.CreateBindingElements(); MessageEncodingBindingElement encodingBindingElement = bindingElements.Find <MessageEncodingBindingElement>(); if (encodingBindingElement == null) { encodingBindingElement = new TextMessageEncodingBindingElement(); } // Set SoapBinding Transport URI if (UdpPolicyStrings.UdpNamespace != null) { WsdlNS.SoapBinding soapBinding = GetSoapBinding(context, exporter); if (soapBinding != null) { soapBinding.Transport = UdpPolicyStrings.UdpNamespace; } } if (context.WsdlPort != null) { AddAddressToWsdlPort(context.WsdlPort, context.Endpoint.Address, encodingBindingElement.MessageVersion.Addressing); } }
public static System.ServiceModel.Channels.Binding CreateMultiFactorAuthenticationBinding() { HttpsTransportBindingElement httpTransport = new HttpsTransportBindingElement(); httpTransport.MaxReceivedMessageSize = int.MaxValue; //AddressHeader addressHeader = AddressHeader.CreateAddressHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", security, xmlObjectSerializer); CustomBinding binding = new CustomBinding(); binding.Name = "myCustomBinding"; TransportSecurityBindingElement messageSecurity = TransportSecurityBindingElement.CreateUserNameOverTransportBindingElement(); messageSecurity.IncludeTimestamp = false; messageSecurity.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12; messageSecurity.SecurityHeaderLayout = SecurityHeaderLayout.Strict; messageSecurity.SetKeyDerivation(false); TextMessageEncodingBindingElement Quota = new TextMessageEncodingBindingElement(MessageVersion.Soap11, System.Text.Encoding.UTF8); Quota.ReaderQuotas.MaxDepth = 32; Quota.ReaderQuotas.MaxStringContentLength = Int32.MaxValue; Quota.ReaderQuotas.MaxArrayLength = 16384; Quota.ReaderQuotas.MaxBytesPerRead = 4096; Quota.ReaderQuotas.MaxNameTableCharCount = 16384; binding.Elements.Add(Quota); binding.Elements.Add(messageSecurity); binding.Elements.Add(httpTransport); return(binding); }
private void Initialize() { HttpTransport = new HttpTransportBindingElement(); HttpsTransport = new HttpsTransportBindingElement(); _textEncoding = new TextMessageEncodingBindingElement(); _textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10; }
private MessageEncoder GetEncoder(string contentType) { //todo: this method is not completely implemented. Look at comments bellow. if (Regex.IsMatch(contentType, "^multipart.*")) { var mtomBindingElement = new MtomMessageEncodingBindingElement(_factory.MessageVersion, Encoding.GetEncoding(_factory.CharSet)); var mtomFactory = mtomBindingElement.CreateMessageEncoderFactory(); return(mtomFactory.Encoder); //return _mtomEncoder; } else // if (...) { var textBindingElement = new TextMessageEncodingBindingElement(_factory.MessageVersion, Encoding.GetEncoding(_factory.CharSet)); //textBindingElement.ReaderQuotas.MaxStringContentLength = 65535; //textBindingElement.ReaderQuotas.MaxStringContentLength = textBindingElement.ReaderQuotas.MaxBytesPerRead = 65535; textBindingElement.ReaderQuotas.MaxStringContentLength = textBindingElement.ReaderQuotas.MaxBytesPerRead = 1024 * 1024 * 16; var textFactory = textBindingElement.CreateMessageEncoderFactory(); return(textFactory.Encoder); //return _textEncoder; } //else if (...) //{ // return new BinaryMessageEncodingBindingElement(); //} throw new NotSupportedException(string.Format("Unexpected content-type: \"{0}\".", contentType)); }
private void InitializeFrom(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding, TransactionFlowBindingElement txFlow, ReliableSessionBindingElement session, CompositeDuplexBindingElement compositeDuplex, OneWayBindingElement oneWay) { 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.ClientBaseAddress = compositeDuplex.ClientBaseAddress; if (session != null) { this.session.InactivityTimeout = session.InactivityTimeout; this.session.Ordered = session.Ordered; } }
//入口方法 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")) { //创建ChannelFactory IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection()); factory.Open(); //这里创建IRequestChannel IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost/RequestReplyService")); requestChannel.Open(); //发送消息 Message response = requestChannel.Request(message); Console.WriteLine("已经成功发送消息!"); //查看返回消息 Console.WriteLine("接受到一条返回消息,action为:{0},body为:{1}", response.Headers.Action, response.GetBody <String>()); requestChannel.Close(); factory.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(); } }
void FillMessageEncoder (BindingContext ctx) { var mbe = (MessageEncodingBindingElement) ctx.Binding.Elements.FirstOrDefault (be => be is MessageEncodingBindingElement); if (mbe == null) mbe = new TextMessageEncodingBindingElement (); message_encoder = mbe.CreateMessageEncoderFactory ().Encoder; }
static void Main(string [] args) { try { /* Discovery doesn't work in Mono * var endPoint = new UdpDiscoveryEndpoint (DiscoveryVersion.WSDiscoveryApril2005); * * var discoveryClient = new DiscoveryClient (endPoint); * * discoveryClient.FindProgressChanged += discoveryClient_FindProgressChanged; * discoveryClient.FindCompleted += (sender, e) => { * Console.WriteLine ("Discovery finished"); * }; * FindCriteria findCriteria = new FindCriteria (); * //findCriteria.Duration = TimeSpan.MaxValue; * findCriteria.Duration = TimeSpan.FromSeconds (10); * findCriteria.MaxResults = int.MaxValue; * discoveryClient.FindAsync (findCriteria); * * //Console.ReadKey (); */ HttpTransportBindingElement httpBinding = new HttpTransportBindingElement(); httpBinding.AuthenticationScheme = AuthenticationSchemes.Digest; var messageElement = new TextMessageEncodingBindingElement(); // FIXME: Probe for Soap12 if Soap11 fails messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None); CustomBinding binding = new CustomBinding(messageElement, httpBinding); EndpointAddress address = new EndpointAddress(@"http://192.168.1.130:8080/onvif/device_service"); OnvifServices.OnvifDeviceService.DeviceClient device = new OnvifServices.OnvifDeviceService.DeviceClient(binding, address); device.ClientCredentials.UserName.UserName = @"admin"; device.ClientCredentials.UserName.Password = @"admin"; var dateTime = device.GetSystemDateAndTime(); var services = device.GetServices(true); foreach (var service in services) { if (service.Namespace == "http://www.onvif.org/ver10/media/wsdl") { OnvifServices.OnvifMediaService.MediaClient client = new OnvifServices.OnvifMediaService.MediaClient(binding, address); client.ClientCredentials.UserName.UserName = @"admin"; client.ClientCredentials.UserName.Password = @"admin"; var profiles = client.GetProfiles(); // use the first profile (the device has at least one media profile). var targetProfileToken = profiles [0].token; // set the GetStreamUriRequest paramater var streamSetup = new OnvifServices.OnvifMediaService.StreamSetup(); streamSetup.Stream = OnvifServices.OnvifMediaService.StreamType.RTPUnicast; streamSetup.Transport = new OnvifServices.OnvifMediaService.Transport(); streamSetup.Transport.Protocol = OnvifServices.OnvifMediaService.TransportProtocol.RTSP; streamSetup.Transport.Tunnel = null; var mediaUri = client.GetStreamUri(streamSetup, targetProfileToken); } } } catch (Exception ex) { Console.Out.WriteLine($"Error: {ex.Message} \r\n{ex.StackTrace}"); } }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="incoming"></param> protected AspNetCoreBinding() { this.transport = new AspNetCoreTransportBindingElement(); this.textEncoding = new TextMessageEncodingBindingElement(); this.textEncoding.MessageVersion = MessageVersion.Soap11; this.mtomEncoding = new MtomMessageEncodingBindingElement(); this.mtomEncoding.MessageVersion = MessageVersion.Soap11; }
public override BindingElementCollection CreateBindingElements() { BindingElementCollection elements = base.CreateBindingElements(); TextMessageEncodingBindingElement textEncoding = elements.Find <TextMessageEncodingBindingElement>(); textEncoding.MessageVersion = MessageVersion.Soap12WSAddressingAugust2004; return(elements); }
public IOnvifClienBuilder <DeviceClient> SetMessageElement() { _messageElement = new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None) }; return(this); }
public void MessageEncoderIsContentTypeSupported() { var enc = new TextMessageEncodingBindingElement().CreateMessageEncoderFactory().Encoder; Assert.IsFalse(enc.IsContentTypeSupported("application/xml"), "#1"); Assert.IsFalse(enc.IsContentTypeSupported("text/xml"), "#2"); Assert.IsTrue(enc.IsContentTypeSupported("application/soap+xml"), "#3"); }
public InsecureGZipBasicHttpBinding() { httpTransport = new HttpTransportBindingElement(); textMessageEncoding = new TextMessageEncodingBindingElement { MessageVersion = MessageVersion.Soap11 }; compressionMessageEncoding = new GZipMessageEncodingBindingElement(textMessageEncoding); }
public override BindingElementCollection CreateBindingElements() { var messageEncoder = new TextMessageEncodingBindingElement(); var transportBindingElement = new DispatcherTransportBindingElement <TService, TContract>(_configureServices); var elements = new BindingElementCollection(new BindingElement[] { messageEncoder, transportBindingElement }); return(elements); }
private MessageEncodingBindingElement CreateMessageEncoding() { TextMessageEncodingBindingElement encoding = new TextMessageEncodingBindingElement(); encoding.MessageVersion = MessageVersion.Soap12; encoding.ReaderQuotas.MaxArrayLength = 1024 * 1024 * 1024; //1 GB encoding.ReaderQuotas.MaxStringContentLength = 1024 * 1024 * 1024; //1 GB return encoding; }
/// <summary> /// Chroniona, nadpisana metoda, służąca do utworzenia wiązania /// </summary> /// <returns></returns> protected override Binding PrepareBinding() { //Utworzenie instancji obiektu, będącego niestandardowym wiązaniem z usługą CustomBinding binding = new CustomBinding(); /* * Utworzenie elementu wiązania zapewniającego asymetryczne, obustronne bezpieczeństwo, czyli możliwe jest uwierzytelnienie klienta, jak i serwera za pomocą certyfikatów * Wspiera bezpieczeństwo kanału z wykorzystaniem asymetrycznego szyfrowania. Element wiązania podpisuje wiadomość z wykorzystaniem tokenu wierzytelniania wysyłającego i * szyfruje ją z wykorzystaniem tokenu odbiorcy komunikatu. Zostaje przekazana wersja zabezpieczenia wiadomości. SOAP to protokół komunikacyjny. * W tym przypadku wiadomość nie będzie szyfrowana. */ var sec = (AsymmetricSecurityBindingElement)SecurityBindingElement. CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10); //Ustawienie wersji zabezpieczenie wiadomości dla utworzonego elementu wiązania sec.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10; sec.IncludeTimestamp = false; //Stemple czasowe nie będa występowały w wiadomościach /* * Ustawienie kolejności ochrony wiadomości (podpisywanie i szyfrowanie). W tym przypadku wiadomość * będzie najpierw podpisywana, a później szyfrowana. Jako że ustawiono wcześniej, że * zabezpieczeniem umowy z punktem końcowym usługi będzie jedynie podpisywanie wiadomości, * to jaka opcja będzie tutaj ustawiona nie ma większego znaczenia, bo * wiadomość nie będzie szyfrowana. */ sec.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt; sec.AllowSerializedSigningTokenOnReply = true; //Serializowanie tokena podpisującego w komunikacie odpowiedzi jest dozwolone. sec.LocalClientSettings.DetectReplays = false; //Wykrywanie ponownego wysłania wiadomości jest wyłączone w wiadomościach otrzymywanych przez klienta z usługi. //Dodawanie utworzonego elementu wiązania do utworzonego niestandardowego wiązania binding.Elements.Add(sec); //Utworzenie elementu wiązania zawierającego informcje o kodowanie wiadomości tekstowej. Wiadomość będzie w wersji protokołu SOAP 1.1 i będzie kodowania w formacie UTF-8 var tme = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8); //Dodawanie utworzonego elementu wiązania do utworzonego niestandardowego wiązania binding.Elements.Add(tme); //Utworznie elementu wiązania zawierającego informcje o transporcie wiadomości poprzez protokuł HTTPS (Hypertext Transfer Protocol Secure) var https = new HttpsTransportBindingElement { //Wymagane jest uwierzytelnianie SSL klienta z wykorzystaniem certyfikatu RequireClientCertificate = true, MaxReceivedMessageSize = 1000000 //Maksymalna wielkość otrzymywanej wiadomości w bajtach wynosi 1000000, czyli ok. 1MB }; //Dodawanie utworzonego elementu wiązania do utworzonego niestandardowego wiązania binding.Elements.Add(https); //Zwrócenie utworzonego niestandardowego wiązania return(binding); }
private static CustomBinding CreateGetBinding(HttpTransportBindingElement httpTransport) { TextMessageEncodingBindingElement textEncoding = new TextMessageEncodingBindingElement(); textEncoding.MessageVersion = MessageVersion.None; httpTransport.Method = "GET"; httpTransport.InheritBaseAddressSettings = true; return(new CustomBinding(textEncoding, httpTransport)); }
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; }
public override BindingElementCollection CreateBindingElements() { var transport = _useHttps ? new HttpsTransportBindingElement() : new HttpTransportBindingElement(); if (_maxReceivedMessageSize.HasValue) { transport.MaxReceivedMessageSize = _maxReceivedMessageSize.Value; } var encoding = new TextMessageEncodingBindingElement(); // [OIO IDWS SOAP 1.1] requires SOAP 1.2 and WS-Adressing 1.0 encoding.MessageVersion = MessageVersion.Soap12WSAddressing10; // AlwaysToInitiator is required by the [OIO IDWS SOAP 1.1] profile. This specifies that the server certificate must be embedded in the response. var recipientTokenParameters = new X509SecurityTokenParameters( X509KeyIdentifierClauseType.Any, SecurityTokenInclusionMode.AlwaysToInitiator); var initiatorTokenParameters = new CustomizedIssuedSecurityTokenParameters( "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" ); initiatorTokenParameters.UseStrTransform = true; var asymmetric = new AsymmetricSecurityBindingElement(recipientTokenParameters, initiatorTokenParameters); // Must be true in order for client to accept embedded server certificates instead of references. This is required by the [OIO IDWS SOAP 1.1] profile. // However, the client must still specify the server certificate explicitly. // Have not figured out how the client can use the embedded server certificate and make trust to it through a CA certificate and a CN (Common Name). This way the client should not need the server certificate. asymmetric.AllowSerializedSigningTokenOnReply = true; // No need for derived keys when both parties has a certificate. Also OIO-IDWS-SOAP does not make use of derived keys. asymmetric.SetKeyDerivation(false); // Include token (encrypted assertion from NemLog-in STS) in signature asymmetric.ProtectTokens = true; // Specifies that WCF can send and receive unsecured responses to secured requests. // Concrete this means that SOAP faults are send unencrypted. [OIO IDWS SOAP 1.1] does not specify whether or not SOAP faults can be encrypted but it looks like they should not be encrypted. // If encrypted the client is not able to process the encrypted SOAP fault if client is not setup correctly. // setting EnableUnsecuredResponse to true makes normal responses unsigned and processed by the client without error. This is not what we want :) //asymmetric.EnableUnsecuredResponse = true; var elements = new BindingElementCollection(); elements.Add(asymmetric); elements.Add(encoding); elements.Add(transport); return(elements); }
private void Initialize() { _securityBindingElement = CreateSecurityBindingElement(); _textEncodingBindingElement = CreateTextEncodingBindingElement(); //_httpsTransportBindingElement = CreateHttpsTransportBindingElement(); _httpTransportBindingElement = CreateHttpTransportBindingElement(); }
protected override BindingElement CreateBindingElement() { TextMessageEncodingBindingElement textBindingElement = new TextMessageEncodingBindingElement(); if (null != this.TextEncoding) { this.TextEncoding.ApplyConfiguration(textBindingElement); } return new CompressionTextMessageEncodingBindingElement(textBindingElement, this.Algorithm, this.MinMessageSize); }
void IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context) { // The MessageEncodingBindingElement is responsible for ensuring that the WSDL has the correct // SOAP version. We can delegate to the WCF implementation of TextMessageEncodingBindingElement for this. TextMessageEncodingBindingElement mebe = new TextMessageEncodingBindingElement(); mebe.MessageVersion = this.msgVersion; ((IWsdlExportExtension)mebe).ExportEndpoint(exporter, context); }
private void Initialize() { HttpTransport = new HttpTransportBindingElement(); HttpsTransport = new HttpsTransportBindingElement(); _session = new ReliableSessionBindingElement(true); _textEncoding = new TextMessageEncodingBindingElement(); _textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10; _reliableSession = new OptionalReliableSession(_session); }
private MessageEncodingBindingElement CreateMessageEncoding() { TextMessageEncodingBindingElement encoding = new TextMessageEncodingBindingElement(); encoding.MessageVersion = MessageVersion.Soap12; encoding.ReaderQuotas.MaxArrayLength = 1024 * 1024 * 1024; //1 GB encoding.ReaderQuotas.MaxStringContentLength = 1024 * 1024 * 1024; //1 GB return(encoding); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseSoapEndpoint <TestService>("/Service.svc", new BasicHttpBinding(), SoapSerializer.DataContractSerializer); var transportBinding = new HttpTransportBindingElement(); var textEncodingBinding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, System.Text.Encoding.UTF8); app.UseSoapEndpoint <TestService>("/ServiceSoap12.svc", new CustomBinding(transportBinding, textEncodingBinding), SoapSerializer.DataContractSerializer); app.UseMvc(); }
internal HttpBindingBase() { _httpTransport = new HttpTransportBindingElement(); _httpsTransport = new HttpsTransportBindingElement(); TextMessageEncodingBindingElement = new TextMessageEncodingBindingElement { MessageVersion = MessageVersion.Soap11 }; }
protected void AddTextEncodingBindingElement(BindingElementCollection bindingElements) { TextMessageEncodingBindingElement item = new TextMessageEncodingBindingElement { WriteEncoding = Encoding.UTF8, MessageVersion = MessagingVersionHelper.MessageVersion(this.protocolVersion) }; bindingElements.Add(item); }
public static FNCEWS40PortTypeClient ConfigureBinding(String user, String domain, String password, String uri) { BindingElementCollection bec = new BindingElementCollection(); // Everything gets treated as if it is username credentials until // right at the point of serialization. TransportSecurityBindingElement sbe = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); sbe.IncludeTimestamp = false; bec.Add(sbe); if (uri.IndexOf("SOAP") != -1) { // using the SOAP endpoint TextMessageEncodingBindingElement tme = new TextMessageEncodingBindingElement(); tme.MessageVersion = MessageVersion.Soap11; tme.ReaderQuotas.MaxDepth = 1024; tme.ReaderQuotas.MaxStringContentLength = 1024 * 1024; bec.Add(tme); } else { MtomMessageEncodingBindingElement mme = new MtomMessageEncodingBindingElement(); mme.MessageVersion = MessageVersion.Soap12; mme.ReaderQuotas.MaxDepth = 1024; mme.ReaderQuotas.MaxStringContentLength = 1024 * 1024; mme.MaxBufferSize = 2147483647; bec.Add(mme); } HttpsTransportBindingElement tbe = new HttpsTransportBindingElement(); tbe.MaxReceivedMessageSize = 2147483647; tbe.MaxBufferSize = 2147483647; bec.Add(tbe); CustomBinding binding = new CustomBinding(bec); binding.ReceiveTimeout = new TimeSpan(TimeSpan.TicksPerDay); // 100 nanonsecond units, make it 1 day binding.SendTimeout = binding.ReceiveTimeout; EndpointAddress endpoint = new EndpointAddress(uri); port = new FNCEWS40PortTypeClient(binding, endpoint); port.ClientCredentials.UserName.UserName = user; port.ClientCredentials.UserName.Password = password; // set up the Localization header, minus the locale. We assume // the timezone cannot change between calls, but that the locale // may. localization = new Localization(); localization.Timezone = GetTimezone(); return(port); }
public void BuildChannelFactoryFail1 () { MessageEncodingBindingElement be = new TextMessageEncodingBindingElement (); BindingContext ctx = new BindingContext ( // no transport -> fail new CustomBinding (), new BindingParameterCollection ()); be.BuildChannelFactory<IRequestChannel> (ctx); }
protected override BindingElement CreateBindingElement() { var textBindingElement = new TextMessageEncodingBindingElement(); if (this.TextEncoding != null) { this.TextEncoding.ApplyConfiguration(textBindingElement); } return(new CustomMessageEncodingBindingElement(textBindingElement, this.Greeting)); }
/// <summary> /// Initializes a new instance of the WOPIMessageEncoder class with the specified message encoder factory. /// </summary> /// <param name="factory">Specify the message encoder factory.</param> public WOPIMessageEncoder(WOPIMessageEncoderFactory factory) { TextMessageEncodingBindingElement element = new TextMessageEncodingBindingElement(); element.MessageVersion = factory.MessageVersion; element.WriteEncoding = Encoding.GetEncoding(factory.CharSet); this.innerEncoder = element.CreateMessageEncoderFactory().Encoder; this.factory = factory; this.contentType = string.Format("{0}; charset={1}", "text/xml", this.factory.CharSet); }
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; }
/// <summary> /// Create TextMessageEncodingBindingElement of specified Soap version with lengths set to int.MaxValue /// </summary> /// <param name="version">Soap Messaging version</param> /// <returns>Instance of TextMessageEncodingBindingElement</returns> private static TextMessageEncodingBindingElement _createTextMessageEncodingBinding(MessageVersion version) { TextMessageEncodingBindingElement rRet = new TextMessageEncodingBindingElement(version, Encoding.UTF8); rRet.ReaderQuotas.MaxArrayLength = int.MaxValue; rRet.ReaderQuotas.MaxStringContentLength = int.MaxValue; rRet.ReaderQuotas.MaxBytesPerRead = int.MaxValue; rRet.ReaderQuotas.MaxDepth = int.MaxValue; rRet.ReaderQuotas.MaxNameTableCharCount = int.MaxValue; return rRet; }
internal HttpBindingBase() { this.httpTransport = new HttpTransportBindingElement(); this.httpsTransport = new HttpsTransportBindingElement(); this.textEncoding = new TextMessageEncodingBindingElement(); this.textEncoding.MessageVersion = MessageVersion.Soap11; this.mtomEncoding = new MtomMessageEncodingBindingElement(); this.mtomEncoding.MessageVersion = MessageVersion.Soap11; this.httpsTransport.WebSocketSettings = this.httpTransport.WebSocketSettings; }
public void BuildChannelFactory1 () { MessageEncodingBindingElement be = new TextMessageEncodingBindingElement (); BindingContext ctx = new BindingContext ( new CustomBinding ( new HttpTransportBindingElement ()), new BindingParameterCollection ()); // hmm, it returns HttpChannelFactory, not sure // if TextMessageEncodingBindingElement is considered. be.BuildChannelFactory<IRequestChannel> (ctx); }
public static void IRequestChannel_Http_CustomBinding() { IChannelFactory<IRequestChannel> factory = null; IRequestChannel channel = null; Message replyMessage = null; try { // *** SETUP *** \\ 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. factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection()); factory.Open(); // Create the channel. 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)); // *** EXECUTE *** \\ // Send the Message and receive the Response. replyMessage = channel.Request(requestMessage); // *** VALIDATE *** \\ string replyMessageAction = replyMessage.Headers.Action; Assert.Equal(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."; Assert.Equal(expectedResponse, actualResponse); // *** CLEANUP *** \\ replyMessage.Close(); channel.Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects(channel, factory); } }
// Get the MessageVersion from a Custom binding public static void GetMessageVersion() { MessageVersion version = null; BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new HttpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); version = binding.MessageVersion; string expected = "Soap12 (http://www.w3.org/2003/05/soap-envelope) Addressing10 (http://www.w3.org/2005/08/addressing)"; string actual = version.ToString(); Assert.Equal<string>(expected, actual); }
private void Initialize() { this.httpTransport = new HttpTransportBindingElement(); this.httpsTransport = new HttpsTransportBindingElement(); this.messageEncoding = WSMessageEncoding.Text; this.txFlow = GetDefaultTransactionFlowBindingElement(); this.session = new System.ServiceModel.Channels.ReliableSessionBindingElement(true); this.textEncoding = new TextMessageEncodingBindingElement(); this.textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10; this.mtomEncoding = new MtomMessageEncodingBindingElement(); this.mtomEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10; this.reliableSession = new OptionalReliableSession(this.session); }
public static void Run(string xmlFilename, string xsdFilename) { var http = new BasicHttpBinding (); http.OpenTimeout = TimeSpan.FromHours (3); http.MaxBufferSize = 8192; http.HostNameComparisonMode = HostNameComparisonMode.WeakWildcard; http.AllowCookies = true; http.Security.Mode = BasicHttpSecurityMode.Transport; http.TransferMode = TransferMode.StreamedRequest; #if !MOBILE || MOBILE_BAULIG var https = new BasicHttpsBinding (); https.MaxBufferSize = 32768; #endif #if !MOBILE_FIXME var netTcp = new NetTcpBinding (); #endif var custom = new CustomBinding (); custom.Name = "myCustomBinding"; var text = new TextMessageEncodingBindingElement (); text.MessageVersion = MessageVersion.Soap12WSAddressingAugust2004; custom.Elements.Add (text); custom.Elements.Add (new HttpTransportBindingElement ()); var root = new Configuration (); root.AddBinding (http); #if !MOBILE || MOBILE_BAULIG root.AddBinding (https); #endif #if !MOBILE_FIXME root.AddBinding (netTcp); #endif root.AddBinding (custom); var contract = new ContractDescription ("MyContract"); var endpointUri = "custom://localhost:8888/MyService"; var endpointAddress = new EndpointAddress (endpointUri); var endpoint = new ServiceEndpoint (contract, custom, endpointAddress); root.AddEndpoint (endpoint); Generator.Write (xmlFilename, xsdFilename, root); Utils.Dump (xsdFilename); Utils.Dump (xmlFilename); Utils.ValidateSchema (xmlFilename, xsdFilename); }
public void init() { string authorizationServerEndpoint = ConfigurationManager.AppSettings["authorizationServerEndpoint"]; clientId = ConfigurationManager.AppSettings["clientId"]; clientSecret = ConfigurationManager.AppSettings["clientSecret"]; var messageElement = new TextMessageEncodingBindingElement(); var transportElement = new HttpTransportBindingElement(); messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap11, AddressingVersion.None); CustomBinding binding = new CustomBinding(messageElement, transportElement); EndpointAddress endpoint = new EndpointAddress(new Uri(authorizationServerEndpoint)); client = new OAuth2Protocol.AccessTokenRequestor.OAuthPortTypeClient(binding, endpoint); }
private UdpBinding(UdpTransportBindingElement transport, TextMessageEncodingBindingElement encoding) : this() { this.DuplicateMessageHistoryLength = transport.DuplicateMessageHistoryLength; this.MaxBufferPoolSize = transport.MaxBufferPoolSize; this.MaxPendingMessagesTotalSize = transport.MaxPendingMessagesTotalSize; this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize; this.MaxRetransmitCount = Math.Max(transport.RetransmissionSettings.MaxUnicastRetransmitCount, transport.RetransmissionSettings.MaxMulticastRetransmitCount); this.MulticastInterfaceId = transport.MulticastInterfaceId; this.TimeToLive = transport.TimeToLive; this.ReaderQuotas = encoding.ReaderQuotas; this.TextEncoding = encoding.WriteEncoding; }
static int SizeOfTextMessage(Message message) { // Create a text encoder MessageEncodingBindingElement element = new TextMessageEncodingBindingElement(); MessageEncoderFactory factory = element.CreateMessageEncoderFactory(); MessageEncoder encoder = factory.Encoder; // Write the message and return its length MemoryStream stream = new MemoryStream(); encoder.WriteMessage(message, stream); int size = (int)stream.Length; message.Close(); stream.Close(); return size; }
public CertificateOverTransportBinding() { //add security var securityElement = SecurityBindingElement.CreateCertificateOverTransportBindingElement(); Elements.Add(securityElement); // Message Encoding var textEncoding = new TextMessageEncodingBindingElement(); textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10; Elements.Add(textEncoding); // Transport Elements.Add(new HttpsTransportBindingElement()); }
public static void Main() { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(ITest), GetServerBinding(), ""); host.Open(); Console.WriteLine("Host opened"); foreach (bool useMtom in new bool[] { false, true }) { MessageEncodingBindingElement clientEncoding; if (useMtom) { clientEncoding = new MtomMessageEncodingBindingElement(); } else { clientEncoding = new TextMessageEncodingBindingElement(); } CustomBinding binding = new CustomBinding(clientEncoding, new HttpTransportBindingElement()); ChannelFactory<ITest> factory = new ChannelFactory<ITest>(binding, new EndpointAddress(baseAddress)); ITest proxy = factory.CreateChannel(); byte[] fileContents = new byte[10000]; for (int i = 0; i < fileContents.Length; i++) { fileContents[i] = (byte)('a' + (i % 26)); } using (new OperationContextScope((IContextChannel)proxy)) { proxy.Echo(new MyDC { Name = "FileName.bin", Contents = fileContents }); HttpResponseMessageProperty responseProperty; responseProperty = (HttpResponseMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name]; Console.WriteLine("In client, response content-type: {0}", responseProperty.Headers[HttpResponseHeader.ContentType]); } ((IClientChannel)proxy).Close(); factory.Close(); } Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); }
/// <summary> /// Initializes the binding. /// </summary> /// <param name="namespaceUris">The namespace uris.</param> /// <param name="factory">The factory.</param> /// <param name="configuration">The configuration.</param> /// <param name="description">The description.</param> public UaSoapXmlBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration, EndpointDescription description) : base(namespaceUris, factory, configuration) { if (description != null && description.SecurityMode != MessageSecurityMode.None) { TransportSecurityBindingElement bootstrap = SecurityBindingElement.CreateUserNameOverTransportBindingElement(); bootstrap.IncludeTimestamp = true; bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; bootstrap.SecurityHeaderLayout = SecurityHeaderLayout.Strict; m_security = SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap); m_security.IncludeTimestamp = true; m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; m_security.SecurityHeaderLayout = SecurityHeaderLayout.Strict; } m_encoding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8); // WCF does not distinguish between arrays and byte string. int maxArrayLength = configuration.MaxArrayLength; if (configuration.MaxArrayLength < configuration.MaxByteStringLength) { maxArrayLength = configuration.MaxByteStringLength; } m_encoding.ReaderQuotas.MaxArrayLength = maxArrayLength; m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength; m_encoding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue; m_encoding.ReaderQuotas.MaxDepth = Int32.MaxValue; m_encoding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue; m_transport = new HttpTransportBindingElement(); m_transport.AllowCookies = false; m_transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous; m_transport.ManualAddressing = false; m_transport.MaxBufferSize = configuration.MaxMessageSize; m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize; m_transport.TransferMode = TransferMode.Buffered; }