I'm trying to call the https API from the WPF application but i'm getting this error:
InnerException = {"The underlying connection was closed: An unexpected
error occurred on a send."} Message = "An error occurred while sending
the request."
Can anyone help me what exactly the problem is?
private static readonly string apiURL =
"https://api.totalsynergy.com/api/v2/Profile/Index";
private async Task<bool> GetAuth(string accessToken)
{
try
{
HttpClient hc = new HttpClient();
HttpResponseMessage hpm = await hc.GetAsync(apiURL);
if (hpm.IsSuccessStatusCode)
{
var res = await hpm.Content.ReadAsAsync<Organization>();
}
return boolValue;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
return boolValue;
}
}
When is HTTPS, connection requires some protocols.
In my example I have a API URL that I call and can send some information and receive the response in JSON. You can adapt this to your problem:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//get OS version
var query = "SELECT version FROM Win32_OperatingSystem";
var searcher = new ManagementObjectSearcher(query);
var info = searcher.Get().Cast<ManagementObject>().FirstOrDefault();
string version = info.Properties["Version"].Value.ToString();
int majorVersion = Int32.Parse(version.Substring(0, version.IndexOf(".")));
//OS version is windows xp or older
if (majorVersion < 6)
{
//tls 1.0
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192;
}
else
{
//tls 1.1 or tls 1.2
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
}
//url to send data
string url = **YOUR URL**
//create request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Timeout = 240000;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = **REQUEST METHOd GET/POST**;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
//convert to byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(**Text to send or empty**);
//specify content of request - this example is in JSON
request.ContentType = "application/json";
if (requestMethod != RequestMethods.GET)
{
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
//send
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (var readers = new StreamReader(response.GetResponseStream()))
{
return result = readers.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
finally
{
request.Abort();
}
Related
I am using CFN to create an HA environment and RDS seems to be the best way for SQL Server DB rather than instances. Now I have tried manual deployment taking RDS and restoring .bak using option group and connecting it with S3 by IAM and EC2. But I am facing a wall when doing the same with CFN automation. Is there a way?
I don't have this in a state where I can "package it up for you", but this should give you a good head start....
public abstract class DatabaseFunctionBase
{
protected static bool IsTaskComplete(SqlConnection sqlConnection, int task)
{
try
{
using var command = sqlConnection.CreateCommand();
command.CommandText = "msdb.dbo.rds_task_status";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("task_id", SqlDbType.Int).Value = task;
using var reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
var s = new StringBuilder();
for (int i = 0; i < reader.FieldCount; i++)
{
s.AppendLine($"{i}={reader[i]}");
}
//LambdaLogger.Log(s.ToString());
var status = reader.GetString(5);
return status == "SUCCESS";
}
}
return false;
}
catch (Exception e)
{
//LambdaLogger.Log(e.ToString());
throw;
}
}
protected int GetTaskId(SqlConnection sqlConnection, string dbName)
{
try
{
using var command = sqlConnection.CreateCommand();
command.CommandText = "msdb.dbo.rds_task_status";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("db_name", SqlDbType.VarChar).Value = dbName;
do
{
using var reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.HasRows)
{
var s = new StringBuilder();
for (int i = 0; i < reader.FieldCount; i++)
{
s.AppendLine($"{i}={reader[i]}");
}
//LambdaLogger.Log(s.ToString());
var status = reader.GetString(5);
var id = reader.GetInt32(0);
var db = reader.GetString(2);
if ((status == "CREATED" || status == "IN_PROGRESS") && db == dbName)
{
return id;
}
}
Thread.Sleep(TimeSpan.FromSeconds(5));
}
} while (true);
throw new InvalidOperationException();
}
catch (Exception e)
{
//LambdaLogger.Log(e.ToString());
throw;
}
}
protected async Task BackupDatabaseAsync(BackupRestoreDatabaseInfo info, ILambdaContext context)
{
var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
{
DataSource = info.DbServer,
InitialCatalog = info.DbCatalog,
UserID = info.DbUserId,
Password = info.DbPassword,
Authentication = SqlAuthenticationMethod.SqlPassword,
MultipleActiveResultSets = true
};
var connectionString = sqlConnectionStringBuilder.ConnectionString;
//LambdaLogger.Log($"{nameof(this.BackupDatabaseFunctionAsync)}:{nameof(connectionString)}:{connectionString}");
await using var sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
await using var command = sqlConnection.CreateCommand();
command.CommandText = "msdb.dbo.rds_backup_database";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("source_db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
command.Parameters.Add("s3_arn_to_backup_to", SqlDbType.VarChar).Value =
$"{info.BackupBucket}/{info.DbCatalog}{DateTime.Now:O}.bak";
command.Parameters.Add("overwrite_S3_backup_file", SqlDbType.TinyInt).Value = 1;
command.ExecuteNonQuery();
var taskId = this.GetTaskId(sqlConnection, info.DbCatalog);
//LambdaLogger.Log($"{nameof(taskId)}={taskId}");
do
{
if (IsTaskComplete(sqlConnection, taskId))
{
//LambdaLogger.Log("Complete");
break;
}
//LambdaLogger.Log("Sleeping...");
await Task.Delay(TimeSpan.FromSeconds(15));
} while (true);
}
protected async Task CreateDatabaseAsync(BackupRestoreDatabaseInfo info, ILambdaContext context)
{
var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
{
DataSource = info.DbServer,
UserID = info.DbUserId,
Password = info.DbPassword,
Authentication = SqlAuthenticationMethod.SqlPassword,
MultipleActiveResultSets = true,
InitialCatalog = info.DbCatalog
};
await using (var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString))
{
try
{
sqlConnection.Open();
// already present - exit
return;
}
catch (Exception e)
{
//LambdaLogger.Log(e.ToString());
}
}
// remove the catalog so we can connect to the server directly
sqlConnectionStringBuilder.InitialCatalog = string.Empty;
await using (var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString))
{
sqlConnection.Open();
await using var restoreCommand = sqlConnection.CreateCommand();
restoreCommand.CommandText = "msdb.dbo.rds_restore_database";
restoreCommand.CommandType = CommandType.StoredProcedure;
restoreCommand.Parameters.Add("restore_db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
restoreCommand.Parameters.Add("s3_arn_to_restore_from", SqlDbType.VarChar).Value =
$"{info.BackupBucket}/{info.FromCatalog}.bak";
restoreCommand.ExecuteNonQuery();
var taskId = GetTaskId(sqlConnection, info.DbCatalog);
do
{
if (IsTaskComplete(sqlConnection, taskId))
{
//LambdaLogger.Log("Complete");
break;
}
//LambdaLogger.Log("Sleeping...");
await Task.Delay(TimeSpan.FromSeconds(15));
} while (true);
}
// this might be redundant in a merge
sqlConnectionStringBuilder.InitialCatalog = info.DbCatalog;
do
{
await using var sqlConnection = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
try
{
sqlConnection.Open();
break;
}
catch (Exception exception)
{
//LambdaLogger.Log(exception.ToString());
await Task.Delay(TimeSpan.FromSeconds(5));
}
} while (context.RemainingTime > TimeSpan.FromMinutes(1));
// this should already be in merged code
sqlConnectionStringBuilder.InitialCatalog = info.DbCatalog;
do
{
try
{
await using var sqlConnection2 = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
sqlConnection2.Open();
break;
}
catch (Exception e)
{
//LambdaLogger.Log(e.ToString());
await Task.Delay(TimeSpan.FromSeconds(15));
}
} while (context.RemainingTime > TimeSpan.FromMinutes(1));
// this should already be in merged code
}
protected async Task DeleteDatabase(BackupRestoreDatabaseInfo info, ILambdaContext context)
{
if (string.Equals(info.DbCatalog.ToString(), "app", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
var sqlConnectionStringBuilder = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder
{
DataSource = info.DbServer,
UserID = info.DbUserId,
Password = info.DbPassword,
Authentication = SqlAuthenticationMethod.SqlPassword,
MultipleActiveResultSets = true
};
var connectionString = sqlConnectionStringBuilder.ConnectionString;
//LambdaLogger.Log($"{nameof(this.BackupDatabaseFunctionAsync)}:{nameof(connectionString)}:{connectionString}");
await using var sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
await using var dropCommand = sqlConnection.CreateCommand();
dropCommand.CommandText = "msdb.dbo.rds_drop_database";
dropCommand.CommandType = CommandType.StoredProcedure;
dropCommand.Parameters.Add("db_name", SqlDbType.VarChar).Value = info.DbCatalog.ToString();
dropCommand.ExecuteNonQuery();
}
}
I have a code to get mail from live mail.
My step :
Connect to sever
Open folder
Get some informations
Close folder
Close store
But sometime I call this function, I got message from sever :
ERR Exceeded the login limit for a 15 minute period. Reduce the frequency of requests to the POP3 server
So How do I slove this problem. I closed connection and open new. I didnt keep connnection so why I got this error
public boolean POPgetMail(final String EMAIL,final String PASS,final String Type,boolean isNewMail) {
int NUMBER_MAIL=5;
Message[] message_s = null;
Properties props2 = System.getProperties();
props2.setProperty("mail.store.protocol", "pop3s");
Session session2 = Session.getInstance(props2, null);
session2.setDebug(true);
try {
Store store = session2.getStore("pop3s");
HOSTGET = "pop3.live.com";
store.connect(HOSTGET,EMAIL,PASS);
Log.i("","Connect Success");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
int new_mail=0;
message_s = folder.getMessages();
int countMail =folder.getMessageCount() -1;
if(countMail<0) {
folder.close(true);
store.close();
return false;
}
Log.i("","Total Mail + "+ countMail);
for (int i =countMail;i > NUMBER_MAIL;i--)
{
Message message = message_s[i];
if(message != null)
{
Log.i("MAIL","LOading Mail ID = " + i);
String subject ="No Subject";
try {
subject=message.getSubject().toString();
}
catch(Exception e)
{
Log.i("XX",e.toString());
}
String contents="";
int ID =i;
Date Date = message.getSentDate();
String date = DatenTime.convertDate(Date);
Address[] froms = message.getFrom();
//get TO
String to="";
try {
Address[] tos = message.getRecipients(Message.RecipientType.TO);
if(tos!=null)
{
for (int j=0;j<tos.length;j++){
to+=((InternetAddress)tos[j]).getAddress() +";";
Log.i("","TOOOOOOOO" + to);
}
}
}
catch (Exception e)
{
Log.i("",e.toString());
}
//get CC
Address[] toCC = message.getRecipients(Message.RecipientType.CC);
String CC="";
if(toCC!=null)
{
for (int j=0;j<toCC.length;j++){
CC+=((InternetAddress)toCC[j]).getAddress() +";";
Log.i("","TOOOOOOOO" + CC);
}
String name = ((InternetAddress) froms[0]).toUnicodeString();
String from = ((InternetAddress) froms[0]).getAddress();
if(mDB.InsertEmailData(ID,EMAIL,name,from,to,CC,contents,subject,date,Define.INBOX)!=-1)
{
System.out.println("get mail success");
}
}
}
folder.close(true);
store.close();
mDB.close();
return true;
} catch (Exception e) {
Log.i("","EX " + e.toString());
return false;
}
}
I guess you didn't understand the error message. It's not that you kept the connection open for too long, it's that you made too many separate connections in a 15 minute period. Don't connect so often.
Currently attachment takes stream for the content, is it possible to set a youtube video url for the attachment?
Thanks
This is not yet possible with the current version of the API and Glass client. Feel free to file a feature request on our issues tracker.
It is possible to stream a youtube video in the timeline card, here is the C#.Net code. use this name space "YoutubeExtractor".This works fine for me. When getting the youtube video url get the link that comes after you select share.
private static String InsertItem5(MainController controller)
{
string link = "http://youtu.be/9uYKISlL7Vg";
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
String vLink = video.DownloadUrl;
TimelineItem critical = new TimelineItem()
{
Text = "Menu Card",
BundleId = "666",
Notification = new NotificationConfig() { Level = "DEFAULT" },
MenuItems = new List<MenuItem>()
{
new MenuItem() {Action = "DELETE"},
}
};
String mediaLink = vLink;
if (!String.IsNullOrEmpty(mediaLink))
{
Stream stream = null;
if (mediaLink.StartsWith("/"))
{
stream = new StreamReader(controller.Server.MapPath(mediaLink)).BaseStream;
}
else
{
HttpWebRequest request = WebRequest.Create(mediaLink) as HttpWebRequest;
request.UseDefaultCredentials = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
byte[] b = null;
using (Stream streamFromWeb = response.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = streamFromWeb.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (streamFromWeb.CanRead && count > 0);
b = ms.ToArray();
stream = new MemoryStream(b);
}
}
controller.Service.Timeline.Insert(critical, stream, "video/mp4").Upload();
}
else
{
controller.Service.Timeline.Insert(critical).Fetch();
}
I have been reading about how to handle AJAX in Selenium webdriver. There are a lot of solutions. Is there one best and correct solution?
The solutions I have read about so far are:
1) Using thread sleep
2) waitFor method
3) ExpectedCondition
4) FluentWait
5) PresenceOfElementLocated
Thanks!
The reliable solution to handle ajax components(as used in my case) is to wait for the element to be visible on the page using waitUntil() API call of webdriver.
Otherwise threadsleep() like solution is not at all recommended to handle Ajax.
I have used this and it itself waits works fine.
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thanks try it.
If you're using jQuery, this is what I recommend. You can control exactly how often polling happens.
// poll every 1/3 second for 3 seconds
int timeout = 3; // seconds
int pollFreq = 3; // times per second
WebDriverWait wait = new WebDriverWait(driver, timeout, 1000/pollFreq);
// to be safe, test (driver instanceof JavascriptExecutor) here
JavascriptExecutor executor = ((JavascriptExecutor) driver);
// Check to see if jQuery is available first
Boolean hasJquery = (Boolean) executor.executeScript("return !!window.jQuery");
Boolean hasActive = (Boolean) executor.executeScript("return typeof window.jQuery.active === \"number\"");
if (hasJquery && hasActive) {
// Wait for JS AJAX calls to complete...
wait.until((ExpectedCondition<Boolean>) driver -> (Boolean) executor
.executeScript("return window.jQuery.active === 0"));
// JS AJAX calls completed.
// Good idea to add a timing report here for troubleshooting.
}
// else jQuery/active-prop not available, continue
You might want to try the Apache Http Client if you want to perform make ajax requests from your test. Here is some Groovy code that does this. Chances are not high that you are using Groovy, but this should still be informative regarding Get & Post in general with the client.
import groovy.util.Expando
import org.apache.commons.httpclient.HttpClient
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.httpclient.methods.PostMethod
import org.apache.commons.httpclient.methods.GetMethod
import java.io.BufferedReader
import java.io.InputStreamReader
import org.apache.commons.httpclient.Header
import java.net.URLDecoder
import com.auto.utils.crypto.Crypto
class ClientHttps {
private HttpClient client = null
private BufferedReader br = null
private String cookieString = ""
private crypto = new Crypto()
def log
public ClientHttps(log) {
this.log = log
client = new HttpClient();
client.getParams().setParameter("http.useragent", "Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2")
}
public Expando get(String url) {
def startTime = System.nanoTime()
GetMethod method = new GetMethod(url)
Expando returnData = new Expando()
try {
log.info("cookieString = " + cookieString)
method.addRequestHeader("Cookie", cookieString)
method.addRequestHeader("Accept", "application/json")
int returnCode = client.executeMethod(method)
log.info("returnCode = " + returnCode)
if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.error("The Get method is not implemented by this URI")
} else {
if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_PERMANENTLY))
assert false, "Bad Response Code"
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
String readLine;
while(((readLine = br.readLine()) != null)) {
log.info(readLine)
}
Header [] respHeaders = method.getResponseHeaders()
respHeaders.each () {
log.info(it.getName() + " = " + it.getValue())
returnData.setProperty(it.getName(), it.getValue())
}
}
def endTime = System.nanoTime()
def duration = endTime - startTime;
def seconds = (double)duration / 1000000000.0;
log.info("Get took = " + seconds + " seconds (Get url = " + url + ")")
return returnData;
} catch (Exception e) {
log.error(e.message, e)
return null
} finally {
method.releaseConnection()
if(br != null) try {
br.close()
} catch (Exception fe) {
log.info(fe.message, fe)
}
}
}
public Expando post(Expando postData) {
def startTime = System.nanoTime()
PostMethod method = new PostMethod(postData.getProperty("url"))
postData.getProperty("params").each() {method.addParameter(it.key, it.value)}
Expando returnData = new Expando()
try {
int returnCode = client.executeMethod(method)
log.info(returnCode)
if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
log.error("The Post method is not implemented by this URI")
} else {
if ((returnCode != HttpStatus.SC_OK) && (returnCode != HttpStatus.SC_MOVED_TEMPORARILY))
assert false, "Bad Response Code"
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()))
String readLine
while(((readLine = br.readLine()) != null)) {
log.info("Response Data = " + readLine)
}
Header [] respHeaders = method.getResponseHeaders()
respHeaders.each () {
log.info(it.getName() + " = " + it.getValue())
try {
returnData.setProperty(it.value.split("=")[0], it.value.split("=")[1])
}
catch (Exception exc) {
log.info("Could not split on equals sign = " + it.value)
}
}
}
def endTime = System.nanoTime()
def duration = endTime - startTime;
def seconds = (double)duration / 1000000000.0;
log.info("Post took = " + seconds + " seconds (Post url = " + postData.getProperty("url") + ")")
return returnData
} catch (Exception exc) {
log.info(exc.message, exc)
return null
} finally {
method.releaseConnection()
if(br != null) try {
br.close()
} catch (Exception fe) {
log.info(fe.message, fe)
}
}
}
}
I am trying to upload a PGP encrypted file through FTP. But I am getting an error message as follows:
The underlying connection was closed: An unexpected error occurred on a receive.
I am using the following code and getting the error at line:
Stream ftpStream = response.GetResponse();
Is there any one who can help me out ASAP.
Following is the code sample:
FtpWebRequest request =
WebRequest.Create("ftp://ftp.website.com/sample.txt.pgp") as FtpWebRequest;
request.UsePassive = true;
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream ftpStream = response.GetResponse();
int bufferSize = 8192;
byte[] buffer = new byte[bufferSize];
using (FileStream fileStream =
new FileStream("localfile.zip", FileMode.Create, FileAccess.Write))
{
int nBytes;
while((nBytes = ftpStream.Read(buffer, 0, bufferSize) > 0)
{
fileStream.Write(buffer, 0, nBytes);
}
}
Regards,
Sumeet
Why are you trying to upload using GetResponse()?
You need at least request.Method = WebRequestMethods.Ftp.UploadFile; and request.GetRequestStream();
ftp.UsePassive = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.KeepAlive = false;
ftp.UseBinary = true;
ftp.UsePassive = true;
ftp.Timeout = int.MaxValue;
ftp.ReadWriteTimeout = int.MaxValue;
ftp.Proxy = null;
ftp.Credentials = new NetworkCredential(values.UserName, values.Password);