How to use c# code to add bindingConfiguration attribute (WCF) - wcf

I have an endpoint in the app.config:
<endpoint address=""
binding="netTcpBinding"
bindingConfiguration="financeBinding"
name="RoutingServiceEndpoint"
contract="System.ServiceModel.Routing.IRequestReplyRouter" />
The bindingConfiguration in app.config
<bindings>
<netTcpBinding>
<binding name="financeBinding" closeTimeout="00:10:10" openTimeout="00:10:10" sendTimeout="00:10:10" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647">
<!--transactionFlow="true"-->
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
Question is: how could i config this in the code? I need read the config for the database and bind it.
:)

With this you can configure your settings in the code:
using System.ServiceModel;
EndpointAddress endpoint = new EndpointAddress("http://yourAdress.svc");
NetTcpBinding binding = new NetTcpBinding();
binding.Name = "financeBinding";
binding.MaxBufferPoolSize = 2147483647;
binding.ReaderQuotas.MaxDepth = 2147483647;
binding.ReaderQuotas.MaxStringContentLength = 2147483647;
binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
binding.OpenTimeout = new TimeSpan(0, 10, 10);
binding.CloseTimeout = new TimeSpan(0, 10, 10);
binding.SendTimeout = new TimeSpan(0, 10, 10);
binding.Security.Mode = SecurityMode.None;
yourClient client = new yourClient(binding, endpoint);

Related

How to programatically create a Custom Binding with TransportWithMessageCredential?

I need to programatically create a wsHttpBinding (Custom Binding) and for this I need the following configuration:
<binding name="ws_IMembershipService_TransportWithMessageCredential_Username" messageEncoding="Text" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="true" maxBufferPoolSize="524288" maxReceivedMessageSize="10000000">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" establishSecurityContext="false" />
</security>
</binding>
What is the equivalent to this config in C#?
Should be something like this:
EDIT: Still not sure if this will get you what you need, but maybe a good starting point. If not let me know I will delete.
CustomBinding cb = new CustomBinding()
{
SendTimeout = System.TimeSpan.FromMinutes(1),
ReceiveTimeout = System.TimeSpan.FromMinutes(1),
CloseTimeout = System.TimeSpan.FromMinutes(1),
OpenTimeout = System.TimeSpan.FromMinutes(1),
};
HttpsTransportBindingElement a = new HttpsTransportBindingElement();
a.MaxReceivedMessageSize = 10000000;
a.MaxBufferSize = 524288;
a.BypassProxyOnLocal = true;
a.AuthenticationScheme = AuthenticationSchemes.None;
SymmetricSecurityBindingElement b = SecurityBindingElement.CreateSspiNegotiationBindingElement(true);
TextMessageEncodingBindingElement c = new TextMessageEncodingBindingElement(MessageVersion.Soap11, System.Text.Encoding.UTF8);
SecurityBindingElement d = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
d.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
c.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxDepth = 32, MaxStringContentLength = 8192, MaxArrayLength = 16384, MaxBytesPerRead = 4096, MaxNameTableCharCount = 16384 };
cb.CreateBindingElements();
cb.Elements.Add(a);
cb.Elements.Add(b);
cb.Elements.Add(c);
cb.Elements.Add(d);

Transport level security in an intranet Silverlight 5 application

I am implementing transport level security in an intranet Silverlight 5 application.
Binding used is custom netTcpBinding and on server end I have enabled security with below settings and PrincipalPermission.
<customBinding>
<binding closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="02:00:00" sendTimeout="00:05:00">
<binaryMessageEncoding maxSessionSize="1000000">
<readerQuotas maxDepth="64" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="16384" maxNameTableCharCount="16384" />
</binaryMessageEncoding>
<windowsStreamSecurity protectionLevel="EncryptAndSign"/>
<tcpTransport portSharingEnabled="false" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
When my client is a normal c# console app and proxy created using channel fatory everything works fine.
var tcpBinding = new CustomBinding();
tcpBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
var windowsStreamSecurityBindingElement=new WindowsStreamSecurityBindingElement();
windowsStreamSecurityBindingElement.ProtectionLevel= System.Net.Security.ProtectionLevel.EncryptAndSign;
tcpBinding.Elements.Add(windowsStreamSecurityBindingElement);
tcpBinding.Elements.Add(new TcpTransportBindingElement { MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue });
tcpBinding.ReceiveTimeout = new TimeSpan(6, 0, 0);
tcpBinding.SendTimeout = new TimeSpan(0, 30, 0);
tcpBinding.ReceiveTimeout = TimeSpan.FromDays(1);
var proxy = new ChannelFactoryServiceWrapper<IHello>(#"net.tcp://XYZ.globaltest.ABC.com:5580/Hello/tcp", tcpBinding).Channel;
var ping = proxy.Ping();
On client(Silverlight 5) I am using same above piece of code but it’s giving compile time error since WindowsStreamSecurityBindingElement is not available in Silverlight 5.
Please tell me any alternative for this.

System.InsufficientMemoryException: Failed to allocate a managed memory buffer of 536870912 bytes. The amount of available memory may be low

Below mentioned in Web.Config on Server Side.
<bindings>
<wsHttpBinding>
<binding name="NewBinding0" closeTimeout="00:50:00" openTimeout="00:50:00" sendTimeout="00:50:00" receiveTimeout="00:50:00" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<reliableSession enabled="true" />
<security mode="None">
<transport clientCredentialType="None" />
<message clientCredentialType="Windows" negotiateServiceCredential="true" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
Also at client side I mention below settings.
WSHttpBinding binding = new WSHttpBinding();
//binding.ReaderQuotas.MaxArrayLength = 10485760;
//binding.MaxReceivedMessageSize = 10485760;
binding.Security.Mode = SecurityMode.None;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
binding.Security.Message.EstablishSecurityContext = false;
//binding.Security.Message.NegotiateServiceCredential = true;
binding.ReliableSession.Enabled = true;
binding.ReaderQuotas.MaxArrayLength = 2147483647;
binding.ReaderQuotas.MaxDepth = 2147483647;
binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
//binding.MaxReceivedMessageSize = 20000000;2147483647
binding.MaxReceivedMessageSize = 2147483647;
//binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = 2147483647;
//binding.MaxBufferPoolSize = 20000000;
binding.MaxBufferPoolSize = 2147483647;
//binding.MaxBufferPoolSize = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = 2147483647;
binding.ReaderQuotas.MaxDepth = 2147483647;
binding.SendTimeout = TimeSpan.FromMinutes(50);
binding.CloseTimeout = TimeSpan.FromMinutes(50);
binding.OpenTimeout = TimeSpan.FromMinutes(50);
binding.ReceiveTimeout = TimeSpan.FromMinutes(50);
//EndpointIdentity.CreateUpnIdentity("user#domain");
ChannelFactory<IDBSyncContract> factory = new ChannelFactory<IDBSyncContract>(binding, new EndpointAddress(endPointURL));
dbProxy = factory.CreateChannel();
this.dbProxy = dbProxy as IDBSyncContract;
I am getting above mentioned error.
Is there any concerns regarding wsHttpBindings.
Your problem is that the service is consuming all available memory on the host machine. I'd recommend that you remove all your config changes and return the config to the WCF default values. These default values were chosen by Microsoft for best performance in the average WCF service and you should only change them when you have a demonstrated need to do so.
The only exceptions I would recommend to the default values are the maxReceivedMessageSize and the maxBufferSize values. I'd start those at 262,144 bytes. If you get specific exceptions with any of these settings then changes only the affected setting.
If you're still having problems after upping a setting to max integer then consider changing your service design to get a successful call within the normal config setting. Staying as close as possible to the WCF default values will give your service the best overall performance.

Maximum request length exceeded in WCF

I am currently using Wcf application and getting above mentiooned error in Trace Log.
Below is the Web.Config for Wcf Service.
<bindings>
<wsHttpBinding>
<binding name="NewBinding0" closeTimeout="00:50:00" openTimeout="00:50:00" sendTimeout="00:50:00" receiveTimeout="00:50:00" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<reliableSession enabled="true" />
<security mode="None">
<transport clientCredentialType="None" />
<message clientCredentialType="Windows" negotiateServiceCredential="true" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<diagnostics wmiProviderEnabled="true">
<messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
</diagnostics>
<services>
<service behaviorConfiguration="DBSyncWcfService.Service1Behavior" name="DBSyncWcfService.DBSyncService">
<endpoint binding="wsHttpBinding" bindingConfiguration="NewBinding0" name="ABC" contract="DBSyncWcfService.IDBSyncContract" address="http://192.168.5.170:9999/" />
<host>
<baseAddresses>
Below is the Client side Configuration.
WSHttpBinding binding = new WSHttpBinding();
//binding.ReaderQuotas.MaxArrayLength = 10485760;
//binding.MaxReceivedMessageSize = 10485760;
binding.Security.Mode = SecurityMode.None;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
binding.Security.Message.EstablishSecurityContext = false;
//binding.Security.Message.NegotiateServiceCredential = true;
binding.ReliableSession.Enabled = true;
binding.ReaderQuotas.MaxArrayLength = 2147483647;
binding.ReaderQuotas.MaxDepth = 2147483647;
binding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
//binding.MaxReceivedMessageSize = 20000000;2147483647
binding.MaxReceivedMessageSize = 2147483647;
//binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = 2147483647;
//binding.MaxBufferPoolSize = 20000000;
binding.MaxBufferPoolSize = 2147483647;
//binding.MaxBufferPoolSize = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = 2147483647;
binding.ReaderQuotas.MaxDepth = 2147483647;
binding.SendTimeout = TimeSpan.FromMinutes(50);
binding.CloseTimeout = TimeSpan.FromMinutes(50);
binding.OpenTimeout = TimeSpan.FromMinutes(50);
binding.ReceiveTimeout = TimeSpan.FromMinutes(50);
Change the following setting in web.config
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxxx" />
</system.web>
</configuration>
xxxx is the value in KB you want to set it to.
You might have to set the readerQuotas for the binding as shown below:
WSHttpBinding binding1 = new WSHttpBinding();
binding1.MaxBufferPoolSize = 2147483647;
binding1.MaxReceivedMessageSize = 2147483647;
var myReaderQuotas1 = new XmlDictionaryReaderQuotas();
myReaderQuotas1.MaxStringContentLength = 2147483647;
myReaderQuotas1.MaxDepth = 2147483647;
myReaderQuotas1.MaxArrayLength = 2147483647;
myReaderQuotas1.MaxBytesPerRead = 2147483647;
myReaderQuotas1.MaxNameTableCharCount = 2147483647;
binding1.GetType().GetProperty("ReaderQuotas").SetValue(binding1, myReaderQuotas1, null);
The reason is that setting quotas on a binding that has already been created has no effect.
Also you would need to consider increasing your "MaxItemsInObjectGraph" value of the DataContractSerializer on both client and server to a large value.

The maximum message size quota for incoming messages (65536) has been exceeded

I get this exception while creating scope for few tables all those tables are huge in design
<bindings>
<wsHttpBinding>
<binding name="wsHttpBinding_ISyncServices" closeTimeout="00:10:00"
openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows"
proxyCredentialType="None" realm="">
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
<message clientCredentialType="Windows"
negotiateServiceCredential="true" algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
</bindings>
I have made MaxReceivedMessageSize to 2147483647
but still it is giving me below exception at this line
client.GetTableDescription(scopeName, syncTable)
The maximum message size quota for incoming messages (65536) has been exceeded.
To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.
As per this question's answer
You will want something like this:
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="32"
maxArrayLength="200000000"
maxStringContentLength="200000000"/>
</binding>
</basicHttpBinding> </bindings>
Please also read comments to the accepted answer there, those contain valuable input.
If you are using CustomBinding then you would rather need to make changes in httptransport element.
Set it as
<customBinding>
<binding ...>
...
<httpsTransport maxReceivedMessageSize="2147483647"/>
</binding>
</customBinding>
Updating the config didn't work for me, but I was able to edit the binding programmatically:
private YourAPIClient GetClient()
{
Uri baseAddress = new Uri(APIURL);
var binding = new BasicHttpBinding();
binding.MaxReceivedMessageSize = 20000000;
binding.MaxBufferSize = 20000000;
binding.MaxBufferPoolSize = 20000000;
binding.AllowCookies = true;
var readerQuotas = new XmlDictionaryReaderQuotas();
readerQuotas.MaxArrayLength = 20000000;
readerQuotas.MaxStringContentLength = 20000000;
readerQuotas.MaxDepth = 32;
binding.ReaderQuotas = readerQuotas;
if (baseAddress.Scheme.ToLower() == "https")
binding.Security.Mode = BasicHttpSecurityMode.Transport;
var client = new YourAPIClient(binding, new EndpointAddress(baseAddress));
return client;
}
You need to make the changes in the binding configuration (in the app.config file) on the SERVER and the CLIENT, or it will not take effect.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="2147483647 " max...=... />
</basicHttpBinding>
</bindings>
</system.serviceModel>
You also need to increase maxBufferSize. Also note that you might need to increase the readerQuotas.
This worked for me:
Dim binding As New WebHttpBinding(WebHttpSecurityMode.Transport)
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None
binding.MaxBufferSize = Integer.MaxValue
binding.MaxReceivedMessageSize = Integer.MaxValue
binding.MaxBufferPoolSize = Integer.MaxValue
For me, the settings in web.config / app.config were ignored. I ended up creating my binding manually, which solved the issue for me:
var httpBinding = new BasicHttpBinding()
{
MaxBufferPoolSize = Int32.MaxValue,
MaxBufferSize = Int32.MaxValue,
MaxReceivedMessageSize = Int32.MaxValue,
ReaderQuotas = new XmlDictionaryReaderQuotas()
{
MaxArrayLength = 200000000,
MaxDepth = 32,
MaxStringContentLength = 200000000
}
};
My solution was to use the "-OutBuffer 2147483647" parameter in my query, which is part of the Common Parameters.
PS C:> Get-Help about_CommonParameters -Full