I am experiencing an issue where an async call works in my WinForms and Console test applications, but not when I implement the same code in my intended target format - a Windows service.
I always get the "A task was canceled" exception - and I can't figure out why :|
System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TotalArchiveService.CustomerServices.<ValidateCustomerCoreWSGen2>d__2.MoveNext() in C:\DeveloperArea\Dev\src\TotalArchiveService\CustomerServices.cs:line 123
Using Fiddler, I can see that the Windows service doesn't even call the service. At least there are no traces of it in the Fiddler log.
The following are code examples, where the two first ones are the WinForms and Console variants respectively. The last on is the non functioning Windows service.
In the Windows Service, the ValidateCustomer method is called in the OnElapsedTime method of the Windows service. I have tried several intervals, as I suspected that there were some kind of overlap of calls due to the async here, but it doesn't change anything. Even if it had been, I'd thought that I'd seen some traces of the first call in Fiddler, but there's nothing.
I am using .NET Framework 4.8 for the service and WinForms variants. .NET 6.0 for the Console app.
Any help or suggestions would be greatly appreciated.
WinForms
private static async Task<string> ValidateCustomerCoreWSGen2(string customerNumber)
{
REMOVED SECTION WHERE INTERNAL PARAMS WERE UPDATED FROMN CONFIG.
}
catch (Exception _ex)
{
_status = "CONFIG_ERROR";
}
try
{
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(_timeout) })
{
// Create HTTP request.
var customerBuilder = new UriBuilder(new Uri($"{_endpoint}"));
var customerRequest = new HttpRequestMessage(HttpMethod.Post, customerBuilder.Uri);
// Set SOAP action
customerRequest.Headers.Add("SOAPAction", "");
// SOAP body content
string xmlSOAP = GetXmlSOAP("CUSTOMERREAD", _sourceApplication, _destinationApplication, _function, _version, _username, _channel, _orgId, _orgUnit, customerNumber);
customerRequest.Content = new StringContent(xmlSOAP, Encoding.UTF8, "text/xml");
// Add signature headers to request object
await SignHttpRequestMessage(customerRequest);
// Call service
var customerResponse = await client.SendAsync(customerRequest);
//Response handling
if (customerResponse.IsSuccessStatusCode)
{
// Do what you want with response body
var responseBody = await customerResponse.Content.ReadAsStringAsync();
_status = "CUSTOMER_EXISTS";
}
else
{
_status = "CUSTOMER_READ_EXCEPTION";
var responseBody = await customerResponse.Content.ReadAsStringAsync();
var message = $"Response returned with status {customerResponse.StatusCode}. Reason: {customerResponse.ReasonPhrase}";
}
}
}
catch (Exception _ex)
{
_status = "SERVICE_ERROR";
}
return _status;
}
static async Task SignHttpRequestMessage(HttpRequestMessage request)
{
// externalize configuration of these
string certPath = "";
string keyStorePassword = "";
string keyId = "";
certPath = Path.GetFullPath(#"c:\cert2\cert.pfx"); // path to keystorefile
keyStorePassword = "REMOVED";
keyId = "REMOVED";
X509Certificate2Collection certs = new X509Certificate2Collection();
X509Certificate2 cert = new X509Certificate2(certPath, keyStorePassword, X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable);
var services = new ServiceCollection()
.AddHttpMessageSigning()
.UseKeyId(keyId)
.UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning(cert, HashAlgorithmName.SHA256))
.UseDigestAlgorithm(HashAlgorithmName.SHA256)
.UseUseDeprecatedAlgorithmParameter()
.UseNonce(false)
.UseHeaders()
.Services;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var signerFactory = serviceProvider.GetRequiredService<IRequestSignerFactory>())
{
var requestSigner = signerFactory.CreateFor(keyId);
await requestSigner.Sign(request);
}
}
request.Headers.Add("Signature", request.Headers.Authorization.ToString());
request.Headers.Authorization = null;
}
private static string GetXmlSOAP(string method, string sourceApplication, string destinationApplication, string function, string version, string username, string channel, string orgId, string orgUnit, string customerNumber)
{
string _xmlSOAP = "";
if (method.ToUpper() == "CUSTOMERREAD")
{
_xmlSOAP = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:wsc=""http://REMOVED""
xmlns:urn=""urn:REMOVED""
xmlns:urn1=""urn:REMOVED""
xmlns:urn2=""urn:REMOVED"">
<soapenv:Header>
<wsc:AutHeader>
<wsc:SourceApplication>" + sourceApplication + #"</wsc:SourceApplication>
<wsc:DestinationApplication>" + destinationApplication + #"</wsc:DestinationApplication>
<wsc:Function>" + function + #"</wsc:Function>
<wsc:Version>" + version + #"</wsc:Version>
<wsc:ClientContext>
<wsc:userid>" + username + #"</wsc:userid>
<wsc:credentials/>
<wsc:channel>" + channel + #"</wsc:channel>
<wsc:orgid>" + orgId + #"</wsc:orgid>
<!--Optional:-->
<wsc:orgunit>" + orgUnit + #"</wsc:orgunit>
<!--Optional:-->
<wsc:customerid>" + customerNumber + #"</wsc:customerid>
<!--Optional:-->
<wsc:locale>no_NO</wsc:locale>
<wsc:ip>127.0.0.1</wsc:ip>
</wsc:ClientContext>
</wsc:AutHeader>
</soapenv:Header>
<soapenv:Body>
<urn:customerReadRequest>
<urn:readQualification>
<urn1:internationalCustomerKey>
<urn2:internationalCustomerNumber>" + customerNumber + #"</urn2:internationalCustomerNumber>
</urn1:internationalCustomerKey>
</urn:readQualification>
</urn:customerReadRequest>
</soapenv:Body>
</soapenv:Envelope>";
}
return _xmlSOAP;
}
private void cmdCustomerRead_Click(object sender, EventArgs e)
{
lblStatus.Text = "Status:";
//ValidateCustomerCoreWSGen2(tbCustomerNumber.Text.Trim());
CallValidateCustomerAsync(tbCustomerNumber.Text.Trim());
}
private async void CallValidateCustomerAsync(string customerNumber)
{
string result = await ValidateCustomerCoreWSGen2(customerNumber);
lblStatus.Text = "Status: " + result;
}
Console
static async Task ExampleRequest()
{
var timeout = 30;
try
{
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(timeout) })
{
int textidx = 2;
// URL to soap service
var endpointUrlCustomer = "https://REMOVED";
// Create HTTP request.
var customerBuilder = new UriBuilder(new Uri($"{endpointUrlCustomer}"));
var customerRequest = new HttpRequestMessage(HttpMethod.Post, customerBuilder.Uri);
// set SOAP action
customerRequest.Headers.Add("SOAPAction", "");
// set SOAP body content
Console.WriteLine();
Console.WriteLine("************************* CUSTOMER ***********************");
string xmlSOAP = GetXmlSOAP("CUSTOMER", textidx);
customerRequest.Content = new StringContent(xmlSOAP, Encoding.UTF8, "text/xml");
// Add signature headers to request object
await SignHttpRequestMessage(customerRequest, textidx);
Console.WriteLine("Signed request HTTP");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerRequest + Environment.NewLine);
Console.WriteLine("Signed request XML");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerRequest.Content.ReadAsStringAsync().Result + Environment.NewLine);
// Perform request
Console.WriteLine("Send request");
Console.WriteLine("-----------------------------------------");
var customerResponse = await client.SendAsync(customerRequest);
Console.WriteLine();
Console.WriteLine("Response HTTP");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerResponse + Environment.NewLine);
Console.WriteLine("Response result XML");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerResponse.Content.ReadAsStringAsync().Result + Environment.NewLine);
if (customerResponse.IsSuccessStatusCode)
{
// Do what you want with response body
var responseBody = await customerResponse.Content.ReadAsStringAsync();
}
else
{
var responseBody = await customerResponse.Content.ReadAsStringAsync();
var message = $"Response returned with status {customerResponse.StatusCode}. Reason: {customerResponse.ReasonPhrase}";
throw new Exception(message);
}
}
}
catch (HttpRequestException e)
{
throw e;
}
}
static async Task SignHttpRequestMessage(HttpRequestMessage request, int testIdx)
{
// externalize configuration of these
string certPath = "";
string keyStorePassword = "";
string keyId = "";
if (testIdx == 1)
{
keyStorePassword = "REMOVED";
keyId = "REMOVED";
}
if (testIdx == 2)
{
certPath = Path.GetFullPath(#"c:\cert2\cert.pfx"); // path to keystorefile
keyStorePassword = "REMOVED";
keyId = "REMOVED";
}
else if (testIdx == 3)
{
certPath = Path.GetFullPath(#"REMOVED"); // path to keystorefile
keyStorePassword = "REMOVED";
keyId = "REMOVED";
}
X509Certificate2Collection certs = new X509Certificate2Collection();
X509Certificate2 cert = new X509Certificate2(certPath, keyStorePassword, X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable);
var services = new ServiceCollection()
.AddHttpMessageSigning()
.UseKeyId(keyId)
.UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning(cert, HashAlgorithmName.SHA256))
.UseDigestAlgorithm(HashAlgorithmName.SHA256)
.UseUseDeprecatedAlgorithmParameter()
.UseNonce(false)
.UseHeaders()
.Services;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var signerFactory = serviceProvider.GetRequiredService<IRequestSignerFactory>())
{
var requestSigner = signerFactory.CreateFor(keyId);
await requestSigner.Sign(request);
}
}
request.Headers.Add("Signature", request.Headers.Authorization.ToString());
request.Headers.Authorization = null;
}
static string GetXmlSOAP(string operation, int testIdx)
{
string xmlSOAP = "";
if (operation == "CUSTOMER")
{
if (testIdx == 1)
{
REMOVED
}
if (testIdx == 2)
{
xmlSOAP = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:wsc=""http://REMOVED""
xmlns:urn=""urn:REMOVED""
xmlns:urn1=""urn:REMOVED""
xmlns:urn2=""urn:REMOVED"">
<soapenv:Header>
<wsc:AutHeader>
<wsc:SourceApplication>REMOVED</wsc:SourceApplication>
<wsc:DestinationApplication>REMOVED</wsc:DestinationApplication>
<wsc:Function>REMOVED</wsc:Function>
<wsc:Version>REMOVED</wsc:Version>
<wsc:ClientContext>
<wsc:userid>REMOVED</wsc:userid>
<wsc:credentials/>
<wsc:channel>REMOVED</wsc:channel>
<wsc:orgid>REMOVED</wsc:orgid>
<wsc:orgunit>REMOVED</wsc:orgunit>
<wsc:customerid>REMOVED</wsc:customerid>
<wsc:locale>no_NO</wsc:locale>
<wsc:ip>127.0.0.1</wsc:ip>
</wsc:ClientContext>
</wsc:AutHeader>
</soapenv:Header>
<soapenv:Body>
<urn:customerReadRequest>
<urn:readQualification>
<urn1:internationalCustomerKey>
<urn2:internationalCustomerNumber>REMOVED</urn2:internationalCustomerNumber>
</urn1:internationalCustomerKey>
</urn:readQualification>
</urn:customerReadRequest>
</soapenv:Body>
</soapenv:Envelope>";
}
if (testIdx == 3)
{
REMOVED
}
}
}
Windows service
internal class CustomerServices
{
private static bool _extendedLogging = true;
public static string ValidateCustomer(string customerNumber)
{
string _status = "";
string _servicesType = CommonMethods.GetAppSetting("ServicesType");
//TODO: Check format, ref. "UNSUPPORTED_FORMAT" in HandleValidateCustomerException
//TODO: Check existing, ref. "CUSTOMER_NOT_FOUND" in HandleValidateCustomerException
if (_servicesType == "COREWSGEN2")
{
_status = ValidateCustomerCoreWSGen2(customerNumber).GetAwaiter().GetResult();
}
return _status;
}
private static async Task<string> ValidateCustomerCoreWSGen2(string customerNumber)
{
string _status = "";
string _username = "";
string _orgId = "";
string _orgUnit = "";
string _channel = "";
string _sourceApplication = "";
string _destinationApplication = "";
string _function = "";
string _version = "";
int _timeout = 30;
string _endpoint = "";
string _values = "";
try
{
_extendedLogging = (CommonMethods.GetAppSetting("ExtendedLogging").ToUpper() == "TRUE" ? true : false);
_values += "ExtendedLogging" + Environment.NewLine;
_username = CommonMethods.GetAppSetting("Username");
_values += "Username" + Environment.NewLine;
_orgId = CommonMethods.GetAppSetting("OrgId");
_values += "OrgId" + Environment.NewLine;
_orgUnit = CommonMethods.GetAppSetting("OrgUnit");
_values += "OrgUnit" + Environment.NewLine;
_channel = CommonMethods.GetAppSetting("CoreWSGen2Channel");
_values += "CoreWSGen2Channel" + Environment.NewLine;
_sourceApplication = CommonMethods.GetAppSetting("CoreWSGen2SourceApplication");
_values += "CoreWSGen2SourceApplication" + Environment.NewLine;
_destinationApplication = CommonMethods.GetAppSetting("CoreWSGen2DestinationApplication");
_values += "CoreWSGen2DestinationApplication" + Environment.NewLine;
_function = CommonMethods.GetAppSetting("CoreWSGen2Function");
_values += "CoreWSGen2Function" + Environment.NewLine;
_version = CommonMethods.GetAppSetting("CoreWSGen2Version");
_values += "CoreWSGen2Version" + Environment.NewLine;
_timeout = Int32.Parse(CommonMethods.GetAppSetting("CoreWSGen2TimeoutSeconds"));
_values += "CoreWSGen2Version" + Environment.NewLine;
_endpoint = CommonMethods.GetAppSetting("CustomerServicesEndpointAddress");
if (_extendedLogging)
{
Logging.LogAction("Application settings used for customer read:" + Environment.NewLine
+ "-------------------------------------------------" + Environment.NewLine
+ "Username = " + _username + Environment.NewLine
+ "OrgId = " + _orgId + Environment.NewLine
+ "OrgUnit = " + _orgUnit + Environment.NewLine
+ "Channel = " + _channel + Environment.NewLine
+ "SourceApplication = " + _sourceApplication + Environment.NewLine
+ "DestinationApplication = " + _destinationApplication + Environment.NewLine
+ "Function = " + _function + Environment.NewLine
+ "Version = " + _version + Environment.NewLine
+ "Timeout (seconds) = " + _timeout + Environment.NewLine
+ Environment.NewLine
+ "Endpoint = " + _endpoint + Environment.NewLine);
}
}
catch (Exception _ex)
{
_status = "CONFIG_ERROR";
Logging.LogException(new Exception("CustomerServices - Error when reading configuration file. Successfully read values: " + Environment.NewLine + _values + Environment.NewLine, _ex.InnerException));
}
try
{
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(_timeout) })
{
// Create HTTP request.
var customerBuilder = new UriBuilder(new Uri($"{_endpoint}"));
var customerRequest = new HttpRequestMessage(HttpMethod.Post, customerBuilder.Uri);
// Set SOAP action
customerRequest.Headers.Add("SOAPAction", "");
// SOAP body content
string xmlSOAP = GetXmlSOAP("CUSTOMERREAD", _sourceApplication, _destinationApplication, _function, _version, _username, _channel, _orgId, _orgUnit, customerNumber);
customerRequest.Content = new StringContent(xmlSOAP, Encoding.UTF8, "text/xml");
// Add signature headers to request object
await SignHttpRequestMessage(customerRequest);
// Call service
var customerResponse = await client.SendAsync(customerRequest);
if (_extendedLogging)
{
Logging.LogAction("Response header:" + Environment.NewLine + customerResponse + Environment.NewLine);
Logging.LogAction("Response content:" + Environment.NewLine + customerResponse.Content.ReadAsStringAsync().Result + Environment.NewLine);
}
//Response handling
if (customerResponse.IsSuccessStatusCode)
{
// Do what you want with response body
var responseBody = await customerResponse.Content.ReadAsStringAsync();
// Log response content if extended logging
if (_extendedLogging)
{
Logging.LogAction(responseBody);
}
_status = "CUSTOMER_EXISTS";
}
else
{
_status = "CUSTOMER_READ_EXCEPTION";
var responseBody = await customerResponse.Content.ReadAsStringAsync();
var message = $"Response returned with status {customerResponse.StatusCode}. Reason: {customerResponse.ReasonPhrase}";
Logging.LogException(new Exception(message));
}
}
}
catch (Exception _ex)
{
_status = "SERVICE_ERROR";
Logging.LogException(_ex);
}
return _status;
}
static async Task SignHttpRequestMessage(HttpRequestMessage request)
{
// externalize configuration of these
string certPath = "";
string keyStorePassword = "";
string keyId = "";
certPath = Path.GetFullPath(#"c:\cert2\cert.pfx"); // path to keystorefile
keyStorePassword = "internal-sls-test";
keyId = "73ae28ed2f31";
X509Certificate2Collection certs = new X509Certificate2Collection();
X509Certificate2 cert = new X509Certificate2(certPath, keyStorePassword, X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable);
var services = new ServiceCollection()
.AddHttpMessageSigning()
.UseKeyId(keyId)
.UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning(cert, HashAlgorithmName.SHA256))
.UseDigestAlgorithm(HashAlgorithmName.SHA256)
.UseUseDeprecatedAlgorithmParameter()
.UseNonce(false)
.UseHeaders()
.Services;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var signerFactory = serviceProvider.GetRequiredService<IRequestSignerFactory>())
{
var requestSigner = signerFactory.CreateFor(keyId);
await requestSigner.Sign(request);
}
}
request.Headers.Add("Signature", request.Headers.Authorization.ToString());
request.Headers.Authorization = null;
if (_extendedLogging)
{
Logging.LogAction("Signed request header:" + Environment.NewLine + request + Environment.NewLine);
Logging.LogAction("Signed request content:" + Environment.NewLine + request.Content.ReadAsStringAsync().Result + Environment.NewLine);
}
}
private static string GetXmlSOAP(string method, string sourceApplication, string destinationApplication, string function, string version, string username, string channel, string orgId, string orgUnit, string customerNumber)
{
string _xmlSOAP = "";
if (method.ToUpper() == "CUSTOMERREAD")
{
_xmlSOAP = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:wsc=""http://edb.com/ws/WSCommon_v22""
xmlns:urn=""urn:srv.cus.corews.enterprise.fs.evry.com:ws:customer:v20_1""
xmlns:urn1=""urn:srv.cus.corews.enterprise.fs.evry.com:domain:customer:v20_1""
xmlns:urn2=""urn:corews.enterprise.fs.evry.com:domain:common:v8"">
<soapenv:Header>
<wsc:AutHeader>
<wsc:SourceApplication>" + sourceApplication + #"</wsc:SourceApplication>
<wsc:DestinationApplication>" + destinationApplication + #"</wsc:DestinationApplication>
<wsc:Function>" + function + #"</wsc:Function>
<wsc:Version>" + version + #"</wsc:Version>
<wsc:ClientContext>
<wsc:userid>" + username + #"</wsc:userid>
<wsc:credentials/>
<wsc:channel>" + channel + #"</wsc:channel>
<wsc:orgid>" + orgId + #"</wsc:orgid>
<!--Optional:-->
<wsc:orgunit>" + orgUnit + #"</wsc:orgunit>
<!--Optional:-->
<wsc:customerid>" + customerNumber + #"</wsc:customerid>
<!--Optional:-->
<wsc:locale>no_NO</wsc:locale>
<wsc:ip>127.0.0.1</wsc:ip>
</wsc:ClientContext>
</wsc:AutHeader>
</soapenv:Header>
<soapenv:Body>
<urn:customerReadRequest>
<urn:readQualification>
<urn1:internationalCustomerKey>
<urn2:internationalCustomerNumber>" + customerNumber + #"</urn2:internationalCustomerNumber>
</urn1:internationalCustomerKey>
</urn:readQualification>
</urn:customerReadRequest>
</soapenv:Body>
</soapenv:Envelope>";
}
return _xmlSOAP;
}
}
I'm trying to make Multiple GET calls using the same client. I've tried multiple things. New Variables, New instances. Closing Clients. The second Stock Call doesnt go through ever. It fails at "while (client.connected())" on the second Call. It Doesnt get to returning headers.
Any Ideas?
Code look like this
void loop()
{
WiFiClientSecure client;
//Stock
String payload;
// Use WiFiClientSecure class to create TLS connection
Serial.print("connecting to ");
Serial.println(host);
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);
if (!client.connect(host, httpsPort))
{
Serial.println("connection failed");
client.stop();
//return;
}
//AAPL
String url = "/api/v1/quote?symbol=AAPL&token=XXXX";
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.0\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
while (client.connected())
{
String line = client.readStringUntil('\n');
// String line = client.readStringUntil('\r');
Serial.println(line);
if (line == "\r")
{
Serial.println("headers received");
payload = client.readStringUntil('\r');
//break;
}
}
Serial.println("payload");
Serial.println(payload);
// String line = client.readString();
//JsonObject& obj = doc.parseObject(payload);
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, payload);
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
// return;
client.stop();
}
//{"c":23.35,"d":-0.73,"dp":-3.0316,"h":24.6986,"l":23.25,"o":24.54,"pc":24.08,"t":1627588802}
double currentprice = doc["c"];
double pctchg = doc["d"];
// Print values.
Serial.println(currentprice);
Serial.println(pctchg);
Serial.println("closing connection");
client.stop();
delay(20000);
//SPY
String spyurl = "/api/v1/quote?symbol=SPY&token=XXXX";
Serial.print("requesting URL: ");
Serial.println(spyurl);
client.print(String("GET ") + spyurl + " HTTP/1.0\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
String spypayload;
while (client.connected())
{
String spyline = client.readStringUntil('\n');
// String line = client.readStringUntil('\r');
Serial.println(spyline);
if (spyline == "\r")
{
Serial.println("headers received");
spypayload = client.readStringUntil('\r');
//break;
}
}
Serial.println("spypayload");
Serial.println(spypayload);
// String line = client.readString();
//JsonObject& obj = doc.parseObject(payload);
StaticJsonDocument<200> spydoc;
DeserializationError spyerror = deserializeJson(spydoc, spypayload);
// Test if parsing succeeds.
if (spyerror) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(spyerror.f_str());
// return;
client.stop();
}
//{"c":23.35,"d":-0.73,"dp":-3.0316,"h":24.6986,"l":23.25,"o":24.54,"pc":24.08,"t":1627588802}
double SPYcurrentprice = spydoc["c"];
double SPYpctchg = spydoc["d"];
// Print values.
Serial.println(SPYcurrentprice);
Serial.println(SPYpctchg);
Serial.println("closing connection");
client.stop();
I'm an idiot.
Needed to keep the connection open on the first call
"Connection: Keep-Alive\r\n\r\n");
I'm using http://dictionary.reference.com/browse/:word and check the status of returned response to evaluate whether the 'word' definition exists or not. It works fine for correct words (200 status code). But for those spelled incorrectly (404 status code), I'm unable to catch the status code from HttpWebRequest.GetResponse(), as it returns null?
The thing is I'm using PostMan to check and I did receive status code 404 there for the following url:
http://dictionary.reference.com/browse/sdfsdsdc
Here's my implementation:
string baseURL = "http://dictionary.reference.com/browse";
bool result = false;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL + "/" + word);
request.Method = "GET";
//request.Timeout = 2000;
request.KeepAlive = false;
request.ContentType = "text/html; charset=UTF-8";
Console.WriteLine(request.RequestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode statusCode = response.StatusCode;
int statusCodeNumber = (int)statusCode;
Console.WriteLine("Status Code: " + statusCode + " - status number: " + statusCodeNumber);
try
{
if (statusCodeNumber == 200) result = true;
else if (statusCodeNumber == 404) { result = false; }
else { throw new UnknownStatusCodeException(); }
}
catch (UnknownStatusCodeException e) {}
response.Close();
}
catch (WebException e) {
}
}
Here's the WebException I caught
full-size-pic
Could someone give me some pointers? Thanks
Im trying to use a .net application but the application cant find the server in my local network.
Im using LdapExploreTool 2 with the following settings:
the base DN is "DC=exago,DC=local", the Ip address "192.168.1.250" and the server name "exago.local"
The connection is successful and this is the result:
Inputing the values:
Examining the code, i get the exception when "Bind to the native AdsObject to force authentication":
"The specified domain either does not exist or could not be contacted."
public bool IsAuthenticated(string domain, string ldapPath, string username, string pwd, string userToValidate)
{
string domainAndUsername = domain + #"\" + username;
if (string.IsNullOrEmpty(ldapPath))
SetLdapPath(domain);
else
_path = ldapPath;
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.INFO, "IsAuthenticated_DirectoryEntry:" + _path + "," + domainAndUsername + "," + pwd);
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
//check if domain is valid
int domainId = AppDomains.GetDomainIdByName(domain);
if (domainId == int.MinValue)
{
return false;
}
AppDomains d = AppDomains.GetRecord(domainId);
List<AppDomainQueries> lQueries = new List<AppDomainQueries>(AppDomainQueries.GetArray());
lQueries = lQueries.FindAll(delegate(AppDomainQueries dq) { return dq.DomainId == domainId && dq.Status == 'A'; });
string queryString = string.Empty;
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
string ldapAndQuerie = string.Empty;
//base account search
queryString = "(SAMAccountName=" + userToValidate + ")";
if (username != userToValidate)
{
if (lQueries.Count == 1)
ldapAndQuerie = lQueries.FirstOrDefault().QueryString;
if ((ldapAndQuerie != string.Empty) && (ldapAndQuerie != "*") && (ldapAndQuerie != "(objectClass = user)"))
queryString = "(&(SAMAccountName=" + userToValidate + ")" + ldapAndQuerie + ")";
}
search.Filter = queryString;
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.INFO, "LDAP=" + queryString);
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.ERROR, "App.Services.Core.LdapAuthentication.IsAuthenticated() Exception - (LDAP=" + queryString + ")" + ex.Message, ex);
return false;
}
return true;
}
How can i establish a connection?
The problem was the LDAP connection string,
it seems that it missed the actual location(IP + port) in the network.
LDAP://192.168.1.250:389/DC=exago,DC=local
WebRequest request = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Method = "POST";
string postData = "code=" + code + "&client_id=" + _clientId + "&client_secret=" + _clientSecret + "&redirect_uri=" + _callback_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
I have placed a google sign in button in HTML page, on its callback got auth code to call ajax web servcice containing above code. But I am getting Error 400 on GetResponse(), I don't know why. Can any body please help me?
I have found following link workable in my case:
Code on page Page load :
protected void Page_Load(object sender, EventArgs e)
{
if (Request["code"] != null)
{
vCode = Request["code"].ToString();
getRefreshToken();
}
else
{
Response.Redirect(vAuthURL + "?scope=" + vScope + "&state=%2Fprofile&client_id=" + vClientId + "&redirect_uri=" + vRedURL + "&response_type=code&access_type=offline&approval_prompt=force", false);
}
}
Following function is being called in page load when code is available:
private void getRefreshToken()
{
string vClientId = "974762xxxxxx-xxxxxxxxx.apps.googleusercontent.com";
string vSecCode = "xxxxxxxxxxxxxxx";
string vScope = "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.login";
string vRedURL = "http://localhost:50488/wwwroot/member/social/googlesignin.aspx";
string vAuthURL = "https://accounts.google.com/o/oauth2/auth";
StringBuilder authLink = new StringBuilder();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
authLink.AppendFormat("code={0}", vCode);
authLink.AppendFormat("&client_id={0}", vClientId);
authLink.AppendFormat("&client_secret={0}", vSecCode);
authLink.AppendFormat("&redirect_uri={0}", vRedURL);
authLink.Append("&grant_type=authorization_code");
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(authLink.ToString());
Stream os = null;
webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); // Send it
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse == null) { Response.Write("null"); }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string jsonStr = sr.ReadToEnd().Trim();
}
Probably the important thing was to get code with server side code instead of mixing the client code and server side access_token getting script. Hope this works for you too.