Random System.Net.Mail.SmtpFailedRecipientsException exception - relay account office365 - smtp

We have an application that runs on a Windows Server 2008 machine. It sends emails out using an office365 smtp relay account. However, all the emails are not sent successfully. We randomly get these two exceptions on emails being sent out on the smtp.Send call:
System.Net.Mail.SmtpFailedRecipientsException: Unable to send to all recipients. ---> System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.64 TenantAttribution; Relay Access Denied
System.Net.Mail.SmtpFailedRecipientException: Insufficient system storage. The server response was: 4.5.3 Too many recipients
Thus far, we haven't been able to figure out why this is happening. Any ideas are appreciated.
The email code uses System.Net.Mail namespace - .Net framework 4.0.
We pass in the username and password for the NetworkCredential.
public void Send(string from, string[] to, string[] cc, string[] bcc, string subject, string body, string[] attachmentArr, Boolean isBodyHtml, string smtpServerName, int port = 25, bool enableSsl = true, string userName = null, string password = null, string domain = null, int timeoutMilliSec = 100000)
{
MailMessage objEmail = new MailMessage();
try
{
foreach (string toItem in to)
{
objEmail.To.Add(toItem);
}
if (cc != null)
{
foreach (string toItem in cc)
{
objEmail.CC.Add(toItem);
}
}
if (bcc != null)
{
foreach (string toItem in bcc)
{
objEmail.Bcc.Add(toItem);
}
}
objEmail.From = new MailAddress(from);
objEmail.Subject = subject;
objEmail.Body = body;
objEmail.IsBodyHtml = isBodyHtml;
objEmail.Priority = MailPriority.High;
if (attachmentArr != null)
{
foreach (String s1 in attachmentArr)
{
objEmail.Attachments.Add(new Attachment(s1));
}
}
using (SmtpClient smtp = new SmtpClient(smtpServerName))
{
if (string.IsNullOrEmpty(userName) == false && string.IsNullOrEmpty(password) == false)
{
NetworkCredential credential = (string.IsNullOrEmpty(domain)) ? new NetworkCredential(userName, password) : new NetworkCredential(userName, password, domain);
smtp.Credentials = credential;
}
smtp.Timeout = timeoutMilliSec;
smtp.Port = port;
smtp.EnableSsl = enableSsl;
smtp.Send(objEmail);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (attachmentArr != null && objEmail.Attachments != null)
{
foreach (Attachment a1 in objEmail.Attachments)
{
a1.Dispose();
}
}
}
}

We finally found what was going on - Email throttling.
Office365 has a Throttling limit of 30 messages per minute for SMTP client submission https://technet.microsoft.com/en-us/library/dn554323%28v=exchg.150%29.aspx#summary
The solution was to send less than 30 messages per minute. I think it is affected by other messages (sent by Outlook) showing up to be sent by the server too. We pushed ours down to almost a five second delay between messages. We have not seen the error reoccur since.

Related

Why JavaFX stucks when running a process?

I am building an application using JavaFX. Application does some CRUD operations with the MySQL Database. So currently, I have 2 functions.
User Registration.
Email Validation (Check if email already exists in the database).
User registration is called in a JFoenix Button event. When it clicked it is calling separate 3 functions in another class as follows,
public static int insertUser(User user) {
int status = 0;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO users (name, password, email, country) VALUES (?, ?, ?, ?)");
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
ps.setString(4, user.getCountry());
status = ps.executeUpdate();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
public static int updateTime(String email, String timestamp) {
int status = 0;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("UPDATE users SET timestamp = ? WHERE email = ?");
ps.setString(1, timestamp);
ps.setString(2, email);
status = ps.executeUpdate();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
The problem is when I click the Button I see it is getting stuck while running that process. So I put that code inside the following,
Platform.runLater(() -> {
try {
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
});
Now it is somewhat okay but I see it is getting a little stuck after clicking (Ripple effect is not working well and also the mouse hover effect is not working as usual).
And Email Validation is done when the user types an email in the text field and the key released event is triggered and it is checking for the database result. The code for checking email is as follows,
public static boolean emailAvailability(String email) {
boolean status = false;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT email FROM users WHERE email = ?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();
status = rs.next();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
In the key event also it is getting stuck more. Can't type a character for some milliseconds.
I don't see any issue with my code because I have done this many times with Java Swing and all are perfectly working fine in Swing. And if a button is getting stuck with the running process I just put those codes inside the following and it works perfect,
new Thread(new Runnable() {
public void run() {
}
}).start();
I am not going to or trying to compare Java Swing and JavaFX But I need to know why JavaFX is behaving like this? What should I do to avoid this and run the program smoothly with the CSS effects if it is a huge process or not? Really appreciate it if anybody can help me. Thanks in advance.
UPDATE
Here is my signUp code. Executes when button clicks,
private void signUp(ActionEvent event) {
if (name.getText.equals("") && name.getText().isEmpty()) {
if (!name.getStyleClass().contains("error-class")) {
name.getStyleClass().add("error-class");
nameImageValidation.setImage(new Image("danger.png"));
nameImageValidation.setVisible(true);
}
} else {
name.getStyleClass().removeIf(style -> style.equals("error-class"));
nameImageValidation.setVisible(false);
}
if (password.getText.equals("") && password.getText().isEmpty()) {
if (!password.getStyleClass().contains("error-class")) {
password.getStyleClass().add("error-class");
passwordImageValidation.setImage(new Image("danger.png"));
passwordImageValidation.setVisible(false);
}
} else {
password.getStyleClass().removeIf(style -> style.equals("error-class"));
passwordImageValidation.setVisible(false);
}
if (email.getText.equals("") && email.getText().isEmpty()) {
if (!email.getStyleClass().contains("error-class")) {
email.getStyleClass().add("error-class");
emailImageValidation.setImage(new Image("danger.png"));
emailImageValidation.setVisible(false);
}
} else {
email.getStyleClass().removeIf(style -> style.equals("error-class"));
emailImageValidation.setVisible(false);
}
if (country.getText.equals("") && country.getText().isEmpty()) {
if (!country.getStyleClass().contains("error-class")) {
country.getStyleClass().add("error-class");
countryImageValidation.setImage(new Image("danger.png"));
countryImageValidation.setVisible(false);
}
} else {
country.getStyleClass().removeIf(style -> style.equals("error-class"));
countryImageValidation.setVisible(false);
}
if(emailValidation() && passwordValidation() && fieldsValidation()) {
User user = new User(name.getText(), email.getText(), password.getText(), country.getText());
int insertStatus = UserController.insertUser(user);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
if (insertStatus > 0) {
int updateStatus = UserController.updateTime(email.getText(), timestamp.toString());
if(updateStatus > 0) {
// Go to Login Page
} else {
showAlert(); // Error Message
}
} else {
showAlert(); // Error Message
}
} else {
showAlert(); // Error Message
}
}
Here the validateEmail code. Executes when user typing the email. Triggered when Key Released and when performing this after type a character have to wait some time and then appear next character and go...
private void validateEmail(KeyEvent event) {
boolean status = UserController.emailAvailability(email.getText());
if (!status) {
email.getStyleClass().removeIf(style -> style.equals("success-class"));
emailImageValidation.setImage(new Image("safe.png"));
emailImageValidation.setVisible(true);
} else {
email.getStyleClass().removeIf(style -> style.equals("error-class"));
emailImageValidation.setImage(new Image("danger.png"));
emailImageValidation.setVisible(true);
}
}
When you trigger a function from the GUI, execution happens in the main thread. Now, these calls are blocking, which means that until they return, the main thread can't update the GUI.
There are generally two ways to solve this:
Async functions, that yield (allows other code to run) until the resource they are waiting for become available
Threads, which means running part of the program in parrallel, which most likely will require you to think about locks etc.
I suggest you look into these two things, as they are quite central to making good apps that are connected to other services and IO

SMTP gmx server problam

Im tyring to send an email with my program to an gmx email. Every time I try to send the mail I get the same error message in my console.
What can be the solution for that?
The error message:
System.Net.Mail.SmtpException: SMTP server requiers secure connection or the client wasnt authenticated. server response was: authentication required.
in - System.Net.Mail.SendMailAsyncResult.End(IAsyncResult result)
in - System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace SMTP_Client
{
class Program
{
static bool mailSent = false;
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Cancelled)
{
Console.WriteLine("[{0}] Send canceled.", token);
}
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
}
else
{
Console.WriteLine("Message sent.");
}
mailSent = true;
}
public static void Main(string[] args)
{
SmtpClient client = new SmtpClient("smtp.gmx.com",25);
MailAddress from = new MailAddress("example#project.com", "me " + (char)0xD8 + " you", System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("example#gmx.com");
MailMessage message = new MailMessage(from, to);
message.Body = "The project has succeeded ";
message.Subject = "made it!";
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = "test message2\n";
client.SendAsync(message, userState);
Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();
if (answer.StartsWith("c") && mailSent == false)
{
client.SendAsyncCancel();
}
message.Dispose();
Console.WriteLine("proccess ended.");
}
}
}

MySql Query Sent by Email

I have a simple query that select some fields from a few different tables and I need it to run once a month. I know i can schedule a monthly "job" with the CREATE EVENT, however, is it possible to have that information emailed to some addresses after the query runs? That way i don't need to log into the server and look at the new file?
I think that Mysql doesn't support Email sending.
In this case, you can develop an auxiliary program that sends the file created, and execute it with - scheduled task, Cron ...(It depends on the Operating System of the server you're using).
The auxiliary program can be like this code adding the file/s you want to attach (attachFiles variable).
public class EmailAttachmentSender {
public static void sendEmailWithAttachments(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, String[] attachFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Test sending e-mail with attachments
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "your-email-address";
String password = "your-email-password";
// message info
String mailTo = "your-friend-email";
String subject = "New email with attachments";
String message = "I have some attachments for you.";
// attachments
String[] attachFiles = new String[3];
attachFiles[0] = "e:/Test/Picture.png";
attachFiles[1] = "e:/Test/Music.mp3";
attachFiles[2] = "e:/Test/Video.mp4";
try {
sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
subject, message, attachFiles);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}
Mysql does not support that functionality.
You can use a cron job (Quartz) to schedule a job every month,
where you can fetch the data and shoot an email containing your data.
Refer the below link for quartz job :
http://www.mkyong.com/java/example-to-run-multiple-jobs-in-quartz/
is it possible to have that information emailed to some addresses
after the query runs?
If you are looking for a MySQL built in solution then probably NO. This particular should be handled in application end.
So, if you are scheduling the query as cron job in linux (OR) batch job in windows then you can configure cron (or) batch to send an email to list of recipients once the query finishes.
How to configure cron to send mail can be checked HERE
I haven't done this myself but I see no reason why it shouldn't work: create a UDF (user defined function) that takes the e-mail parameters and sends out the e-mail. You can write UDFs e.g. in C++ and have so all necesssary libraries at hand.

Connecting SSIS WebService task to Spring WevService

I have a SSIS package in which i use a WebService task to call a Spring WS.
The authentication is done by client certificate and username & password.
I have tried to do it like this a simple HttpConnection and a WebService task - Error 504 Gateway Timeout. When i edit the HttpConnection and click on Test Connection i get an error that states:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
I have tried doing it with a script task and the same error.
I have even tried with a dummy console application and the same result.
I also have a java written app that actually does the job but i do not have access to it's code-behind. This basically proves that the problem is not from the server itself.
The java application has it's own keystore and the same certificates that i have installed on the server.
I opened a wireshark capture and i saw that when i used either of my apps the host made a DNS request for an address that i did not configure anywhere(it seems like a proxy address from the intranet), while the java app made a DNS request with the correct address.
I am stuck here, and i have no idea what the problem might be or what else i can do so that i would get a proper error.
Please advise!
Edit:
This is the code that calls the WS:
public static void CallWebService()
{
var _url = "https://<IP>/App/soap/DataService";
string action = "getData";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("param1", "0");
parameters.Add("param2", "0");
parameters.Add("param3", "value");
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(action, parameters);
HttpWebRequest webRequest = CreateWebRequest(_url);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
}
Console.WriteLine(soapResult);
}
private static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
string thumbprint = "CERTIFICATE THUMBPRINT";
byte[] thumbprintArray = new byte[thumbprint.Split(new char[]{ ' ' }).Length];
string[] stringArray = thumbprint.Split(new char[] { ' ' });
for (int i = 0; i < thumbprintArray.Length; i++)
{
thumbprintArray[i] = Convert.ToByte(stringArray[i], 16);
}
X509Store localStore = new X509Store("My");
localStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCol = localStore.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
foreach (X509Certificate cert in certCol)
{
if (cert.GetCertHashString() == thumbprint)
{
webRequest.ClientCertificates.Add(cert);
break;
}
}
webRequest.UseDefaultCredentials = false;
webRequest.Credentials = new NetworkCredential("USER", "PASSWORD");
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string action, Dictionary<string, string> parameters)
{
string formatedParameters = string.Empty;
string paramFormat = "<{0}>{1}</{0}>";
foreach (string key in parameters.Keys)
{
formatedParameters += string.Format(paramFormat, key, parameters[key]);
}
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(string.Format(#"
<soapenv:Envelope xmlns:soap=""http://custom/soap/"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"">
<soapenv:Header/>
<soapenv:Body>
<soap:{0}>
{1}
</soap:{0}>
</soapenv:Body>
</soapenv:Envelope>", action, formatedParameters));
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}

System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.