Smtp Exception need perfect answers - smtpclient

I have this code which was working perfectly a few months ago. Now it throws two exceptions.
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 199.168.188.194:25
System.Net.Mail.SmtpException: 'Failure sending mail' -WebException: Unable to connect to the remote server
SocketException: 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.
MailMessage email_msg = new MailMessage("test#email.com", "test#email.com", "Order Confirm", "Dear ss! your Order Has Been Confirmed. Thanx For Shoping");
email_msg.IsBodyHtml = true;
SmtpClient mailclient = new SmtpClient();
System.Net.NetworkCredential basic = new System.Net.NetworkCredential("username", "password");
mailclient.Host = "mail.testdeva.com";
mailclient.UseDefaultCredentials = false;
mailclient.Credentials = basic;
mailclient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailclient.Send(email_msg);
email_msg.Dispose();
email_msg = null;
mailclient.Dispose();
mailclient = null;
Really appreciate the answers

Related

Azure Webjob, KeyVault Configuration extension, Socket Error

Need some help to determine if this is a bug in my code or in the config kevault extensions.
I have a netcore console based webjob. all working fine until a few weeks ago when we stated getting occasional startup errors which were Socket Error 10060 - Socket timed out or "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"
These were all related to loading configuration layers (app settings, env, command line and keyvault). The errors stemmed from the keyvault once the build was executed on the hostbuilder.
I initially added the retry policy with the default HttpStatusCodeErrorDetectionStrategy and an exponential back-off but this is not executing.
finally I added my own retry policy with my own detection strategy (see below). Still not being fired.
I have stripped down the code to a hello world like example and included the messages from the webjob.
Here is the code summary:
Main
public static async Task<int> Main(string[] args)
{
var host = CreateHostBuilder(args)
.UseConsoleLifetime()
.Build();
using var serviceScope = host.Services.CreateScope();
var services = serviceScope.ServiceProvider;
//**stripped down to logging just for debug
var loggerFactory = host.Services.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Main");
logger.LogDebug("Hello Test App Started OK. Exiting.");
//**Normally lots of service calls go here to do real work**
return 0;
}
HostBuilder - why hostbuilder? We use lots of components that are built for webapi and webapps so it was convenient to use a similar services model.
public static IHostBuilder CreateHostBuilder(string[] args)
{
var host = Host
.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((ctx, config) =>
{
//override with keyvault
var azureServiceTokenProvider = new AzureServiceTokenProvider(); //this is awesome - it will use MSI or Visual Studio connection
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var retryPolicy = new RetryPolicy<ServerErrorDetectionStrategy>(
new ExponentialBackoffRetryStrategy(
retryCount: 5,
minBackoff: TimeSpan.FromSeconds(1.0),
maxBackoff: TimeSpan.FromSeconds(16.0),
deltaBackoff: TimeSpan.FromSeconds(2.0)
)
);
retryPolicy.Retrying += RetryPolicy_Retrying;
keyVaultClient.SetRetryPolicy(retryPolicy);
var prebuiltConfig = config.Build();
config.AddAzureKeyVault(prebuiltConfig.GetSection("KeyVaultSettings").GetValue<string>("KeyVaultUri"), keyVaultClient, new DefaultKeyVaultSecretManager());
config.AddCommandLine(args);
})
.ConfigureLogging((ctx, loggingBuilder) => //note - this is run AFTER app configuration - whatever the order it is in.
{
loggingBuilder.ClearProviders();
loggingBuilder
.AddConsole()
.AddDebug()
.AddApplicationInsightsWebJobs(config => config.InstrumentationKey = ctx.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]);
})
.ConfigureServices((ctx, services) =>
{
services
.AddApplicationInsightsTelemetry();
services
.AddOptions();
});
return host;
}
Event - this is never fired.
private static void RetryPolicy_Retrying(object sender, RetryingEventArgs e)
{
Console.WriteLine($"Retrying, count = {e.CurrentRetryCount}, Last Exception={e.LastException}, Delay={e.Delay}");
}
Retry Policy - only fires for the non-MSI attempt to contact the keyvault.
public class ServerErrorDetectionStrategy : ITransientErrorDetectionStrategy
{
public bool IsTransient(Exception ex)
{
if (ex != null)
{
Console.WriteLine($"Exception {ex.Message} received, {ex.GetType()?.FullName}");
HttpRequestWithStatusException httpException;
if ((httpException = ex as HttpRequestWithStatusException) != null)
{
switch(httpException.StatusCode)
{
case HttpStatusCode.RequestTimeout:
case HttpStatusCode.GatewayTimeout:
case HttpStatusCode.InternalServerError:
case HttpStatusCode.ServiceUnavailable:
return true;
}
}
SocketException socketException;
if((socketException = (ex as SocketException)) != null)
{
Console.WriteLine($"Exception {socketException.Message} received, Error Code: {socketException.ErrorCode}, SocketErrorCode: {socketException.SocketErrorCode}");
if (socketException.SocketErrorCode == SocketError.TimedOut)
{
return true;
}
}
}
return false;
}
}
WebJob Output
[SYS INFO] Status changed to Initializing
[SYS INFO] Run script 'run.cmd' with script host - 'WindowsScriptHost'
[SYS INFO] Status changed to Running
[INFO]
[INFO] D:\local\Temp\jobs\triggered\HelloWebJob\42wj5ipx.ukj>dotnet HelloWebJob.dll
[INFO] Exception Response status code indicates server error: 401 (Unauthorized). received, Microsoft.Rest.TransientFaultHandling.HttpRequestWithStatusException
[INFO] Exception 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. received, System.Net.Http.HttpRequestException
[ERR ] Unhandled exception. System.Net.Http.HttpRequestException: 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.
[ERR ] ---> System.Net.Sockets.SocketException (10060): 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.
[ERR ] at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
[ERR ] --- End of inner exception stack trace ---
[ERR ] at Microsoft.Rest.RetryDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
[ERR ] at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
[ERR ] at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretWithHttpMessagesAsync(String vaultBaseUrl, String secretName, String secretVersion, Dictionary`2 customHeaders, CancellationToken cancellationToken)
[ERR ] at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretAsync(IKeyVaultClient operations, String secretIdentifier, CancellationToken cancellationToken)
[ERR ] at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
[ERR ] at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
[ERR ] at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
[ERR ] at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
[ERR ] at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
[ERR ] at Microsoft.Extensions.Hosting.HostBuilder.Build()
[ERR ] at HelloWebJob.Program.Main(String[] args) in C:\Users\mark\Source\Repos\HelloWebJob\HelloWebJob\Program.cs:line 21
[ERR ] at HelloWebJob.Program.<Main>(String[] args)
[SYS INFO] Status changed to Failed
[SYS ERR ] Job failed due to exit code -532462766
This is an issue in the KV connectivity which is identified by the PG. Below is an official statement from Product Group:
The Microsoft Azure App Service Team has identified an issue with the
Key Vault references for App Service and Azure Functions feature
related to intermittent failure to resolve references at runtime.
Engineers identified a regression in the system that reduced the
performance and availability of our scale unit’s ability to retrieve
key vault references at runtime. A patch has been written and deployed
to our fleet of VMs to mitigate this issue.
We are continuously taking steps to improve the Azure Web App service
and our processes to ensure such incidents do not occur in the future,
and in this case, it includes (but is not limited to): Improving
detection and testing of performance and availability of the Key Vault
App Setting References feature Improvements to our platform to ensure
high availability of this feature at runtime. We apologize for any
inconvenience.
For almost everyone, updating packages to the new Microsoft.Azure packages has mitigated this issue, so trying those would be my first suggestion.
Thanks #HarshitaSingh-MSFT, makes sense though I searched for this when I had the problem and couldn't find it.
As a work around, I added some basic retry code to the startup.
Main looks like this for now:
public static async Task<int> Main(string[] args)
{
IHost host = null;
int retries = 5;
while (true)
{
try
{
Console.WriteLine("Building Host...");
var hostBuilder = CreateHostBuilder(args)
.UseConsoleLifetime();
host = hostBuilder.Build();
break;
}
catch (HttpRequestException hEx)
{
Console.WriteLine($"HTTP Exception in host builder. {hEx.Message}, Name:{hEx.GetType().Name}");
SocketException se;
if ((se = hEx.InnerException as SocketException) != null)
{
if (se.SocketErrorCode == SocketError.TimedOut)
{
Console.WriteLine($"Socket error in host builder. Retrying...");
if (retries > 0)
{
retries--;
await Task.Delay(5000);
host?.Dispose();
}
else
{
throw;
}
}
else
{
throw;
}
}
}
}
using var serviceScope = host.Services.CreateScope();
var services = serviceScope.ServiceProvider;
var transferService = services.GetRequiredService<IRunPinTransfer>();
var result = await transferService.ProcessAsync();
return result;
}

Http Client with Source.tick

I am trying to connect http client to a http service exposed by server, the source should send request every 1 second for that I have crated following partial graphs:
def httpSourceGraph() = {
Source.fromGraph(GraphDSL.create() { implicit builder =>
val sourceOutLet = builder.add(Source.tick(FiniteDuration(0, TimeUnit.SECONDS), FiniteDuration(1,
TimeUnit.SECONDS),
HttpRequest(uri ="/test", method = HttpMethods.GET))).out
// expose outlet
SourceShape(sourceOutLet)
})
}
def httpConnFlow() = {
Flow.fromGraph(GraphDSL.create() { implicit builder =>
val httpSourceFlow = builder.add(Http(system).outgoingConnection(host = "localhost", port = 8080))
FlowShape(httpSourceFlow.in, httpSourceFlow.out)
})
}
the graph is composed as
val response= httpSourceGraph.via(httpConnFlow()).runForeach(println)
if the http server (localhost:8080/test) is up and running, everything works fine, every 1 second I can see the response coming back from the server. I am not able to any response in case of either server is down or it goes down later.
I think it should give me following error:
akka.stream.StreamTcpException: Tcp command [Connect(localhost/127.0.0.1:8080,None,List(),Some(10 seconds),true)] failed
This can tested with some wrong url as well. (domain name stackoverflow1.com and wrong url "/test")
Thanks for the help.
-Arun
I can propose one way to get the behavior that you are seeking. I think what's at the heart of your issue is that the Flow produced by Http().outgoingConnection will terminate when a failure is encountered. Once that happens, there is no more downstream demand to pull the requests from the Source and the whole flow stops. If you want something that will continue to emit elements downstream regardless of if the connection is lost then you might try and use a host connection pool instead of just a single connection. The pool will be more resilient to failures with individual connections and it's also setup from the get go to send either a Success or Failure downstream. A simplified version of your flow, using a host connection pool could be defined as follows:
val source =
Source.tick(
1 second,
5 second,
(HttpRequest(uri ="/", method = HttpMethods.GET), 1)
)
val connFlow = Http(system).
newHostConnectionPool[Int](host = "www.aquto.com", port = 80)
val sink = Sink.foreach[(util.Try[HttpResponse], Int)]{
case (util.Success(r), _ ) =>
r.entity.toStrict(10 seconds)
println(s"Success: ${r.status}")
case (util.Failure(ex), _) =>
println(s"Failure: ${ex.getMessage}")
}
source.via(connFlow).to(sink).run
I tested this out, unplugging my network connection in the middle of the test and this is what I see as output:
Success: 200 OK
Success: 200 OK
Failure: Tcp command [Connect(www.aquto.com/50.112.131.12:80,None,List(),Some(10 seconds),true)] failed
Failure: Tcp command [Connect(www.aquto.com/50.112.131.12:80,None,List(),Some(10 seconds),true)] failed
Failure: Tcp command [Connect(www.aquto.com/50.112.131.12:80,None,List(),Some(10 seconds),true)] failed
Success: 200 OK
Success: 200 OK

why NotFound error occur in REST services with windows Phone app?

i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.

MS Dynamics Great Plains Authentication - No Connection Could Be Made

I am trying to pull a list of vendors from my local instance of Great Plains.
When I visit
http://localhost:48620/DynamicsGPWebServices/DynamicsGPService.asmx
I am asked to login. I enter my windows credentials, then I see endpoint not found.
I know that the web service exists.
I know that my windows credentials are correct because they are the admin account.
I have the sample company installed.
Here is my code:
DynamicsGP g = new DynamicsGP();
g.Credentials = new NetworkCredential("username", "password", "domain");
// Create an instance of the web service want to do this
//asynchronously.
// Be sure the default credentials are used
//g.UseDefaultCredentials = true;
// Create a context with which to call the web service
Context context = new Context();
// Specify which company to use (sample company)
var companyKey = new CompanyKey();
companyKey.Id = (-1);
// Set up the context object
context.OrganizationKey = (OrganizationKey)companyKey;
context.CultureName = "en-US";
//error occurs after this line
VendorSummary[] vs = g.GetVendorList(new VendorCriteria(), context);
I receive this error:
{System.Net.WebException: Unable to connect to the remote server ---> > System.Net.Sockets.SocketException: No connection could be made because the target machine actively > refused it 127.0.0.1:48260
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)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at PMInvoices.DynamicsGPService.DynamicsGP.GetVendorList(VendorCriteria criteria, Context Context) in >c:\Users\joe_a84\Downloads\DeveloperToolkitSampleApps\PMInvoices\PMInvoices\PMInvoices\Web References\DynamicsGPService\Reference.cs:line 4069
I see the URL is this:
http://machinename:48620/DynamicsGPWebServices
where machinename is localhost.

JBoss EAP 5.1 Server not using Windows Network Setting

I'm trying to call a web service from my application. My system is protected with a Firewall and I'm using a Proxy to access any external URL/internet access. The application is running on JBoss EAP 5.1 server. The application fails to write to the service URL with IO Exception: 'Could not transmit message'.
However, when I'm trying to access the service URL with IE/Firefox, it's opening. Although the XML response I'm receiving from Browser states a generic error - 'invalid request parameters...', which is quite obvious. Because I'm not sending a proper request XML from Browser.
I'm really confused with this disparity. I used to believe that JBoss will pick up standard windows network settings, but in my case it is not.
My code is as follows:
String strUrl = "http://theurlgoeshere";
String requestXml = "<request></request>";
String wsResponse="";
SOAPConnection conn = null;
try {
MessageFactory msgFac = MessageFactory.newInstance();
MimeHeaders mh = new MimeHeaders();
mh.setHeader("Content-Type", "text/xml; charset=UTF-8");
log.info("Request Xml:" + requestXml );
InputStream is = new ByteArrayInputStream(requestXml.getBytes("UTF-8"));
SOAPMessage reqMsg = msgFac.createMessage(mh, is);
SOAPConnectionFactory conFac = SOAPConnectionFactory.newInstance();
conn = conFac.createConnection();
SOAPMessage repMsg = conn.call(reqMsg, strUrl);
ByteArrayOutputStream out = new ByteArrayOutputStream();
repMsg.writeTo(out);
wsResponse = new String(out.toByteArray());
}
catch (Exception e) {
e.printStackTrace();
}
Got it sorted few days back. Basically I am using HttpURLConnection now to add proxy setting in the java code itself while making the Webservice call. Just closing this question, since my query is solved.
Will update the new code, if anyone needs.