Share on LinkedIn using Restsharp - linkedin

I'm having difficculty getting a share working on linkedin using restsharp. Here's my code:
var shareMsg = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new
{
title = "Test post to LinkedIn",
submitted_url = "http://www.somewebsite.com",
submitted_image_url = "http://www.somewebsite.com/image.png"
},
visibility = new
{
code = "anyone"
}
};
RestClient rc = new RestClient(LinkedInAppInfo.LinkedInBaseApiUrl);
RestRequest request = new RestRequest(LinkedInAppInfo.SharePostPath, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("format", "json");
request.AddBody(shareMsg);
request.AddParameter("oauth2_access_token", accessToken, ParameterType.GetOrPost);
RestResponse restResponse = (RestResponse)rc.Execute(request);
ResponseStatus responseStatus = restResponse.ResponseStatus;
The result i'm getting is:
{
"errorCode": 0,
"message": "Couldn't parse share document: error: Unexpected end of file after null",
"requestId": "06ZU78FUNW",
"status": 400,
"timestamp": 1363551953855
}
Any thoughts on what I am doing wrong?

Related

Swagger OAuth, how to send bearer token in a different header than "Authorization"

I have an API with authorization code flow authentication and I have configured swagger to use that as a security definition and it works fine.
Now I need swagger to send the bearer token in a different header as well, besides "Authorization", e.g. "X-Forwarded-Authorization". Is there a way to do that?
My current security configuration:
setup.AddSecurityDefinition(
"oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("..."),
TokenUrl = new Uri("..."),
Scopes = { }
}
},
});
You can configure swagger when adding service collection like this;
services.AddSwaggerGen(options =>
{
//...other configurations
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field!",
Name = "X-Forwarded-Authorization",
Type = SecuritySchemeType.ApiKey
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}, Array.Empty<string>()
}
});
//...other configurations
});

Error while using FIREBASE STORAGE in flutter using HTTP REST api

I am getting the error while inserting image file into the firebase Stroage. I am using HTTP rest api's for the same.
The code is as follows:
Future<void> upload(Image image2) async {
var accountCredentials = ServiceAccountCredentials.fromJson({
"private_key_id": " ",
"private_key": " ",
"client_email":"< >.iam.gserviceaccount.com",
"client_id": "",
"type": "service_account"
});
var scopes = [
'https://www.googleapis.com/auth/cloud-platform',
];
var client = Client();
AccessCredentials credentials =
await obtainAccessCredentialsViaServiceAccount(accountCredentials, scopes, client);
String accessToken = credentials.accessToken.data;
var request = Request(
'POST',
Uri.parse(
'https://www.googleapis.com/upload/storage/v1/b/mybucket/o?uploadType=media&name=$image2'),
);
request.headers['Authorization'] = "Bearer $accessToken";
request.headers['Content-Type'] = "image/png";
Response response = await Response.fromStream(await request.send());
print("response is ");
print(response.statusCode);
print("response body");
print(response.body);
client.close();
}
The Error is as follows:
{
"error": {
"code": 403,
"message": "< >.iam.gserviceaccount.com does not have storage.objects.create access
to the Google Cloud Storage object.",
"errors": [
{
"message": "< >.gserviceaccount.com does not have storage.objects.create access to the
Google Cloud Storage object.",
"domain": "global",
"reason": "forbidden"
}
]
}
}
I have given the permission of storage.objects.create through IAM service management but this is not working
Click here to view ScreenShot of assigned permission

Common generic class to handle server response in flutter

I'm calling requesting server for data and getting following response.
{
"success": 1,
"data": [
{
"id": 1,
"name": "Kurti"
},
{
"id": 2,
"name": "Top"
}
],
"message": "Data fetched"
}
Modal class to convert json data coming from server.
class Product {
String categoryName;
int productId;
Product.fromJson(Map<String, dynamic> json) {
categoryName = json["id"];
productId = json["name"];
}
}
So from the server the format will be fix for every call like below...
{
"success": <Int>,
"message": <String>,
"data": <An array of Model class>
}
For that I've created below class...
class ServerResponse<T> {
String message;
int success;
List<T> data;
ServerResponse.fromJson(Map<String, dynamic> json) {
message = json["message"];
success = json["success"];
data = json["product_data"];
}
}
And this is how I'm calling api...
class ServerManager {
final baseUrl = isProduction ? liveServer : stagingServer;
var headers = {"consumer-key": "sdfgdqwrtw34563t545"};
dynamic callWSToGetData({Map<String, String> params}) async {
var client = http.Client();
var url = baseUrl + allProducts;
print("URL = $url");
print("params: $params");
print("header: $headers");
var response = await client.post(url, headers: headers, body: params);
var json = converter.jsonDecode(response.body);
return json;
}
}
Calling api to get data as following.
Map<String, String> params = {"categories_id": "1", "language_id": "1", "type": "Newest", "customers_id": "0", "page_number": "0"};
var response = ServerManager().callWSToGetData(params: params);
var res = ServerResponse<Product>.fromJson(response);
print(res.data);
So when I ran this code I'm getting following error.
type 'Future' is not a subtype of type 'Map'
The question is...
How can I create a single generic class that can be used to handle server responses?
Any help please.
type 'Future' is not a subtype of type 'Map'
This is probably due to missing await call. Your callWSToGetData has async in declaration so it's type will be Future.
To use generics you need to pass the type. So your code will look like this:
var response = await ServerManager().callWSToGetData(); //how can I use generic here
var res = ServerResponse<Product>.fromJson(response);
print(res.data);

How to send a POST request to Firebase Cloud Messaging API in Vapor

I am trying to make a POST request to a Firebase Notifications API using Vapor 1.5 and Firebase Legacy Protocol, but I get failure response.
response is JSON(node: Node.Node.object(["multicast_id":
Node.Node.number(5936281277445399934), "failure": Node.Node.number(0),
"canonical_ids": Node.Node.number(0), "results":
Node.Node.array([Node.Node.object(["message_id":
Node.Node.string("0:1527074314969790%c7ade8b9f9fd7ecd")])]),
"success": Node.Node.number(1)]))
EDIT
Making the request through POSTMan fails with error "The request was missing an Authentication Key (FCM Token)."
class FirebaseRequester {
let fcmLegacyServerKey = "AIzaSyDSuXXXXXXkCafTQay5_r8j3snvVos"
func sendNotification(payLoad: JSON) throws -> Response {
var response: Response?
do {
let responseFCM = try drop.client.post("https://fcm.googleapis.com/fcm/send",
headers: ["Content-Type":"application/json","Authorization": "key\(fcmLegacyServerKey)"],
query: [:],
body: payLoad.makeBody())
response = responseFCM
}catch let error {
let message = error.localizedDescription
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
guard let rsp = response?.json else {
let message = "no json received on line \(#line)"
drop.log.error(message)
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
print("rsp in json format is \(rsp)")
return response!
}//end of sendNotification()
}//end of class FirebaseRequester
//make another class here and initialize it with FirebaseRequester
//get data from Client App
// validate data
// finally, create the payLoad and call sendNotification(:)
//request should look like
{
"aps": {
"alert": "Breaking News!",
"sound": "default",
"link_url": "https://raywenderlich.com"
}
}
let fcmKeyToSendTo = "someDeviceTokenKeyReceivedFromClient_biHZNI-e9E53WEkCzrki"
let data = try Node(node: ["alert": "alert", "sound": "sound", "link_url": "https://www.someWebsite.com"])
var payLoadObj = try JSON(node: ["aps" : data])
payLoadObj["to"] = try JSON(node: fcmKeyToSendTo)
do {
let _ = try firebaseRequester.sendNotification(payLoad: payLoadObj)
}catch{
logErr.prints(message: error.localizedDescription)
}
let message = "notification Sent"
return try JSON(node:["success":message])
In sendNotification(payload:) I had a typo, I missed = after key. It should have been "key=\(fcmLegacyServerKey)"
In sendNotification(payload:), payLoad.makeBody should not be called, I should have just passed the JSON object payLoad as an argument to the .post request.
The JSON object of the notification was clearly badly formatted from the outset. The message type I wanted to send was notification, but I was passing in a key named aps. I should have passed key notification as shown below.
.
class FirebaseRequester {
let fcmLegacyServerKey = "AIzaSy....vVos"
func sendNotification(payLoad: JSON) throws -> Response {
var response: Response?
do {
let responseFCM = try drop.client.post("https://fcm.googleapis.com/fcm/send",
headers: ["Content-Type":"application/json","Authorization": "key=\(fcmLegacyServerKey)"],
query: [:],
body: payLoad
response = responseFCM
}catch let error {
let message = error.localizedDescription
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
guard let rsp = response?.json else {
let message = "no json received on line \(#line)"
drop.log.error(message)
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
return response!
}//end of sendNotification()
}//end of class FirebaseRequester
class TestRouteNow {
let firebaseRequester: FirebaseRequester
init(firebaseRequester: FirebaseRequester) {
self.firebaseRequester = firebaseRequester
}
func addRoutes(drop: Droplet) {
drop.post("test", "notif", handler: postNotification)
}
func postNotification(request: Request) throws -> ResponseRepresentable {
let fcmDevice = "someDeviceTokenReceivedFromClientApp"
let data = try Node(node: ["title": "title","body": "body", "sound": "default", "badge":"60"])
var payLoadObj = try JSON(node: ["notification": data])
payLoadObj["to"] = try JSON(node: fcmDevice)
do {
let _ = try firebaseRequester.sendNotification(payLoad: payLoadObj)
}catch{
logErr.prints(message: error.localizedDescription)
}
let message = "notification Sent"
return try JSON(node:["success":message])
}
}//end of class
// request body
{
"to" : "cQDtm_someDeviceTokenReceivedFromClient",
"priority":"high",
"notification": {
"title":"Booking Rescheduled",
"body": "Cancelled Booking 7830593, for Mon, 12 March",
"sound":"default",
"badge": "100"
}
}

Calendar API v3 reminder in event is always default

I am developing calendar api client and I have problem with reminder - they do not work...
I create event like this:
Event gEvent = new Event()
{
Summary = "Reminder test",
Location = "Reminder test",
Start = new EventDateTime()
{
DateTime = new DateTime(2014, 12, 14, 21, 0, 0),
},
End = new EventDateTime()
{
DateTime = new DateTime(2014, 12, 14, 22, 0, 0),
},
Reminders = new Event.RemindersData()
{
UseDefault = false,
Overrides = new List<EventReminder>()
{
new EventReminder()
{
Method = "email",
Minutes = 15
},
new EventReminder()
{
Method = "email",
Minutes = 30
},
new EventReminder()
{
Method = "email",
Minutes = 45
},
}
}
};
Event simpleEvent = calService.Events.Insert(gEvent, strCalendarID).Execute();
This code works and in my google calendar GUI is really created my event, but if I click on editing event - I can not see my reminders, there are only default reminders.
Why? What I am doing wrong?
Thanks for all answers
Today I attempted send request from code with JSON. My method look like this:
private static void CreateSimpleEvent(string strAccessToken, string strCalendarID, string strApiKey)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("https://www.googleapis.com/calendar/v3/calendars/{0}/events?sendNotifications=false&fields=reminders&key={1}", strCalendarID, strApiKey));
request.Method = "POST";
request.ContentType = "application/json";
request.UserAgent = "TestCalendarApi2";
request.Headers.Add("Authorization", "Bearer " + strAccessToken);
string strJson = #"{
'end': {
'dateTime': '2014-12-19T15:30:00.000Z',
'timeZone': 'Europe/Prague'
},
'start': {
'dateTime': '2014-12-19T14:30:00.000Z',
'timeZone': 'Europe/Prague'
},
'reminders': {
'useDefault': false,
'overrides': [
{
'method': 'email',
'minutes': 13
}
]
}
}";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(strJson);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
Method proceeded OK and in google calendar was created event, but reminders are still missing when I use AccessToken from ServiceAccountCredential object :(. When I use AccessToken generated in Apis explorer (https://developers.google.com/apis-explorer/#p/calendar/v3/) - reminders are working.
Problem is, that in Apis explorer I must turn on OAuth2 and after that I must grand acess...
Is there any way, how to grand access from code?
Thanks for all answers.
The problem with reminders while using a service account to manage events in Google Calendar is that the service account is practically a virtual user with its own Google Calendar. The event reminders are set per user, so you would be only able to see the reminders if you'd manage to log in to Google Calendar as your service account. The users who share the calendar with the service account only see the event details but they have to set their own reminders.
Same issue here, event inserted without any reminders.
Sending same request via API explorer successfully inserted event with reminders.
My JSON data:
{
"end":{
"dateTime":"2015-01-19T01:20:00.000",
"timeZone":"Europe\/Minsk"
},
"reminders":{
"useDefault":false,
"overrides":[
{
"method":"sms",
"minutes":"30"
},
{
"method":"email",
"minutes":"60"
}
]
},
"start":{
"dateTime":"2015-01-19T01:15:00.000",
"timeZone":"Europe\/Minsk"
},
"summary":"New event",
"start_date":"2015-01-19 01:15",
"end_date":"2015-01-19 01:20"
}

Resources