How to programmatically set WCF client maxBufferSize parameters? - wcf-binding

I am setting wcf client parameters programmatically like below:
try
{
ServiceReference1.MyDbServiceClient webService =
new ServiceReference1.MyDbServiceClient(new System.ServiceModel.BasicHttpBinding(),
new System.ServiceModel.EndpointAddress((string)((App)Application.Current).Resources["wcfMyDBServiceEndPoint"]));
webService.GetSeriesImagesCompleted += new EventHandler<ServiceReference1.GetSeriesImagesCompletedEventArgs>(webService_GetSeriesImagesCompleted);
webService.GetSeriesImagesAsync(index);
}
It works just fine for the default maxBufferSize. However when a client exceeds the default size, an exception is throughn: "the maximum message size quota for incoming messages (65536) has been exceeded."
How to set this parameter in code?
Thanks.

BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = new TimeSpan(00, 05, 00);
binding.OpenTimeout = new TimeSpan(00, 05, 00);
binding.ReceiveTimeout = new TimeSpan(00, 05, 00);
binding.SendTimeout = new TimeSpan(00, 05, 00);
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, XmlDictionaryReaderQuotas.Max, null);
Create binding based on your requirement.

Related

.Net Core 2.0 timeout for WCF web service in c#

I am doing a .NET Core 2.0 App. I am calling a webService. I added a Reference to a local Service and call it from my Application.
ServiceReference1.QueryCalendarClient servicio = null;
ServiceReference1.ListCalendarDayTypeRequest request = new ServiceReference1.ListCalendarDayTypeRequest();
ServiceReference1.ListCalendarDayTypeResponse response = null;
var binding = new BasicHttpBinding();
binding.ReceiveTimeout = new TimeSpan(0, 25, 0);
binding.SendTimeout = new TimeSpan(0, 25, 0);
binding.MaxBufferSize = 2147483647;
binding.MaxReceivedMessageSize = 2147483647;
binding.Security = new BasicHttpSecurity
{
Mode = BasicHttpSecurityMode.TransportCredentialOnly,
Transport = new HttpTransportSecurity()
{
ClientCredentialType = HttpClientCredentialType.Basic
}
};
servicio = new ServiceReference1.QueryCalendarClient(binding, new EndpointAddress("http://WebBasica?wsdl"));
servicio.ClientCredentials.UserName.Password = "123456789";
servicio.ClientCredentials.UserName.UserName = "user";
response = new ServiceReference1.ListCalendarDayTypeResponse();
response = servicio.Method(request.CalendarInquireRequest_MT).Result;
I have an time Out Exception.
The request channel timed out while waiting for a reply after
00:24:58.3211575. Increase the timeout value passed to the call to
Request or increase the SendTimeout value on the Binding. The time
allotted to this operation may have been a portion of a longer
timeout.
Any timeOut I set, gave me a TimeOut error...
Where can I set the time out?
What I am missing?
Thank

c# console application returning no results

This code runs fine in my windows form application using .net framework 4.6.2 but when I go to make it a console application so it can be ran from the task scheduler I get no results. I think I am losing something in translation.
RestClient restClient = new RestClient("https://api.vault.com");
string refreshToken = #"abc";
string encodedClientIdSecret = Base64Encode("AP-123");
string responseStr = "";
string url = "/v1/OAuth";
dynamic jsonObj = "";
RestRequest request = new RestRequest(url, Method.POST);
request.AddHeader("Authorization", encodedClientIdSecret);
request.AddParameter("grant_type", "refresh_token");
request.AddParameter("refresh_token", refreshToken);
IRestResponse response;
restClient.Execute(request);
response = restClient.Execute(request);
Console.WriteLine(response.Content + " || " + encodedClientIdSecret);
Console.ReadKey();
jsonObj = JsonConvert.DeserializeObject(response.Content);
responseStr = jsonObj.access_token;
return responseStr;
It basically tells me the value cannot be null, and when I look at response.Content I get nothing and the status code comes back as "0". Any thoughts?
Just added:
//Required For SSL/TLS Error Start
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//Required For SSL/TLS Error End
and I got my results. Hope this helps someone else!

C# "The request was aborted: Could not create SSL/TLS secure channel." - happening occasionally

This is a request to GoCardless test API from a Dynamics CRM plugin. I receive "The request was aborted: Could not create SSL/TLS secure channel." error. It only happens on the first request after some time without sending one. If I send it again, it will be OK. I would appreciate a lot your help.
Here is my code:
//I have tried all the following lines in comment without success
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
//ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//ServicePointManager.Expect100Continue = true;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
// Create a new WebClient instance.
string baseURL = "https://api-sandbox.gocardless.com/";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", "Bearer " + t);
client.Headers.Add("GoCardless-Version", "2015-07-06");
client.Headers.Add("Accept", "application/json");
Customers model = new Customers();
customer.country_code = "GB";
model.customers = customer;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customers));
ser.WriteObject(stream1, model);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
// Apply ASCII Encoding to obtain the string as a byte array.
byte[] byteArray = Encoding.ASCII.GetBytes(sr.ReadToEnd());
ReturnedCustomers result = new ReturnedCustomers();
//Upload the input string using the HTTP 1.0 POST method.
try
{
byte[] responseArray = client.UploadData(baseURL + "customers", "POST", byteArray);
string responseText = Encoding.ASCII.GetString(responseArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ReturnedCustomers));
using (Stream s = GenerateStreamFromString(responseText))
{
result = (ReturnedCustomers)serializer.ReadObject(s);
}
}
catch (WebException exception)
{
}
From the Microsoft documentation (https://msdn.microsoft.com/en-us/library/gg334752.aspx) are the following limitations:
Only the HTTP and HTTPS protocols are allowed.
Access to localhost (loopback) is not permitted.
IP addresses cannot be used. You must use a named web address that requires DNS name resolution.
Anonymous authentication is supported and recommended.
5.There is no provision for prompting the logged on user for credentials or saving those credentials.
The error may be due to seguneti things:
The certificate is invalid
The certification authority is not public
Could you check what is the value of ServicePointManager.Expect100Continue and ServicePointManager.SecurityProtocol attributes in your environment?

setting maxBufferPoolSize of basicHttpBinding programmatically

I am trying to set the maxBufferPoolSize along with MaxReceivedMessageSize and MaxBufferSize. However, when I try to set it, i got the message "'maxBufferPoolSize' is not a member of 'System.ServiceModel.BasicHttpBinding'." I am using VS 2010. From MS Documentation, MaxBufferpoolSize is a member ( http://msdn.microsoft.com/en-us/library/system.servicemodel.basichttpbinding.maxbufferpoolsize). Why am I getting this error??? Please help. Thank you.
Dim basicHttpBinding As BasicHttpBinding = New BasicHttpBinding()
Dim endpointAddress As EndpointAddress = New EndpointAddress("/test.svc")
basicHttpBinding.MaxReceivedMessageSize = "2147483647"
basicHttpBinding.MaxBufferSize = "2147483647"
**basicHttpBinding.maxBufferPoolSize = "2147483647"**
basicHttpBinding.OpenTimeout = New TimeSpan(0, 20, 0)
basicHttpBinding.CloseTimeout = New TimeSpan(0, 10, 0)
basicHttpBinding.ReceiveTimeout = New TimeSpan(0, 10, 0)
basicHttpBinding.SendTimeout = New TimeSpan(0, 10, 0)
Dim Svc As Svc= New ChannelFactory(Of Svc)(basicHttpBinding, endpointAddress).CreateChannel
'... do the binding
Per the comments, you're using Silverlight, so that property doesn't exist in that framework. There's no buffer pooling in Silverlight, which is why it doesn't compile.

WCF Client Performance

I used WCF to call a Java based web service and constantly get 1.4 second or 1.5 second response time. I used exactly same SOAP request in SoapUI to call the same web service and constantly get 0.9 second to 1 second response time.
Both requests are initiated from my local computer, both requets hit same target.
It is very hard for me to believe it will take 0.5 second to serialize and deserialize, but other than this what else can impact the performance?
Update 1 - included sample code
Stopwatch sw = new Stopwatch();
//Trust all certificates, non-production uses self-signed certificate
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
MyServiceClient.MyService.Spml2ServicePortTypeClient client = new MyServiceClient.MyService.Spml2ServicePortTypeClient();
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
for (int i = 0; i < 5; i++)
{
MyServiceClient.MyService.SuggestUserIDRequestType webRequest = new MyServiceClient.MyService.SuggestUserIDRequestType();
webRequest.requestID = "MyId";
webRequest.givenName = "Hardy";
webRequest.sn = "Wang";
webRequest.uid = "some value";
sw.Start();
MyServiceClient.MyService.SuggestUserIDResponseType response = client.suggestUserID(webRequest);
sw.Stop();
Console.WriteLine("Elapsed time {0} ms.", sw.ElapsedMilliseconds);
sw.Reset();
}