I am attempting to develop a WinUI 3 application to push the files in a folder on my local machine to an existing private GitHub repository. However, I when run the code shown below, nothing gets pushed to GitHub.
public async Task PushFolderToGitHub()
{
string folderPath = "C:\\TestFolder"
string repoOwner = "my_github_username";
string repoName = "my_repo_name";
string token = "my_github_PAT";
var baseAddress = "https://api.github.com";
var client = new HttpClient { BaseAddress = new Uri(baseAddress) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyApp", "1.0"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", token);
var rootFolder = await StorageFolder.GetFolderFromPathAsync(folderPath);
var files = await rootFolder.GetFilesAsync();
foreach (var file in files)
{
var content = new StringContent(System.IO.File.ReadAllText(file.Path), Encoding.UTF8, "text/plain");
var path = $"{rootFolder.Name}/{file.Name}";
var requestUri = $"/repos/{repoOwner}/{repoName}/contents/{path}";
try
{
var response = await client.PutAsync(requestUri, content);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
}
catch (Exception ex)
{
// Log the exception or display an error message
Debug.WriteLine(ex.Message);
return;
}
}
}
I debugged this, and found that the line var response = await client.PutAsync(requestUri, content); returned the following value for "response":
response {StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Cache-Control: no-cache
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 0
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'
Connection: close
Content-Type: text/html; charset=utf-8
}} System.Net.Http.HttpResponseMessage
I have double checked that my username and PAT are correct, so I do not understand why this is happening. If anyone could share any ideas on how I could fix this, then I would greatly appreciate it.
Update: On doing some further research I found that all GitHub API calls must include the User Agent header, so I added the following line of code as shown above: client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyApp", "1.0"));. As a result the value for response is now as follows:
- response {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Server: GitHub.com
Date: Thu, 16 Feb 2023 07:00:12 GMT
X-OAuth-Scopes: admin:enterprise, admin:gpg_key, admin:org, admin:org_hook, admin:public_key, admin:repo_hook, admin:ssh_signing_key, audit_log, codespace, delete:packages, delete_repo, gist, notifications, project, repo, user, workflow, write:discussion, write:packages
X-Accepted-OAuth-Scopes: repo
github-authentication-token-expiration: 2023-03-13 12:19:42 UTC
X-GitHub-Media-Type: github.v3
x-github-api-version-selected: 2022-11-28
X-RateLimit-Limit: 5000
X-RateLimit-Remaining: 4973
X-RateLimit-Reset: 1676532832
X-RateLimit-Used: 27
X-RateLimit-Resource: core
Access-Control-Expose-Headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset
Access-Control-Allow-Origin: *
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Referrer-Policy: origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy: default-src 'none'
Vary: Accept-Encoding, Accept, X-Requested-With
X-GitHub-Request-Id: 1826:0605:C27EE8:D02D1B:63EDD47C
Content-Type: application/json; charset=utf-8
Content-Length: 74
}} System.Net.Http.HttpResponseMessage
I have double checked the repoOwner and repoName variables, so I am unsure why this is returning a 404 error. SO once again, if anyone has any ideas, I would greatly appreciate it.
Related
I'm trying to write a simple console based application with the help from C# to create Salesforce standard objects like Accounts, Contacts, Leads etc. As a starting point I tried to create account using following code but it is always failing with below reason.
Code Snippet -
// Here string requestbody = "{\"name\":\"Testrun Limited\", \"city\":\"Delhi\"}"
public static string SFPostCall2(string requestbody)
{
string responseresult = string.Empty;
using ( var client = new HttpClient())
{
// Headers
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", SalesforceClient.AuthToken);
client.DefaultRequestHeaders.Add("X-PrettyPrint", "1");
// Contents
Uri URL = new Uri("https://mysalesforce-env.salesforce.com/services/data/v55.0/sobjects/account");
var data = new StringContent(requestbody, Encoding.UTF8, "application/json");
var response = client.PostAsync(URL, data).Result;
response.EnsureSuccessStatusCode();
responseresult = response.Content.ReadAsStringAsync().Result;
}
return responseresult;
}
Error Details -
System.Net.Http.HttpRequestException: 'Response status code does not
indicate success: 400 (Bad Request).'
Response Body -
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Wed, 29 Jun 2022 12:08:46 GMT
Set-Cookie: CookieConsentPolicy=0:1; path=/; expires=Thu, 29-Jun-2023 12:08:46 GMT; Max-Age=31536000
Set-Cookie: LSKey-c$CookieConsentPolicy=0:1; path=/; expires=Thu, 29-Jun-2023 12:08:46 GMT; Max-Age=31536000
Set-Cookie: BrowserId=OfVYGvekEeyahU8Wnegiow; domain=.salesforce.com; path=/; expires=Thu, 29-Jun-2023 12:08:46 GMT; Max-Age=31536000
Strict-Transport-Security: max-age=63072000; includeSubDomains
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Robots-Tag: none
Cache-Control: no-store, must-revalidate, no-cache, max-age=0, private
Sforce-Limit-Info: api-usage=16/15000
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
}
}
Please Note :-
I have successfully got the Salesforce Token while using the GET request.
Same request with same parameters in POSTMAN is creating data successfully every time
I have also tried using
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls but still no
help
Same request via JavaScript is also creating data from IE browser { to avoid CORS error }.
I have also tried to change the content to JSON object using following code, but still got same error -
var dataobj = new
{
Name = "Testrun Limited",
City = "Delhi"
};
var jsondataobj = JsonConvert.SerializeObject(dataobj);
HttpContent c_content = new StringContent(jsondataobj, Encoding.UTF8, "application/json");
This style worked for me.
HttpRequestMessage requestUpdate = new HttpRequestMessage(HttpMethod.Post, url);
requestUpdate.Headers.Add("Authorization", "Bearer " + SFAuthToken);
requestUpdate.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
requestUpdate.Content = contentUpdate;
HttpClient client = new HttpClient();
HttpResponseMessage asyncResponse = client.SendAsync(requestUpdate).Result;
var content = asyncResponse.Content.ReadAsStringAsync();
I have an application that requests the marketing cloud for an access token to use in subsequent requests to access the API. This was designed last year and working fine till last week. The same request has been failing since 02/22. Here is the sample code to request the token:
public static async Task<string> GetAuthorizationToken(string ClientId, string ClientSecret)
{
string strAuthorizationToken = string.Empty;
HttpClient client = new HttpClient();
var dictParams = new Dictionary<string, string>()
{
{ "clientId", ClientId }, {"clientSecret", ClientSecret }
};
var content = new FormUrlEncodedContent(dictParams);
var response = await client.PostAsync("https://auth.exacttargetapis.com/v1/requestToken", content);
if (response.IsSuccessStatusCode)
{
var strresponse = await response.Content.ReadAsStringAsync();
//dynamic objResult = JsonConvert.DeserializeObject<dynamic>(strresponse);
//strAuthorizationToken = objResult.accessToken;
}
return strAuthorizationToken;
}
GetAuthorizationToken("*********", "*******").GetAwaiter().GetResult();
Here is the error I am getting from the API:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-Mashery-Responder: 02-26
Vary: Origin
X-Mashery-Message-ID: f4cec199-2e7e-49e2-88e0-6673ffe849ed
strict-transport-security: max-age=15552000; preload
Content-Security-Policy: upgrade-insecure-requests
x-xss-protection: 1; mode=block
x-frame-options: DENY
x-content-type-options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Connection: close
Cache-Control: no-store, must-revalidate, no-cache, max-age=0, private
Date: Tue, 26 Feb 2019 16:42:29 GMT
Server: Apache
Content-Length: 223
Content-Type: application/json; charset=UTF-8
}}
I need to know what has been changed or what I need to fix in this code to be able to access the API again. Please help how I can make this work again.
Thanks in advance.
I am posting the answer as it is resolved and might be helpful for someone else who has a similar issue with sending http requests.
I had to add the following line of code to specify the security protocol to use:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;
OK. So this is really starting to baffle me now. I can get this to work on one UWP app, but not this one.
I have this piece of code to post:
public async Task<string> SubmitDataWithTokenAsync(string url, string token)
{
var httpClient = new HttpClient();
HttpResponseMessage response;
try
{
var root = new
{
fields = new Dictionary<string, string>
{
//General Parameters...
//Inspection Parameters...
//Startup Parameters...
//Mechanical Parameters...
//Electrical Parameters...
//SCR Parameters...
//Shutdown Parameters...
}
};
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
var content = JsonConvert.SerializeObject(root, s);
var request = new HttpRequestMessage(HttpMethod.Post, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
response = await httpClient.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
the content comes back just fine, so it seems....
"{\"fields\":{\"Date\":\"8/16/2018 2:18:48 PM -04:00\",\"Maximo\":null,\"IBX\":\"DC4\",\"Generator\":\"Generator D\",\"AirQuality\":\"Red / Unhealthy\",\"Engineer\":\"Kassim Ganiyou\",\"MT1Level\":null,\"MT2Level\":null,\"StartDTLevel\":null,\"BC1V\":null,\"BC1A\":null,\"BC2V\":null,\"BC2A\":null,\"StartCoolantTEmp\":null,\"StartHours\":null,\"Reason\":null,\"InspectionNotes\":null,\"StartTime\":null,\"CrankV1\":null,\"CrankV2\":null,\"Emissions\":null,\"SCRStartTime\":null,\"OilPressure\":null,\"CoolantTemp\":null,\"BatteryVolt\":null,\"LeftExhTemp\":null,\"RightExhTemp\":null,\"ABVolts\":null,\"BCVolts\":null,\"CAVolts\":null,\"AAmps\":null,\"BAmps\":null,\"CAmps\":null,\"KW\":null,\"Frequency\":null,\"SCROutletTemp\":null,\"NOx\":null,\"UReaFLow\":null,\"Alarms\":null,\"SCRSTopTime\":null,\"StopTime\":null,\"StopHours\":null}}"
The request comes back:
{Method: POST, RequestUri: 'https://graph.microsoft.com/v1.0/sites/root/lists/A07CEC93-XXXX-XXXX-XXXX-0F756D2EF63A/items', Version: 2.0, Content: System.Net.Http.StringContent, Headers:
{
Authorization: Bearer eyJ0eX...PUQ
Content-Type: application/json; charset=utf-8
Content-Length: 603
}}
But then the response is:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
client-request-id: bb26e6fe-4fae-41ae-921d-aeb39063bd8e
Strict-Transport-Security: max-age=31536000
request-id: bb26e6fe-4fae-41ae-921d-aeb39063bd8e
Transfer-Encoding: chunked
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"East US","Slice":"SliceC","Ring":"5","ScaleUnit":"001","Host":"AGSFE_IN_1","ADSiteName":"EUS"}}
Duration: 319.5961
Cache-Control: private
Date: Thu, 16 Aug 2018 20:03:10 GMT
Content-Type: application/json
}}
I have another UWP app going to the same sharepoint site and I get a Status 201 no problem. I am just not seeing where my issue is in this case.
This is why it is good to take a break from a project and come back to it later.
I found out that I had mistyped ONE letter on the SharePoint list. So today when I reviewed the response code it pointed it our to me.
The code WAS good.
Thanks all.
I've cracked how to pull data using the API but now I'm trying to push a new work item to a project and i just can't seem to get it working here's my c# :
try {
using (HttpClient client = new HttpClient()) {
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(
ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", token))));
string Url = $"https://XXX/DefaultCollection/{Job.Project}/_apis/wit/workitems/$Task?api-version=1.0";
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, Url) {
Content = new StringContent(Job.WorkItem, Encoding.UTF8,
"application/json-patch+json")
};
using (HttpResponseMessage response = client.SendAsync(request).Result) {
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
}
}
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
return null;
}
Here is Job.WorkItem as shown up in the debugger
"[
{
\"op\":\"add\",
\"path\":\"/fields/System.Title\",
\"value\":\"Please add a business area for XXX Systems\\n\"
}
]"
Have I missed something or doing something wrong as it responds with
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
X-TFS-ProcessId: xxx
Strict-Transport-Security: max-age=31536000; includeSubDomains
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 3600
Access-Control-Allow-Methods: OPTIONS,GET,POST,PATCH,PUT,DELETE
Access-Control-Expose-Headers: ActivityId,X-TFS-Session,X-MS-ContinuationToken
Access-Control-Allow-Headers: authorization
X-FRAME-OPTIONS: SAMEORIGIN
X-VSS-UserData: xxxx
ActivityId: xxxx
X-TFS-Session: xxx
X-Content-Type-Options: nosniff
Cache-Control: no-cache
Date: Wed, 13 Jul 2016 16:48:28 GMT
P3P: CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOC CNT"
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 429
Content-Type: application/json; charset=utf-8
Expires: -1
}}
I have omitted some details with xxx just FYI
You should refer to REST Api documentation for specific actions.
Also, as you are calling it from .net maybe client lib for VSO Api is a simpler way to go?
There is redundant double quotation marks in the Job.WorkItem which will cause bad request. The content should be:
[
{
\"op\":\"add\",
\"path\":\"/fields/System.Title\",
\"value\":\"Please add a business area for XXX Systems\\n\"
}
]
Refer to this link for details: Create a work item.
I am seeing the following message in attempting to post a json string to a web API (this is what is written to file in the line containing System.IO.File.WriteAllText):
Response: StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Cache-Control: no-cache
Date: Thu, 13 Aug 2015 21:26:12 GMT
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 36
Content-Type: application/json; charset=utf-8
Expires: -1
}
The code within my async posting method is as follows:
Uri theUri = new Uri("http://www.website.com/WebsiteAPI/PostDetails");
HttpClient aClient = new HttpClient();
aClient.BaseAddress = theUri;
aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
aClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "USERNAME", "PASSWORD"))));
aClient.DefaultRequestHeaders.Host = theUri.Host;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, theUri);
request.Content = new StringContent(resource, Encoding.UTF8, "application/json");
// Post the data
aClient.SendAsync(request).ContinueWith(responseTask =>
{
System.IO.File.WriteAllText(PROFILE_JSON_PATH, "Response: " + responseTask.Result);
});
I've tried many different solutions online but nothing seems to work. Any idea why this may not be working?
The short answer is that there is something with your Web API that is erroring. You may or may not have something wrong with your client code--but you'll have to go to the Web API for information that could explain what the problem is.