Using Google Blogger API v3 with C# - c#

I've been using the Google Blogger API v2 for a long time, using GDATA to authenticate and post new posts. However, this is not supported now anymore and they are requiring an OAuth authentication.
Unfortunately I cannot find any .Net documentation I fully understand.
I followed them as best as I could, and I don't see any errors, so I do not know what else to try, please help me.
My first approach was to go like this: Google.GData.Client.GDataRequestException - Authentication suddenly fails in old code
Here an example for Google Spread Sheets is given. However, I do not know with what to replace the line "var service = new SpreadsheetsService(null)", since I do not know if there is a Blogger service.
In the second approach I first got an OAuth2 token like before and then followed the description from https://developers.google.com/blogger/docs/3.0/using?hl=de about publishing posts. So I created a WebRequest as follows:
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
http.Headers.Add("Authorization", "Bearer " + token);
var vm = new { kind = "blogger#post", blog = new { id = "id" }, title = "Testtitle", content = "testcontent" };
var dataString = JsonConvert.SerializeObject(vm);
string parsedContent = dataString;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
But here, I got 403 (not allowed). Why?
Thanks in advance!
Best, Oliver

Related

OneLogin Create Session Login Token API returns status 400 with message: Bad Request

I am developing a C# application which needs to use the onelogin API to retrieve a session token. I am able to authenticate and and create a token with the following code:
WebRequest Authrequest = WebRequest.Create("https://api.us.onelogin.com/auth/oauth2/token");
Authrequest.Method = "POST";
Authrequest.ContentType = "application/json";
Authrequest.Headers.Add("cache-control", "no-cache");
Authrequest.Headers.Add("Authorization: client_id:XXXXXXX7bbf2c50200d8175206f664dc28ffd3ec66eef0bfedb68c3366420dc, client_secret:XXXXXXXXXX6ba2802187feb23f6450c6812b8e6639361d24aa83f12010f ");
using (var streamWriter = new StreamWriter(Authrequest.GetRequestStream()))
{
string Authjson = new JavaScriptSerializer().Serialize(new
{
grant_type = "client_credentials"
});
streamWriter.Write(Authjson);
}
WebResponse AuthReponse;
AuthReponse = Authrequest.GetResponse();
Stream receiveStream = AuthReponse.GetResponseStream ();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream);
JObject incdata = JObject.Parse(readStream.ReadToEnd());
string sToken = incdata["data"][0]["access_token"].Value<string>();
AuthReponse.Close();
However, when running the Create Session Login Token with the following code, it only returns a 400 error, and the message has no detail. Just Bad Request:
//Get the session token for the specified user, using the token recieved from previous web request
WebRequest request = WebRequest.Create("https://api.us.onelogin.com/api/1/login/auth");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("authorization", "bearer:" + sToken);
using (var streamWriter2 = new StreamWriter(request.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(new
{
username_or_email = sUsername,
password = sPassword,
subdomain = "comp-alt-dev"
});
streamWriter2.Write(json);
}
WebResponse response;
response = request.GetResponse();
string streamText = "";
var responseStream = response.GetResponseStream();
using (responseStream)
{
var streamReader = new StreamReader(responseStream);
using (streamReader)
{
streamText = streamReader.ReadToEnd();
streamReader.Close();
//
}
responseStream.Close();
}
Any ideas?
-Thank you
Also for anyone who may be getting this error. in C# the email is case sensitive. I tried User.email.com. In onelogin it was saved as user#email.com. changing the c# to lower case fixed it.
Can you let us know what payload you're sending across the wire to the .../1/login/auth endpoint as well as the response (either as others have suggested as packet snoop, or just as a debug output from the code)
400 means either bad json or the endpoint requires MFA, so this will narrow it down.
~thanks!
Just joining the troubleshooting effort =) -- I can replicate a 400 Bad Request status code with a "bad request" message when the request body contains a username_or_email and/or subdomain value that does not exist, or if the request body is empty.
Can you post what goes over the wire to the OneLogin endpoint...
OK Thanks. So it appears your subdomain does not exist. If you give me an email in the account I can find the correct subdomain value for you.

Get Response from HttpWebRequest on Windows Phone 8

I'm trying to do a WebRequest to a site from a Windows Phone Application.
But is vry important for me to also get the response from the server.
Here is my code:
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Ahri</string>";
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await stream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
Unfortunatelly, I have no idea of how I could get the response from the server.
Does anyone have an idea?
Thanks in advance.
Thanks to #max I found the solution and wanted to share it above.
Here is how my code looks like:
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Claor</string>";
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
string responseFromServer = "no response";
HttpWebRequest httpWebRequest = HttpWebRequest.Create(requestUri) as HttpWebRequest;
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (Stream requestStream = await httpWebRequest.GetRequestStreamAsync())
{
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await requestStream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
WebResponse webResponse = await httpWebRequest.GetResponseAsync();
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
}
I hope it will help someone in the future.
This is very common question for people new in windows phone app
development. There are several sites which gives tutorials for the
same but I would want to give small answer here.
In windows phone 8 xaml/runtime you can do it by using HttpWebRequest or a WebClient.
Basically WebClient is a wraper around HttpWebRequest.
If you have a small request to make then user HttpWebRequest. It goes like this
HttpWebRequest request = HttpWebRequest.Create(requestURI) as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
string responseContent = reader.ReadToEnd();
// Do anything with you content. Convert it to xml, json or anything.
}
Although this is a get request and i see that you want to do a post request, you have to modify a few steps to achieve that.
Visit this place for post request.
If you want windows phone tutorials, you can go here. He writes awesome tuts.

Send Message using a WebRequest and Twilio

I'm need to send a message using Twilio services and the NetDuino.
I know there is an API that allows to send messages but it uses Rest-Sharp behind the scene which is not compatible with the micro-framework. I have try to do something like the below but I got a 401 error (not authorized). I got this code form here (which is exactly what I need to do)
var MessageApiString = "https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/SMS/Messages.json";
var request = WebRequest.Create(MessageApiString + "?From=+442033*****3&To=+447*****732&Body=test");
var user = "AC4*************0ab05bf";
var pass = "0*************b";
request.Method = "POST";
request.Credentials = new NetworkCredential(user, pass);
var result = request.GetResponse();
Twilio evangelist here.
From the code above it does not look like you are replacing the {AccountSid} token in the MessageApiString variable with your actual Account Sid.
Also, it looks like you are appending the phone number parameters to the URL as querystring values. Because this is a POST request I believe you need to include these as the request body, not in the querystring, which means you also need to set the ContentType property.
Here is an example:
var accountSid = "AC4*************0ab05bf";
var authToken = "0*************b";
var MessageApiString = string.Format("https://api.twilio.com/2010-04-01/Accounts/{0}/SMS/Messages.json", accountSid);
var request = WebRequest.Create(MessageApiString);
request.Method = "POST";
request.Credentials = new NetworkCredential(accountSid, authToken);
request.ContentType = "application/x-www-form-urlencoded";
var body = "From=+442033*****3&To=+447*****732&Body=test";
var data = System.Text.ASCIIEncoding.Default.GetBytes(body);
using (Stream s = request.GetRequestStream())
{
s.Write(data, 0, data.Length);
}
var result = request.GetResponse();
Hope that helps.

Vimeo uploading. Cannot get complete_uri field in response

I've been fiddling quite a bit with my uploading to vimeo.
I've made a ticket request.
I've uploaded the file.
I've checked the file if its uploaded.
I need to run the method DELETE with the complete_uri response i should get from my ticket.
However, im not receiving any complete_URI from the ticket response.
Here is my code:
public static dynamic GenerateTicket()
{
const string apiUrl = "https://api.vimeo.com/me/videos?type=streaming";
var req = (HttpWebRequest)WebRequest.Create(apiUrl);
req.Accept = "application/vnd.vimeo.*+json;version=3.0";
req.Headers.Add(HttpRequestHeader.Authorization, "bearer " + AccessToken);
req.Method = "POST";
var res = (HttpWebResponse)req.GetResponse();
var dataStream = res.GetResponseStream();
var reader = new StreamReader(dataStream);
var result = Json.Decode(reader.ReadToEnd());
return result;
}
This response gives me:
form
ticket_id
upload_link
upload_link_secure
uri
user
In order to finish my upload i need to run step 4 in this guide: https://developer.vimeo.com/api/upload
Sending parameter type=streaming as body:
ASCIIEncoding encoding = new ASCIIEncoding();
string stringData = "type=streaming"; //place body here
byte[] data = encoding.GetBytes(stringData);
req.Method = "PUT";
req.ContentLength = data.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
At the moment, type=streaming must be sent in the body of the request, not as a url parameter.
This will probably change to allow either option.
the important point is :
"The first thing you need to do is request upload access for your application. You can do so from your My Apps page."
If you get all values without complete_uri, it means: you dont have an upload access token. So go to your apps and make an upload request

The remote server returned an error: (403) Forbidden. during post request...?

I try to make small application for myself and I found this application
How to upload video on Dailymotion with c# ?? Is somebody has a complete code?
When I tried every thing but publishing is not working. I used fiddler but I cant find the error.
Here is the code
var request = WebRequest.Create("https://api.dailymotion.com/me/videos?url=" + Uri.EscapeUriString(uploadResponse.url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "OAuth " + accessToken);
var requestBytes = Encoding.UTF8.GetBytes("title=test 123&channel=Funny&tags=Humor&description=Testing testing&published=true");
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
When it reaches request.GetResponse() it gives the error. So what is the problem here..?
I believe you need to get rid of the "me" in the url as you're using OAuth instead of basic authentication, like this:
"https://api.dailymotion.com/videos?url="
Instead of:
"https://api.dailymotion.com/me/videos?url="
At least in a quick scan that looks like it's it, I wrote an auto-publisher for a client a year ago and it didn't use the me in the url. My credentials are invalid now, so can't test it unfortunately. It seems to be a bug in the answer you linked.
If you can read other languages, I found it helpful just going through their SDKs and converting the code:
http://www.dailymotion.com/doc/api/sdk-php.html
https://github.com/dailymotion/dailymotion-sdk-php/blob/master/Dailymotion.php

Categories

Resources