c# console application returning no results - restsharp

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

Just added:
//Required For SSL/TLS Error Start
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//Required For SSL/TLS Error End
and I got my results. Hope this helps someone else!

Related

Getting (401) UnAuthorized error on some requests not all, but most

I don't think this is a code issue, but we have a list of hundreds of addresses to process. Some return data and we are able to get Long and Lat but most return (401) UnAuthorized errors. What would cause this to happen? We have tried passing Host Headers and everything else, the REST API seems to work better in our development environment but throws way more errors when deployed to our Job Server. Any help on this issue will be greatly appreciated. We would like to understand why some calls work and others don't, we pass the same apiKey each time so this is really confusing. Thanks
Here is a code snippet using c# (Work in progress):
//GET THE LATITUDE AND LONGITUDE BASED OFF THE PHYSICAL ADDRESS
String clientAddress = clientRow["home_address"].ToString() + ", " + clientRow["home_city"].ToString() + ", " + clientRow["home_state"].ToString() + ", " + clientRow["home_zip"].ToString();
Logger.Debug("CLIENT ADDRESS: {0}", clientAddress);
String geocoderUri = "https://geocode.search.hereapi.com/v1/geocode?q=" + clientAddress + "&apiKey=xxxxxxxxxxxxxxxxxxxxx"; //KEY REMOVED FOR POSTING ON STACK OVERFLOW
var syncClient = new WebClient();
var content = syncClient.DownloadString(geocoderUri);
//CREATE THE JSON SERIALIZER AND PARSE OUR RESPONSE
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AddressData));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
var addressData = (AddressData)serializer.ReadObject(ms);
if (addressData.items.Count() > 0)
{
//INSERT THE LATITUDE AND LONGITUDE IN DB
String sLat = addressData.items[0].position.lat.ToString();
String sLong = addressData.items[0].position.lng.ToString();
Logger.Debug("CLIENT GEOLOCATION - Longitude: {0} Latitude: {1}", sLong, sLat);
insertLatLong(sLat, sLong, clientRow["clientID"].ToString(), 1);
}
}
Would you please try to use RestSharp lib for rest api?
Please see below sample code.
var client = new RestClient("https://geocode.search.hereapi.com/v1/geocode?q="+ clientAddress);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer YOUR TOKEN");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

WebClient or WebRequest to get the re-directed URL of the landing page

From the string I parsed from Bing's Pic of the Day, I got the info of the pic to be downloaded, let's say today it is /az/hprichbg/rb/PearlHarborWindows_EN-US8565186567, then we will have full URL of the image be like http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1366x768.jpg
Usually Bing has an image of higher resolutions, so I will download the image 1920x1200 too. It's easy with the URL changed to be like http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg, then give the task to a WebClient such as client1.DownloadFile(url, fileName)
The issue here is, some days, the resolution 1920x1200 is not available, and the download URL of this res.(1920x1200) will be re-directed to the URL of the image /sa/simg/hpb/NorthMale_EN-US8782628354_1920x1200.jpg - as default (you can check it).
So my try was a function to get the return/re-directed URL from the input URL:
Public Function GetWebPageURL(ByVal url As String) As String
Dim Request As WebRequest = WebRequest.Create(url)
Request.Credentials = CredentialCache.DefaultCredentials
Return Request.RequestUri.ToString
End Function
and compare to the input URL to see it they are different, but the result was not as expected.
Could anyone let me know the method to check this re-directed URL, like the return URL after we press Enter and wait for the site to load.
Please give me idea to overcome this obstacle. Thank you!
Notes: Some issues related to access rights on different PCs cause me not to use HttpWebRequest, so I prefer the solution not using HttpWebRequest (WebClient or others are better).
With help from #IvanValadares #AlenGenzić, and suggestion of Proxy for HttpWebRequest from #Jimi, I have come to the fair solution, as the below code:
url1 = "http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg"
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(url1), HttpWebRequest)
myHttpWebRequest.MaximumAutomaticRedirections = 1
myHttpWebRequest.AllowAutoRedirect = True
Dim defaultProxy As IWebProxy = WebRequest.DefaultWebProxy
If (defaultProxy IsNot Nothing) Then
defaultProxy.Credentials = CredentialCache.DefaultCredentials
myHttpWebRequest.Proxy = defaultProxy
End If
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse, HttpWebResponse)
url2 = myHttpWebResponse.ResponseUri.ToString
Label1.Text = url1
Label2.Text = url2
Use AllowAutoRedirect and check the StatusCode.
var webRequest = (HttpWebRequest)System.Net.WebRequest.Create("http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg");
webRequest.AllowAutoRedirect = false;
using (var response = (HttpWebResponse)webRequest.GetResponse())
{
if (response.StatusCode == HttpStatusCode.Found)
{
// Have been redirect
}
else if (response.StatusCode == HttpStatusCode.OK)
{
// Have not been redirect
}
}
Using HttpClient
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false
};
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync("http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg");
if (response.StatusCode == HttpStatusCode.Found)
{
// Have been redirect
}
else if (response.StatusCode == HttpStatusCode.OK)
{
// Have not been redirect
}
With help from #IvanValadares #AlenGenzić, and suggestion of Proxy for HttpWebRequest from #Jimi, I have come to the fair solution as below:
url1 = "http://www.bing.com/az/hprichbg/rb/PearlHarborWindows_EN-US8565186567_1920x1200.jpg"
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(url1), HttpWebRequest)
myHttpWebRequest.MaximumAutomaticRedirections = 1
myHttpWebRequest.AllowAutoRedirect = True
Dim defaultProxy As IWebProxy = WebRequest.DefaultWebProxy
If (defaultProxy IsNot Nothing) Then
defaultProxy.Credentials = CredentialCache.DefaultCredentials
myHttpWebRequest.Proxy = defaultProxy
End If
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse, HttpWebResponse)
url2 = myHttpWebResponse.ResponseUri.ToString
Label1.Text = url1
Label2.Text = url2
The System.Net.WebException: The remote server returned an error: (407) Proxy Authentication Required. is no longer thrown.

Zoho Creator API Integration Basic Authorization postUrl()

Here is my code and I am getting Internal Error for postural() call. By the way, one more thing I want to know how we can use verify_peer to 0(zero) for not using SSL things. What is wrong with my code?
void SendSMS(SMS SMSObject)
{
//CONFIGURATION
URL = "https://example.com/send_ack.php";
wbLogin = "wbLogin";
wbPwd = "wbPwd";
wbAccount = "wbAccount";
label = "label";
applicationName = "ADR SMS v1.0";
//BASE64 ENCODING
Base64Encoded = zoho.encryption.base64Encode("httpLogin:httpPwd");
AuthorizationBasic = "Authorization: Basic " + Base64Encoded;
//HEADER
HeaderMap = Map();
HeaderMap.put("content-type", "application/x-www-form-urlencoded");
HeaderMap.put("Authorization", AuthorizationBasic);
//REQUEST
RequestMap = Map();
RequestMap.put("compte", wbAccount);
RequestMap.put("op", 1);
RequestMap.put("type", 0);
RequestMap.put("dt", zoho.currentdate.getDay());
RequestMap.put("hr", zoho.currenttime.getHour());
RequestMap.put("mn", zoho.currenttime.getMinutes());
RequestMap.put("label", label);
RequestMap.put("dest_num", "phone_number");
RequestMap.put("msg", "ZC Testing");
RequestMap.put("ref", "ZC");
//CALL POSTURL
Result = postUrl(URL, RequestMap, HeaderMap, false);
//DEBUG
info Result;
}
Use Zoho Creator API for this purpose.

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

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

How do I add just a username within an authentication header in stripe-payments?

I'm trying to get a simple post request to work to create a customer via the Stripe.js API.
https://stripe.com/docs/api/java#authentication
I'm doing this in vb.net and don't want to use the stripe.net library.
I keep getting authorization failed. All I have to pass is the username in the header, or in this case the username is my test api key.
Here's a chunk of the code:
Dim asPostRequest As HttpWebRequest = WebRequest.Create(String.Format(ApiEndpoint))
Dim as_ByteArray As Byte() = Encoding.UTF8.GetBytes(stripeccw.ToString)
asPostRequest.Method = "POST"
asPostRequest.ContentType = "application/json"
'asPostRequest.Headers("Authorization") = "Basic" + apikey
'asPostRequest.Credentials("bearer", apikey)
'asPostRequest.Headers.Add("Authorization") = apikey
'asPostRequest.Credentials("Username") = apikey
'asPostRequest.Credentials = New NetworkCredential(apikey, "")
asPostRequest.ContentLength = as_ByteArray.Length
Dim as_DataStream As Stream = asPostRequest.GetRequestStream()
as_DataStream.Write(as_ByteArray, 0, as_ByteArray.Length)
as_DataStream.Close()
Where I've commented out... those are different ways that I've tried. I know some are just stupid attempts, but just getting frustrated. I know for a fact my api key is correct. I can verify this by navigating to https://api.stripe.com/v1/customers and entering it in for my username only.
Hoping someone can spot something simple :)
Thank you!
If I were in your shoes, the first thing I'd do is take a look at how Stripe.Net does it. Even if you don't want to use that library yourself, that doesn't mean you can't use the source code as a reference.
From Requestor.cs:
internal static WebRequest GetWebRequest(string url, string method, string apiKey = null, bool useBearer = false)
{
apiKey = apiKey ?? StripeConfiguration.GetApiKey();
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
if(!useBearer)
request.Headers.Add("Authorization", GetAuthorizationHeaderValue(apiKey));
else
request.Headers.Add("Authorization", GetAuthorizationHeaderValueBearer(apiKey));
request.Headers.Add("Stripe-Version", StripeConfiguration.ApiVersion);
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Stripe.net (https://github.com/jaymedavis/stripe.net)";
return request;
}
private static string GetAuthorizationHeaderValue(string apiKey)
{
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", apiKey)));
return string.Format("Basic {0}", token);
}
private static string GetAuthorizationHeaderValueBearer(string apiKey)
{
return string.Format("Bearer {0}", apiKey);
}
So it seems there are two ways to do it. You can either use "Bearer" format, which is:
asPostRequest.Headers.Add("Authorization", "Bearer " & apiKey)
or you can use "Basic" format which is:
asPostRequest.Headers.Add("Authorization", _
"Basic " & Convert.ToBase64String(Encoding.UTF8.GetBytes(apiKey & ":")))