JSON Post Request In C# - c#

I am a SQL Developer, JSON and C# are completely new to me. I am trying to get the JSON data from Rest API from elastic DB using POST method. I think my code is incorrect since I am getting all the response from the API even though I am passing string json variable in my c# code.
public static string COSMOS(string getAPiurl, string ApiUserId, string ApiPassword)
{
string url = getAPiurl;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/JSON";
webrequest.Accept = "application/JSON";
String username = ApiUserId;
String password = ApiPassword;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
webrequest.Headers.Add("Authorization", "Basic " + encoded);
using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
string json = "{\"query\":{\"bool\":{\"should\":[{\"match\":{\"platform\":{\"query\":\"COSMOS\"}}}],\"filter\":" +
"[{\"range\":{\"cu_ticketLastUpdated_date\":{\"gte\":\"2022-05-01 00:00:00\",\"lt\":" +
"\"2022-05-31 23:59:59\"}}}]}}}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var rl = streamReader.ReadToEnd();
httpResponse.Close();
}
I am using the above code in my SSIS script component. When I am trying to debug the above code in the var rl I am getting all the response even though I am passing the filters like "filter":[{"range":{"cu_ticketLastUpdated_date":{"gte":"2022-05-01 00:00:00","lt":"2022-05-31 23:59:59"}}
Please help me with an solution.

Related

POST JSON Data to web API in SSIS Script task from SQL

I have been searching for an answer to this question, but I keep coming up short so hopefully I can find an answer. Admittedly I am not the best C# programmer and this is born out of necessity and not having a resource to help develop this for me, so I have jumped in feet first.
I have some code that I have successfully posted JSON data to the API IF I hard code the JSON string, but I would like to set the results from a SQL query as an OBJ and then serialize them using NEWTONSOFT.JSON to pass to the API in place of the hard coded data.
public void Main()
{
string url = Dts.Variables["$Package::url"].Value.ToString();
string user = Dts.Variables["$Package::user"].Value.ToString();
string pwd = Dts.Variables["$Package::pwd"].GetSensitiveValue().ToString();
string result = Dts.Variables["User::JSON"].Value.ToString();
var JsonResult = JsonConvert.SerializeObject(result);
var request = (HttpWebRequest)WebRequest.Create(url);
string authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(user + ":" + pwd));
request.Headers.Add("Authorization", "Basic" + " " + authHeader);
request.ContentType = "application/json";
request.Accept = "application/json";
request.Method = "POST";
request.Headers.Add("Cookie: freedomIdentifyKey=XX");
result.ToString();
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(JsonResult);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result2 = streamReader.ReadToEnd();
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
I keep getting Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.
Any thoughts on how I could resolve this?
You don't need to use a StreamWriter.
string url = Dts.Variables["$Package::url"].Value.ToString();
string user = Dts.Variables["$Package::user"].Value.ToString();
string pwd = Dts.Variables["$Package::pwd"].GetSensitiveValue().ToString();
string result = Dts.Variables["User::JSON"].Value.ToString();
var JsonResult = JsonConvert.SerializeObject(result);
var request = (HttpWebRequest)WebRequest.Create(url);
string authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(user + ":" + pwd));
request.Headers.Add("Authorization", "Basic" + " " + authHeader);
request.ContentType = "application/json";
request.Accept = "application/json";
request.Method = "POST";
request.Headers.Add("Cookie: freedomIdentifyKey=XX");
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(JsonResult);
using (var dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
}
}
And if you want to use HttpClient instead:
string url = Dts.Variables["$Package::url"].Value.ToString();
string user = Dts.Variables["$Package::user"].Value.ToString();
string pwd = Dts.Variables["$Package::pwd"].GetSensitiveValue().ToString();
string result = Dts.Variables["User::JSON"].Value.ToString();
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
var client = new HttpClient();
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
var response = await client.PostAsync(url, result);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}
catch(HttpRequestException e)
{
// do something
}
Not tested
I was able to get this sorted out. The issue wasn't with the code, but rather with the Newtonsoft.JSON package. It was failing before it even got to the code and I was trying to run it as a SQL 2016 target. When I switched back to a 2019 project it ran fine. To get it to run as a 2016, I installed NEWTONSOFT.JSON using the GACUTIL and it runs great now.
I did make a change and used an SQL query in the code instead of using an execute SQL task and then passing it to a variable.

C# eBay OAuth Compliance API Authentication Problems

After many struggles, I was finally able to get the OAuth Authentication/Refresh token process down. I am certain that the tokens I am using in this process are good. But I am struggling to communicate with the Compliance API and I think it may have more to do with my headers authentication process than it does specifically the Compliance API but I am not certain. I've tried so many different combinations of the below code unsuccessfully. I've tried to do the call as a GET and a POST (the call should be a GET). I've tried it with the access token encoded and not encoded. With all of my different code combinations tried I've been getting either an authorization error or a bad request error. You can see some of the various things I've tried from commented out code. Thank you for your help.
public static string Complaince_GetViolations(string clientId, string ruName, string clientSecret, string accessToken, ILog log)
{
var clientString = clientId + ":" + clientSecret;
//byte[] clientEncode = Encoding.UTF8.GetBytes(clientString);
//var credentials = "Basic " + System.Convert.ToBase64String(clientEncode);
byte[] clientEncode = Encoding.UTF8.GetBytes(accessToken);
var credentials = "Bearer " + System.Convert.ToBase64String(clientEncode);
var codeEncoded = System.Web.HttpUtility.UrlEncode(accessToken);
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
// request.ContentType = "application/x-www-form-urlencoded";
//request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + codeEncoded);
request.Headers.Add(HttpRequestHeader.Authorization, credentials);
//request.Headers.Add("Authorization", "Bearer " + codeEncoded);
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = "";
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream())) //FAILS HERE
{
result = streamReader.ReadToEnd();
}
//DO MORE STUFF BELOW
return "STUFF";
}
And I finally figured out a resolution to this problem. The HTML encoding of the entire bearer string was the issue. If anyone needs this in the future your welcome. =)
HttpWebRequest request = WebRequest.Create("https://api.ebay.com/sell/compliance/v1/listing_violation?compliance_type=PRODUCT_ADOPTION")
as HttpWebRequest;
request.Method = "GET";
request.Headers.Add(HttpRequestHeader.Authorization, System.Web.HttpUtility.HtmlEncode("Bearer " + accessToken));
request.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY-US");
log.Debug("starting request.GetRequestStream");
string result = null;
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}

hoopla-api using ASP.NET WEB API

I want to make use of the hoopla-api which from their website uses "CURL" and I need to make HTTP "POST, GET" using C#.
They mention that any Questions related to development posted on stackoverflow but I didn't see any post from anyone who asked a question. or perhaps it is just too easy for many people to get this up.
Here is their link https://developer.hoopla.net/docs/authentication
I am not sure how to properly implement this in C#:
Below is my sample GET method.
string res;
string client_id = "myclientid";
string client_secret = "mysecret";
string auth = client_id + ":" + client_secret;
string ContentType = "application/json";
string url = #"https://api.hoopla.net/users";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//request.Credentials = new NetworkCredential(client_id, client_secret);
request.Headers.Add("Authorization", "Bearer" + auth);
request.ContentType = ContentType;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
res = reader.ReadToEnd();
}
and from their site they do have a python script that imports request module. but not sure if python has this module.
Here is their code :
import requests
client_id = 'your-generated-client-id'
client_secret = 'your-generated-client-secret'
host = 'https://api.hoopla.net'
auth_params = {'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret}
r = requests.post( host+'/oauth2/token', params = auth_params )
access_token = r.json()['access_token']
request_headers = {
'Authorization':'Bearer '+access_token,
'Accept':'application/vnd.hoopla.api-descriptor+json'
}
r = requests.get( host+'/',headers = request_headers )
}
Can anyone assist me in getting this in C#?

Authorize.Net Creating error creating a new WebHook

I'm a C# developer I need to use webhooks to get some stuff after the gethostpage with redirect.
Everything it's fine if I use GET ( get events, get my webhooks ), but when I'm going to create a new webhook I get a "The remote server returned an error: (400) Bad Request." for sure it's a stupid thing but I'm stuck.
Any tips?
The request
byte[] encoded = System.Text.Encoding.Default.GetBytes(apiLogin + ":" + transactionKey);
string base64 = System.Convert.ToBase64String(encoded);
var isPost = !string.IsNullOrWhiteSpace(json);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = isPost ? "POST" : "GET";
httpWebRequest.Headers.Add("Authorization", "Basic " + base64);
httpWebRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
if (isPost)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
}
}
string result = null;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
return result;
}
return result;
I'm trying the JSON sample from documentation sample
Found, it is need to create a signature in merchant panel before use "post" webhooks, "get" works also without doing it

Unable to get response with WebRequest of method post

I want to authenticate the users who visit my website using google's OAUTH2.0.
I have successfully got the authorization_code in response and now I am facing problem when I make a 'POST request' to Google when getting an access token. The problem is that the request is being continued over the time and I'm not getting any response.
Is there anything wrong in the code I have written below?
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string addons = "/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=123029216828.apps.googleusercontent.com&client_secret={zd5dYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code";
request.ContentLength = addons.Length;
Stream str = request.GetResponse().GetResponseStream();
StreamReader r = new StreamReader(str);
string a = r.ReadToEnd();
str.Close();
r.Close();
As I mentioned in my comment, you just have a few minor mistakes in your code. As it stands, you're not actually POST-ing anything. I'm assuming you intend to send the postData string.
The following should work:
//Build up your post string
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
//Create a POST WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//Write your post string to the body of the POST WebRequest
var sw = new StreamWriter(request.GetRequestStream());
sw.Write(postData.ToString());
sw.Close();
//Get the response and read it
var response = request.GetResponse();
var raw_result_as_string = (new StreamReader(response.GetResponseStream())).ReadToEnd();
You were just missing the part where you attached the string to your POST WebRequest.

Categories

Resources