Follow Company issue (LinkedIn API) - linkedin

I am trying to follow a company without success.
I have generated an access token for all scopes which also works for other functions with the API:
scope=w_messages+rw_company_admin+rw_nus+r_emailaddress+r_basicprofile+rw_groups+r_fullprofile+r_network+r_contactinfo
The below code reaches the end and shows the MessageBox with message:
"BadRequest,Can not parse JSON company document.\nRequest body:\n\nError:\nnull"
I will be happy for help. I have follwed the below documentation but it doesn't exactly show how to follow the company, so it leaves me with this question and example below:
https://developer.linkedin.com/documents/company-follow-and-suggestions
String companyID = "9288340";
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies/id=" + companyID + "?oauth2_access_token=MYTOKENGOESHERE";
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());

After a lot of testing, I just managed to be able to follow a company.
So the below code is working:
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies?oauth2_access_token=MYTOKENGOESHERE";
var BODY = new
{
id = "9288340" //companyID
};
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(BODY);
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());

Related

How to write to csv file and attach it to email using Mail kit - Dotnet 6.0?

I want to know how to write my response - filtered Response to a csv file and attach it to an email using Mail kit. I can send an email with a body but I am unable to add an attachment.
//My Object
var result = await _thunderheadReportRepository.GetMembershipOfferDetailsAsync(searchDate, cancellationToken);
var filteredResponse = result.Select(o => new MembershipOfferDetailsResponse { CreationDate = o.CreationDate!, CorrelationId = o.CorrelationId!, PolicyCode = o.PolicyCode!, AnnualPremium = o.AnnualPremium! }).ToList();
return filteredResponse;
//My email body
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("email", _appSettings.EmailConfiguration.From));
emailMessage.To.AddRange(message.To);
emailMessage.Subject = message.Subject;
var bodybuilder = new BodyBuilder { HtmlBody = string.Format("<h2 style='color:red'>{0}</h2>", message.Content) };
emailMessage.Body = bodybuilder.ToMessageBody();
return emailMessage;
You just need to call:
bodyBuilder.Attachments.Add ("filename.csv");

How to send a notification to the OneSignal API with flurl

I'm trying to send some data using the example in the page of onesignal
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic xxx");
var obj = new
{
app_id = "xxx",
contents = new { en = "English Message" },
included_segments = new string[] { "Active Users" }
};
var param = JsonConvert.SerializeObject(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
This coded works fine, but I'm using Flurl to make a request to onesignal like this:
var body = new
{
app_id = "xxx",
contents = new
{
es = "Mensaje prueba"
},
included_segments = new string[] { "All" }
};
string param = JsonConvert.SerializeObject(body);
var content = new System.Net.Http.ByteArrayContent(Encoding.UTF8.GetBytes(param));
var response = await new Flurl.Url(urlbase)
.AppendPathSegment("notifications")
.WithHeader("Content-Type", "application/json; charset=utf-8")
.WithHeader("Authorization", "Basic xxx")
.PostAsync(content)
.ReceiveString();
but I'm getting the "Bad request". Please someone could help to point how to make the same call with Flurl?
As mentioned in the first comment, you're doing more work than you need to. Flurl will serialize body for you, so remove these lines:
string param = JsonConvert.SerializeObject(body);
var content = new System.Net.Http.ByteArrayContent(Encoding.UTF8.GetBytes(param));
And post body directly using PostJsonAsync:
var response = await urlbase
...
.PostJsonAsync(body)
.ReceiveString();

Unknown authentication scheme when liking post (LinkedIn API)

Below goal is to like a post!
I get an error when trying to "Like" a post with the REST API (LinkedIn)
I have created an accesstoken with all scopes:
scope=w_messages+rw_company_admin+rw_nus+r_emailaddress+r_basicprofile+rw_groups+r_fullprofile+r_network+r_contactinfo
I can retreive comments from posts with the accesstoken which tell us that I have set it up correctly as a base.
However when I try to like a comment with the below code (just after in the same code where I have collected a comment), I receive this error:
"unknown authentication scheme"
I wonder why I can't like a post when I have set all scopes and I also have them checked in my application settings. Also notice that the postID is correct as I can retreive the comments for the post?
Thank you!
String accessToken = "MYLONGTOKEN"; //Just dummy example
String postID = "g-123456-S-123456789"; //Just dummy example
String requestUrl = "https://api.linkedin.com/v1/posts/" + postID + "/relation-to-viewer/is-liked&oauth2_access_token=" + accessToken;
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.PUT);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
restResponse = (RestSharp.RestResponse)rc.Execute(request);
responseStatus = restResponse.ResponseStatus;
//unknown authentication scheme
MessageBox.Show(restResponse.Content.ToString());
I found a solution which seems to work. The additional and replacement code is:
//Comment this post
requestUrl = "https://api.linkedin.com/v1/posts/" + postID + "/comments?oauth2_access_token=" + accessToken;
var comment = new
{
text = "This is a comment!"
};
rc = new RestSharp.RestClient();
request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(comment);
restResponse = (RestSharp.RestResponse)rc.Execute(request);
responseStatus = restResponse.ResponseStatus;
MessageBox.Show(responseStatus.ToString() + "," + restResponse.Content.ToString());

Sending parameter along URL actionscript

As part of a mobile app I'm building I have to authenticate trough the API of Last.FM.
As documented on their website I tried to format to url correctly but appearently I'm doing something wrong because I get error:
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession
Last.FM documentation: http://www.last.fm/api/mobileauth
My code below:
var username:String = "xxxxxxx";
var password:String = "xxxxxxxxxxxx";
var api_key:String = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var secret:String = "xxxxxxxxxxxxxxxxxxxxxx";
var api_sig:String = MD5.hash( "api_key" + api_key + "methodauth.getMobileSessionpassword" + password + "username" + secret);
var request:URLRequest = new URLRequest("https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession");
var variables:URLVariables = new URLVariables();//create a variable container
variables.username =username;
variables.password = password;
variables.api_key = api_key;
variables.api_sig = api_sig;
request.data = variables;
request.method = URLRequestMethod.POST;//select the method as post/
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.load(request);//send the request with URLLoader()
Does someone know the answer?
Try to use HTTPService instead of URLLoader. Smth like this:
var http:HTTPService = new HTTPService();
http.useProxy = false;
http.resultFormat = "e4x";
http.method = "POST";
http.url = "https://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession";
var variables:Object = {};
variables.username = username;
variables.password = password;
variables.api_key = api_key;
variables.api_sig = api_sig;
var token:AsyncToken = http.send(variables);
var responder:Responder = new Responder(handleRequestComplete, handleError);
token.addResponder(responder);
Where handleRequestComplete and handleError are your handlers for the request results:
private function handleRequestComplete(event:ResultEvent):void
{
// your code here
}
private function handleError(event:FaultEvent):void
{
// your code here
}

Amazon CloudFront invalidation in ASP.Net

I am not sure how to send a request using ASP.Net to Amazon CloudFront to invalidate an object.
The details are here http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?Invalidation.html
but I am not sure how to implement this in ASP.Net.
The accepted answer no longer works as of the latest version of the AWS SDK for .NET (1.5.8.0). This should do the trick:
using Amazon;
using Amazon.CloudFront.Model;
...
var client = AWSClientFactory.CreateAmazonCloudFrontClient(accessKey, secretKey);
client.CreateInvalidation(new CreateInvalidationRequest {
DistributionId = distributionID,
InvalidationBatch = new InvalidationBatch {
Paths = new Paths {
Quantity = arrayofpaths.Length,
Items = arrayofpaths.ToList()
},
CallerReference = DateTime.Now.Ticks.ToString()
}
});
Got it working, here it is if anyone else finds it useful.
public static void InvalidateContent(string distributionId, string fileName)
{
string httpDate = Helpers.GetHttpDate();
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = #"<InvalidationBatch>" +
" <Path>/" + fileName + "</Path>" +
" <CallerReference>" + httpDate + "</CallerReference>" +
"</InvalidationBatch>";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation");
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.Headers.Add("x-amz-date", httpDate);
Encoding ae = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1(ae.GetBytes(GlobalSettings.AWSSecretAccessKey.ToCharArray()));
string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));
webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + GlobalSettings.AWSAccessKeyId + ":" + b64);
webRequest.ContentLength = data.Length;
Stream newStream = webRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
/// <summary>
/// Gets a proper HTTP date
/// </summary>
public static string GetHttpDate()
{
// Setting the Culture will ensure we get a proper HTTP Date.
string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
return date;
}
Here's a python version of the above, if anyone finds it useful
from datetime import datetime
import urllib2, base64, hmac, hashlib
def getHTTPDate():
return datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")
def submitInvalidationRequest(fileName,distributionId):
url = "https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation"
httpDate = getHTTPDate();
postData = "<InvalidationBatch>" +"<Path>/" + fileName + "</Path>" +"<CallerReference>" + httpDate + "</CallerReference>" +"</InvalidationBatch>";
sig = hmac.new(AWSSecretAccessKey, unicode(httpDate), hashlib.sha1)
headers = {"ContentType": "text/xml",
"x-amz-date": httpDate,
"Authorization":"AWS " + AWSAccessKeyId + ":" + base64.b64encode( sig.digest() )}
req = urllib2.Request(url,postData,headers)
return urllib2.urlopen(req).read()
using the AWSSDK .net api wrapper from amazon makes this task even easier.
using Amazon.CloudFront.Model;
...
var client = Amazon.AWSClientFactory.CreateAmazonCloudFrontClient(ConfigurationManager.AppSettings["Aws.AccessKey"],
ConfigurationManager.AppSettings["Aws.SecretKey"]);
var request = new PostInvalidationRequest();
request.DistributionId = ConfigurationManager.AppSettings["Cdn.DistributionId"];
request.InvalidationBatch = new InvalidationBatch();
request.InvalidationBatch.CallerReference = new Guid().ToString();
request.InvalidationBatch.Paths = PathsInput.Text.Split(new[]{'\n','\r'},StringSplitOptions.RemoveEmptyEntries).ToList();
var response = client.PostInvalidation(request);
Here's perl:
use warnings;
use strict;
use HTTP::Date;
use Digest::SHA qw(hmac_sha1);
use LWP::UserAgent;
use MIME::Base64;
use Encode qw(encode_utf8);
#ARGV == 4 || die "usage: $0 url distribution_id accesskey secretkey\n";
my $invalid_url = $ARGV[0];
my $distribution_id = $ARGV[1];
my $accesskey = $ARGV[2];
my $secretkey = $ARGV[3];
my $url = "https://cloudfront.amazonaws.com/2010-11-01/distribution/$distribution_id/invalidation";
my $date = time2str;
my $post_data = <<HERE;
<?xml version="1.0" encoding="UTF-8"?>
<InvalidationBatch>
<Path>$invalid_url</Path>
<CallerReference>$date</CallerReference>
</InvalidationBatch>
HERE
my $sig = encode_base64(hmac_sha1(encode_utf8($date),encode_utf8($secretkey)));
my $browser = LWP::UserAgent->new;
my $res = $browser->post($url,
"Content" => $post_data,
"ContentType" => "text/xml",
"x-amz-date" => $date,
"Authorization" => "AWS $accesskey:$sig");
print $res->status_line, "\n", $res->content;

Resources