Issue while creating product using Shopify API - c#

I am experiencing a weird issue while exporting some products to Shopify. When I save a JSON generated using JSON.net to txt file and then read it and then send it to Shopify's create product API, it works fine. However, if I just save the JSON to string and send post request directly, I get a 502 gateway error from Shopify. This happens only when creating certain products, where the JSON payload is somewhat bigger than normal. On other products, just saving JSON to a string and then sending to Shopify works OK. Weirdly, when I save the JSON to file from C#, then read that file a few lines below in the same code, and use that content as JSON string and send a post request, it again doesn't work. What do you think could be the issue?
Here's the JSON generated using JSON.net which works OK when read from file (https://pastebin.com/9SKFPjGJ)
var jsonContent = JsonConvert.SerializeObject(myObject);
using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, $"https://{shopifySlug}.myshopify.com/admin/products/{originalShopifyProductId}.json"))
{
requestMessage.AddShopifyHeaders(shopifyAccessToken); // just a method for adding necessary shopify headers
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
response = await client.SendAsync(requestMessage);
}
Its getting hard for me to know the reason.
Here's what works:
Code that works:
json.txt was generated using this separately:
System.IO.File.WriteAllText("E:\\json.txt",JsonConvert.SerializeObject(myObject));
(Note that if the above line of code is inserted before the code below in the same file, then the code below doesn't work, i.e. the file has to be saved separately for it to work).
And then, just reading the JSON from file and sending that in the POST request works. Code below:
var jsonContent = System.IO.File.ReadAllText("E:\\json.txt");
using (var requestMessage = new HttpRequestMessage(HttpMethod.Put, $"https://{shopifySlug}.myshopify.com/admin/products/{originalShopifyProductId}.json"))
{
requestMessage.AddShopifyHeaders(shopifyAccessToken); // just a method for adding necessary shopify headers
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
response = await client.SendAsync(requestMessage);
}
Also the not working code at the very top works OK for smaller JSON payloads like this one https://pastebin.com/RhYjVuvv

Related

How to call ChatGPT from C# using HttpClientFactory, I keep getting errors and no responses

Getting really irritated with this. The playground gives only python and node, trying to use this in C# and I keep getting errors. Here is how I have it setup.
First in the Program / Startup file, I am setting it up like so: (URL: https://api.openai.com/)
services.AddHttpClient("ChatGptAPI", client =>
{
client.DefaultRequestHeaders.Clear();
client.BaseAddress = aiOptions.Url;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + aiOptions.Bearer);
});
Then in my method, I am calling this:
var client = _httpFactory.CreateClient("ChatGptAPI");
var payload = new
{
prompt = $"Create a first person story\n\n{storyText}",
temperature = "0.5",
max_tokens = "1500",
model = "text-davinci-003"
};
var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
var response = await client.PostAsync("v1/completions", content);
Console.WriteLine("ChatGptAPI result:");
Console.WriteLine(response.RequestMessage);
I at first I kept getting Bad Request errors, but once I tried other URLs for the request, it appears to go through, but the response is blank.
For the life of me, I cannot find any samples out there that has C# calling these services.
Any help would be great.
I have tried multiple URLs, I've tried running this in Playground and view code and I've searched for other samples, but this keeps failing or returning nothing. Also tried using the OpenAI Nuget package, that was a waste of time.
If you are actually managing to reach the completions endpoint and you have a valid key then you are just reading the wrong object back.
After you get your response you should read it, something like:
var gptResponse = await response.Content.ReadAsStringAsync();
you can then parse or better deserialize the API response

What is the equivalent of using StringContent (System.Net.Http) to make a post request in Python

I have some C# code that does the following post request:
string postData = newFormUrlEncodedContent(params).ReadAsStringAsync().Result;
var postContent = new StringContent(postData, UTF8Encoding.UTF8, "application/x-www-form-urlencoded");
var responseMessage = httpClient.PostAsync(url, postContent).Result;
I would like to do the equivalent in Python using the Requests library. This is what I have:
headers = {'content-type':'application/x-www-form-urlencoded'}
postContent = requests.post(url, params=params, headers=headers, cookies=previousResponse.cookies)
But postContent.status_code for the Python code is 404, whereas the C# request returns 200. It's possible that there's something wrong with the params since I retrieve those via some Regex matching from a previous request, but that seems to be working.
Edit: I think setting the params parameter is for get requests, not post requests. Also I believe Requests takes care of form encoding:
Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made
So now I have:
postContent = requests.post(url, data = params, cookies = previousResponse.cookies)
Now postContent.status_code == 500. The stack trace says the data is invalid at the root level. I will look into it.

404 error when trying to upload crash to hockeyapp

I'm trying to upload crash manually to HockeyApp using public API. When calling the api link using Postman and uploading crash.log file it works fine but when I try to do the same from C# code I get 404 error.
Here is my code:
string log = ""; //log content
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("*/*"));
var content = new MultipartFormDataContent();
var stringContent = new StringContent(log);
stringContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain");
content.Add(stringContent, "log", "crash.log");
var response = await this.client.PostAsync("https://rink.hockeyapp.net/api/2/apps/[APP_ID]/crashes/upload", content);
}
I was using WireShark to analyse the request that Postman is sending and tried to make mine look exactly the same. The only difference I see is that request from C# code has filename* field in Content-Disposition for the attachment while the one from Postman doesn't:
Content-Disposition: form-data; name="log"; filename="crash.log"; filename*=utf-8''%22crash.log%22
It might be worth mentioning that the code is written in portable library in Xamarin project.
Following #Lukas Spieß sugestion I asked the question on HockeyApp support. Apparently they don't handle quotes in the boundary header. The one thing I missed comparing Postman request and mine.
Here is the solution:
var contentTypeString = content.Headers.ContentType.ToString().Replace("\"", "");
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", contentTypeString);

Google Map Api to Find Only Address Name And Postal Code Of all Shops in City

I am trying to fetch Address Name and Postal Code info of All Shops in specific City.e.g Amsterdam.
I want to do as same done on this website.
https://www.openingstijden.nl/Noord-Holland/Amsterdam/Drukkerijen/
But i am creating a desktop app.
I was trying this Url
https://maps.googleapis.com/maps/api/js?sensor=false&language=nl&key=MY_API_KEY&callback=gmap_draw to fetch but i ain't much deeper in javascript.
If this is correct way of doing this can any one suggest how could i fetch the same results in xml format if not then what is the correct way of fetching the same results as available on this website?
Thanks in Advance
The URL you provided is JS reference for calling the API.
string urlParameters = "";
//Your code goes here
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA");
// Add an Accept header for XML format.
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/xml"); //Keeps returning false
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result;
//Console.WriteLine(response);
if (response.IsSuccessStatusCode)
{
// output xml
string output = response.Content.ReadAsStringAsync().Result;
//response.Content.ReadAsStringAsync();
Console.WriteLine(output);
}
You can edit the URI constructor to include parameters like address/components,key.enter code here
Please refer the documentation for more information.
https://developers.google.com/maps/documentation/geocoding/intro

How do I pull data from a Slack API response with WebClient?

I am making a portal for our team's Slack channel, and I'm wanting to pull a list of all of our current users using the Slack Web API - using the method api/users.list.
The code I am playing around with is:
var response = client.UploadValues("https://slack.com/api/users.list",
"POST", new NameValueCollection()
{
{ "token" ,"mySecretToken"}
});
I get an OK response back, but I'm having trouble actually finding out how to pull the data I want. When I look at the response object all I have is an array of bytes.
What am I missing to actually pull back an object with the user list information?
I needed to encode the response.
Just add this after:
var encoding = new UTF8Encoding();
var responseText = encoding.GetString(response);
I can then use the responseText to pull out the data I need.

Categories