YouTube API Video Upload Parse Error in C# - c#

I'm trying to upload a video (resumable) to YouTube via the API in C# (not through client).
I'm following these instructions on using resumable upload protocol
However when I make the attempt I get back an Parse Error.
Here is my request:
POST /upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails&key={api_key} HTTP/1.1
Host: www.googleapis.com
X-upload-content-length: 5346742
X-upload-content-type: video/*
Content-type: application/json; charset=UTF-8
Content-length: 277
Authorization: Bearer {access_token}
{
"snippet": {
"title": "My video title",
"description": "This is a description of my video",
"tags": ["cool", "video", "more keywords"],
"categoryId": 22
},
"status": {
"privacyStatus": "public",
"embeddable": True,
"license": "youtube"
}
}
Here is the response:
HTTP/1.1 400 Bad Request
Alternate-protocol: 443:quic
Content-length: 171
Via: HTTP/1.1 GWA
X-google-cache-control: remote-fetch
Server: HTTP Upload Server Built on Sep 30 2013 10:58:35 (1380563915)
Date: Wed, 02 Oct 2013 21:38:10 GMT
Content-type: application/json
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
Anyone have any ideas?

The parse error is due to True being written with a big T.
(using the beta library is not an option for me becuase of Unity. .NET 2.0..)

why dont u use Google GData Youtube Api for .NET ?
string developerkey = "developerKey";
YouTubeRequestSettings settings = new YouTubeRequestSettings("Somethinghere", developerkey, "googleUserName", "googlePassWord");
YouTubeRequest request = new YouTubeRequest(settings);
newVideo.Title = "Video Title Here || ArgeKumandan";
newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "cars, funny";
newVideo.Description = "My description";
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag", YouTubeNameTable.DeveloperTagSchema));
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(#"D:\video ArgeKumandan.flv", "video/flv");
createdVideo = request.Upload(newVideo);

Related

How do I convert a string into an HTTP Response in C#?

{
"AdditionalProcessCardSwipeResponseData": null,
"CustomerTransactionID": "",
"ProcessCardSwipeOutputs": [
{
"AdditionalProcessCardSwipeResponseData": null,
"CardSwipeOutput": {
"AdditionalOutputData": [
{
"key": "CardType",
"value": "VISA"
}
],
"CardID": "abcdefghijk",
"IsReplay": false,
"MagnePrintScore": 0.12345,
"PanLast4": "1234"
},
"CustomerTransactionID": "",
"DecryptForwardFaultException": null,
"MagTranID": "2c3b08e9-b628-4f3c-a8ad-1ac1d57c1698",
"PayloadResponse": "HTTP\/1.1 200 OKPragma: no-cache\u000aX-OPNET-Transaction-Trace: a2_8bfb4474-c9fb-4257-b914-8411770544e4-22192-26834262\u000aAccess-Control-Allow-Credentials: true\u000aAccess-Control-Allow-Headers: x-requested-with,cache-control,content-type,origin,method,SOAPAction\u000aAccess-Control-Allow-Methods: PUT,OPTIONS,POST,GET\u000aAccess-Control-Allow-Origin: *\u000aStrict-Transport-Security: max-age=31536000\u000aX-Cnection: close\u000aContent-Length: 328\u000aCache-Control: no-store\u000aContent-Type: application\/json; charset=utf-8\u000aDate: Thu, 26 Dec 2019 16:05:35 GMT\u000a\u000a&{\"messages\":{\"resultCode\":\"Error\",\"message\":[{\"code\":\"E00003\",\"text\":\"The 'AnetApi\/xml\/v1\/schema\/AnetApiSchema.xsd:customerProfileId' element is invalid - The value 'customer_profile_id' is invalid according to its datatype 'AnetApi\/xml\/v1\/schema\/AnetApiSchema.xsd:numericString' - The Pattern constraint failed.\"}]}}",
"PayloadToken": "ADFASDFASDFASDFASDFASFADSFF",
"TransactionUTCTimestamp": "2019-12-26 16:05:35Z"
}
]
}
How do I convert the string returned for "PayloadResponse" to a HTTPResponse? I've tried the following but am not able to retrieve the body of the response:
var response = JObject.Parse(await httpResponseMessage.Content.ReadAsStringAsync());
var payloadResponse = response["ProcessCardSwipeOutputs"][0]["PayloadResponse"];
var msg = new HttpResponseMessage
{
Content = new StringContent(payloadResponse.ToString(), Encoding.UTF8, "application/json")
};
This is the content of the PayloadResponse I want to convert to an HttpResponse so that I can parse out the response body in a clean way:
HTTP/1.1 200 OKPragma: no-cache
X-OPNET-Transaction-Trace: a2_cadac737-0b60-45f5-9d5a-4d540c0975a0-7760-47076038
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-requested-with,cache-control,content-type,origin,method,SOAPAction
Access-Control-Allow-Methods: PUT,OPTIONS,POST,GET
Access-Control-Allow-Origin: *
Strict-Transport-Security: max-age=31536000
X-Cnection: close
Content-Length: 530
Cache-Control: no-store
Content-Type: application/json; charset=utf-8
Date: Thu,
26 Dec 2019 21: 46: 56 GMT
&{
"customerProfileId": "45345345345",
"customerPaymentProfileId": "123123123",
"validationDirectResponse": "1,1,1,(TESTMODE) This transaction has been approved.,000000,P,0,none,Test transaction for ValidateCustomerPaymentProfile.,1.00,CC,auth_only,none,John,Doe,,2020 Vision St,Somewhere,CA,90028,USA,,,email#example.com,,,,,,,,,0.00,0.00,0.00,FALSE,none,,,,,,,,,,,,,,XXXX1234,Visa,,,,,,,,,,,,,,,,,",
"messages": {
"resultCode": "Error",
"message": [
{
"code": "E00039",
"text": "A duplicate customer payment profile already exists."
}
]
}
}
If I understand correctly you just want to "parse out the response body in a clean way".
You are trying to convert this to an HttpResponseMessage because you think that will line everything up for you. This is a distraction, it makes it sound like you want to create a response and forward it on, but all you really want is the payload to be parsed into a usable format.
Correct me if I'm wrong.
To parse out that payload you can split that string on the newline character (/u000a), remove the extraneous & and parse the json.
var splitResponse = payloadResponse.ToString().Split(new char[] { '\u000a' });
string body = splitResponse.Last().Substring(1);
JObject job = JObject.Parse(body);
// example
Console.WriteLine(job["messages"]["message"][0]["text"]);
I did not provide classes that you can deserialize this json into because it is an error message and I assume you won't always be dealing with an error. A success response would probably be a different schema. I can't know how to design classes for this from the information you have provided but maybe working with the JObject is adequate.

Web api error 500 starting from usermanager

First of all, I would like to apologize for my really bad english, if something is not understandable, then reask please.
When I try POST with /api/account/regapi in Swagger then with too short password it gives error 200, but with correct length it gives error 500, while debugging it shows correct parameters at AuthDTO model, but still shows error 500 with correct data.
Response header returned by false data(incorrect password length):
{
"$id": "1",
"succeeded": false,
"errors": [
{
"$id": "2",
"code": "PasswordTooShort",
"description": "Passwords must be at least 6 characters."
}
]
}
Response header with incorrect password
access-control-allow-origin: *
content-type: application/json; charset=utf-8
date: Sat, 26 May 2018 13:54:06 GMT
server: Kestrel
transfer-encoding: chunked
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?RDpcS29vbGkgQXNqYWRcVlIyXFZSMlByb2pla3RTb2x1dGlvblxWUjJQcm9qZWt0XGFwaVxBY2NvdW50XFJlZ0FwaQ==?=
Response header with correct data:
content-type: text/html; charset=utf-8
date: Sat, 26 May 2018 14:03:59 GMT
server: Kestrel
transfer-encoding: chunked
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?RDpcS29vbGkgQXNqYWRcVlIyXFZSMlByb2pla3RTb2x1dGlvblxWUjJQcm9qZWt0XGFwaVxBY2NvdW50XFJlZ0FwaQ==?=
Registration in AccountController
public async Task<IActionResult> RegApi(AuthDTO model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
return Ok(result);
}
return BadRequest();
}
public class AuthDTO
{
public string Email { get; set; }
public string Password { get; set; }
}
I think the is problem is in _usermanager, because error 500 is starting to show up there

Making HttpWebRequest with "If-None-Match" Header (Etag)

I am trying do download data from web with normall httpwebrequest (work on most url), but server send me unexpected response, like this
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 10 Aug 2017 03:59:39 GMT
Content-Type: application/json
Content-Length: 1984
Connection: keep-alive
Access-Control-Allow-Headers: Content-Type,Authorization,X-Requested-With,X-CSRFToken,If-None-Match-,X-API-SOURCE
Vary: Accept-Encoding, Cookie
ETag: "6f15f338d170c7f833c491beb546e4a9;gzip"
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Set-Cookie: SPC_SI=ycl079eb0umjw270xoybjhok3hz6hp7x; expires=Fri, 11-Aug-2017 03:59:39 GMT; httponly; Max-Age=86400; Path=/
{
"itemid": 62790979,
"liked": false,
"offer_count": 0,
"videos": [],
"rating_star": 5.187136305269734,
"image": "6ebb860db6?????????????????????",
"image_list": ["6ebb860db6?????????????????????"],
"is_adult": null,
"can_use_wholesale": false,
"currency": "IDR",
"rcount_with_context": 6,
"show_free_shipping": 1,
"estimated_days": 3,
"show_discount": 0,
"price_before_discount": 0,
"cmt_count": 16,
"is_shopee_verified": false,
"catid": 202,
"is_official_shop": false,
"price_min": null,
"rating_count": [10, 0, 0, 2, 3, 5],
"liked_count": 13,
"version": "6f15f338d170c7f833c491beb546e4a9",
"coin_earn_items": [],
"price_min_before_discount": 0,
"cb_option": 0,
"price": null,
"hashtag_list": [
"#editin??????????????",
"#soft??????????",
"#sof?????????",
"#pal????????",
"#pal????????",
"#co??????",
"#co???????",
"#prog??????????",
"#juals????????????",
"#ins????????",
"#fl??????",
"#??",
"#pal????????",
"#u????"
],
"price_max": null,
"description": "Corel Draw Video X9 32 & 64 Bit\n2. Ulead VideoStudio v11 Plus\n3. Ulead VideoStudio v11 Plus\n4. Sony Ve?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"
,
"flash_sale": null,
"models": [],
"brand": "",
"rcount_with_image": 1,
"shopid": 3732962,
"discount": null,
"has_lowest_price_guarantee": false,
"sold": 4,
"price_max_before_discount": 0,
"sub_catid": 443,
"condition": 1,
"name": "Packet????????????????????????",
"wholesale_tier_list": [],
"item_status": "no????",
"third_catid": 6910,
"is_pre_order": false,
"coin_spend_cash_unit": null,
"attributes": [],
"stock": 118
}
as you can see, some fields is combined with annoying "?"
I check standar browser request using Fidler, the only thing different from my request is browser send "If-None-Match-" header to the server.
question is how to fill that header, because I tried sent etag header from previous request but i still get response with "?" characters.
Hope you understand my poor language.
this is my code.
HttpWebRequest Web;
HttpWebResponse Resp;
StreamReader Reader;
Web =
(HttpWebRequest)WebRequest.Create(""https://shopee.co.id/api/v1/item_detail/?item_id=262740376&shop_id=13072340");
Web.CookieContainer = New CookieContainer();
Web.Method = "GET";
Web.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240";
Web.KeepAlive = true;
Web.Accept = "application/json";
Web.ContentType = "application/json; Charset=UTF-8";
Web.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);
Web.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
Web.Headers.Add("x-requested-with", "XMLHttpRequest");
Web.Headers.Add("x-api-source", "pc");
Resp = (HttpWebResponse)Web.GetResponse();
Reader = new StreamReader(Resp.GetResponseStream());
string Res = Reader.ReadToEnd();
this code work for first 5/6 request.
after that, server will send annoying "?" like above..

C# HttpClient PostAsJsonAsync -> Error reading string

Hi I try to call an web api by server side with:
using (var client = new HttpClient())
{
using (var rsp = client.PostAsJsonAsync<Request>(url, model).Result)
{
if (!rsp.IsSuccessStatusCode)
{
// throw an appropriate exception
}
var result = rsp.Content.ReadAsAsync<string>().Result;
}
}
but I get error
Error reading string. Unexpected token: StartObject. Path '', line 1, position 1.
If I try to call same url from jQuery
$.post('http://localhost/api/Test')
the server return
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 25 Oct 2015 12:15:56 GMT
Content-Length: 104
{
"Header": {
"Token": "Response",
"Timestamp": "2015-10-25T14:15:56.0092197+02:00"
}
}
The "model" arrive on api controller but I can't get response from request.
ReadAsAsync<T> attempts to deserialize the response to type T. In this case, you're saying you want to deserialize JSON to a string, which doesn't really make sense. Either use a type matching the response (i.e. a custom data structure containing Header, Token, etc.) or use ReadAsStringAsync() if you really want to get a string.

How to use google domains apis in .Net Applications

I'm trying to get person data using following .net(installed application) code. but it gives me error forbidden
UserCredential credential;
using (var stream = new FileStream("path to the secrets json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] {
PlusDomainsService.Scope.PlusCirclesRead,
PlusDomainsService.Scope.PlusCirclesWrite,
PlusDomainsService.Scope.PlusLogin,
PlusDomainsService.Scope.PlusMe,
PlusDomainsService.Scope.PlusMediaUpload,
PlusDomainsService.Scope.PlusProfilesRead,
PlusDomainsService.Scope.PlusStreamRead,
PlusDomainsService.Scope.PlusStreamWrite,
PlusDomainsService.Scope.UserinfoEmail,
PlusDomainsService.Scope.UserinfoProfile
},
"user", CancellationToken.None, new FileDataStore("Domains.SampleApi"));
}
var service = new PlusDomainsService(new BaseClientService.Initializer
{
ApplicationName = "API Sample",
HttpClientInitializer = credential
});
var me = await service.People.Get("me").ExecuteAsync();<-- this line gives error
I cannot even run the sample code here
https://developers.google.com/+/domains/api/people/get#try-it
it gives me following error
Cache-Control: private, max-age=0
Content-Type: application/json; charset=UTF-8
Date: Thu, 25 Sep 2014 14:24:56 GMT
Expires: Thu, 25 Sep 2014 14:24:56 GMT
Server: GSE
Transfer-Encoding: chunked
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
Note: I tried using website and installed application but both giving me same error.

Categories

Resources