Couldn't parse share document: error in LinkedIn REST API share - c#

I try to call a share REST API with Hammock library function in my MVC 4 application.
Please see my code below
public ActionResult SharePost()
{
string content = "";
try
{
var credentials = new OAuthCredentials
{
ConsumerKey = "xxxxxxxxxxxxxx",
ConsumerSecret = "xxxxxxxxxxxxxxxx",
Token = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
TokenSecret = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
Verifier = verifier,
Type = OAuthType.AccessToken,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
Version = "1.0"
};
var client = new RestClient { Authority = "http://api.linkedin.com/v1", Credentials = credentials, Method = WebMethod.Post };
var request = new RestRequest { Path = "/people/~/shares" };
StringBuilder sbAppend = new StringBuilder();
sbAppend.AppendLine("<?xml version=1.0 encoding=UTF-8?>");
sbAppend.AppendLine("<share><comment>Check out the LinkedIn Share API!</comment><content><title>LinkedIn Developers Documentation On Using the Share API</title><description>Leverage the Share API to maximize engagement on user-generated content on LinkedIn</description><submitted-url>https://developer.linkedin.com/documents/share-api</submitted-url><submitted-image-url>http://m3.licdn.com/media/p/3/000/124/1a6/089a29a.png</submitted-image-url></content><visibility><code>anyone</code></visibility></share>");
client.AddHeader("Content-Type", "text/xml");
byte[] msg = Encoding.Default.GetBytes(sbAppend.ToString());
client.AddPostContent(msg);
RestResponse response = client.Request(request);
content = response.Content;
}
catch (Exception ex)
{
throw ex;
}
return Content(content);
}
But i get a error responce.content
Edit
I use double quotes in my xml header. but always shows the same error.
Is there any thing wrong.
I didn't see the post xml values in fiddller. Please see this image
Please help.

I found error in your XML you are missing ""
Try this
sbAppend.AppendLine('<?xml version="1.0" encoding="UTF-8"?>');

Related

Send post to Facebook page

I have a c# asp.net web application.
I am using the facebook login through their javascript sdk and it does the login.
Now I have a Simple WYSIWYG Editor in which whatever is added should be posted on the facebook page of that logged in user.
Following is the code:
string FacebookApiId = "952214336368241";
string FacebookApiSecret = "fb2213d66523c8cb0bc99306f46ee457";
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
private string GetAccessToken(string apiId, string apiSecret)
{
string AuthenticationUrlFormat = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret);
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd(); // this gives me {"access_token":"952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6Bt","token_type":"bearer"}
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"]; // This line throws error
}
//if (accessToken.Trim().Length == 0)
//throw new Exception("There is no Access Token");
return "952214336368241|McqSGYIMU1eYBZ1zGydWj9hu6B"; // hard-coded to get it working;
}
private void PostMessage(string accessToken, string v)
{
try
{
FacebookClient facebookClient = new FacebookClient(accessToken);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
messagePost.message = v;
var result = facebookClient.Post("/[user id]/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle something
}
catch (Exception ex)
{
//handle something else
}
}
This throws error:
{"(OAuthException - #803) (#803) Some of the aliases you requested do not exist: [user id]"}
I even wrote my facebook emailid instead of [user id] but it still does not work and gives me error:
Message: "(OAuthException - #2500) An active access token must be used to query information about the current user."
Can anyone please advise how can I remove this error.
The code is VERY old, offline_access and publish_stream do not exist anymore since many years.
You have to use a Page Token with the publish_pages permission in order to post to your Page with the API.
You can use "me/feed" or "page-id/feed", but not an Email.
Information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens/
https://www.devils-heaven.com/facebook-access-tokens/
Try stuff in the API Explorer before programming: https://developers.facebook.com/tools/explorer/

Jira Rest API login error in JIRA SERVER using C#

I want connect to jira server using C# Rest api
https://jira.myserver.co.kr/rest/auth/1/session
enter code here
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
... more
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
the remote server returned an error (404)
I tried different work arounds but all went in vain. May I know why this error is coming? What could be the resolution of this error?
You can search for a reason of this error in different ways:
by looking at logs of JIRA server, there might be some messages/stacktraces there (for example, atlasian-jira.log);
by using some tool to perform/debug/test REST calls (for example, postman), and when it's start working in tool you can write code to do it programmatically. JIRA can return description of error in the response, and tool can show it to you.
When you get this information it can give you exact reason why it is not working. Once I got 403 error and it was because threshold of unsuccessful login attempts was exceeded, I logged into JIRA server using web browser (and entered captcha), and after that I was able to obtain session through application code.
I can successfully obtain session from JIRA in the following way using postman:
Request type: POST
URL: https://myjiraserver.com/rest/auth/1/session
Body: {"username":"myusername","password":"mypassword"}
Headers: Content-Type:application/json
you can do something like this:
namespace YOUR_NAME_SPACE
{
public class jira
{
public static string createTicket(string url, string data)
{
try
{
var client = new System.Net.Http.HttpClient();
string base64Credentials = GetEncodedCredentials();
var header = new AuthenticationHeaderValue("Basic", base64Credentials);
client.DefaultRequestHeaders.Authorization = header;
var content = new StringContent(data, Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;
var response = result.Content.ReadAsStringAsync().Result;
// You can call putIssue if you want
return response;
}
catch (System.Net.WebException ex)
{
Console.WriteLine("Exception Occurred" + " : {0}", ex.Message);
throw;
}
}
private static string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", "LOGIN", "PASSWD");
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
return Convert.ToBase64String(byteCredentials);
}
public static string jiraSerialise(string project, string summary, string description, string issutype, string author)
{
JObject valuesToJson =
new JObject(
new JProperty("fields",
new JObject(
new JProperty("project",
new JObject(new JProperty("key", project))),
new JProperty("summary", summary),
new JProperty("description", description),
new JProperty("issuetype",
new JObject(new JProperty("name", issutype))),
new JProperty("assignee",
new JObject(new JProperty("name", author))))));
return valuesToJson.ToString();
}
public static string putSerialize(string key, string value)
{
JObject valueToJson =
new JObject(
new JProperty(key, value));
return valueToJson.ToString();
}
public static string putIssue(string response, string author, System.Net.Http.HttpClient client)
{
JObject jsonResponse = JObject.Parse(response);
Dictionary<string, string> dictResponse = jsonResponse.ToObject<Dictionary<string, string>>();
string issueUrl = dictResponse.Last().Value;
string issueAssignee = issueUrl + "/assignee";
var authorContent = new StringContent(author, Encoding.UTF8, "application/json");
var authorResult = client.PutAsync(issueAssignee, authorContent).Result;
var authorResponse = authorResult.Content.ReadAsStringAsync().Result;
Console.WriteLine(authorResponse);
return authorResponse;
}
}
}
And now you can call this class like that:
string data = jira.jiraSerialise("lala", "nameVulnerabilty", "descriptionField", "Bug", "author");
string url = "http://YOUR_URL/rest/api/2/issue/";
Console.WriteLine(jira.createTicket(url, data));
Hope it helps :)

Box API Create Shared link

I am trying to upload some documents to Box and create and retrieve a shared link for each of them.
This is the code I am using for it, but I always retrieve 403:access_denied_insufficient_permissions.
Any idea of why this is happening?
Hope you can help me! Thanks.
// CREATE THE FILE
BoxFileRequest req = new BoxFileRequest
{
Name = zipFile.Name,
Parent = new BoxRequestEntity { Id = newFolder.Id}
};
BoxFile uploadedFile = client.FilesManager.UploadAsync(req, stream).Result;
//REQUEST SHARED LINK
BoxSharedLinkRequest sharedLinkReq = new BoxSharedLinkRequest()
{
Access = BoxSharedLinkAccessType.open,
Permissions = new BoxPermissionsRequest
{
Download = BoxPermissionType.Open,
Preview = BoxPermissionType.Open,
}
};
BoxFile fileLink = fileManager.CreateSharedLinkAsync(uploadedFile.Id, sharedLinkReq).Result;
you need to give the access token and url. I have use the Following code and in JSON Format you will get the Response. For more reference check the box API document
HttpWebRequest httpWReq = HttpWebRequest)WebRequest.Create("https://api.box.com/2.0/folders/" + FolderID);
ASCIIEncoding encoding = new ASCIIEncoding();
string putData = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] data = encoding.GetBytes(putData);
httpWReq.Method = "PUT";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
Use the httpwebrequest PUT method after this.
Mark it as Answer if its helpful.
It looks as if you are using the 3rd party BoxSync V2 API object. If you would like to just code to the API directly I had a similar issue that you are having. If you view this post you will see the answer. Here is the code I use and it works.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;

How to post an image to Twitter in C#

I want to post an image to my Twitter account via C#. I can get access token code, everything is fine but I investigated a PHP code
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => OAUTH_CONSUMER_KEY,
'consumer_secret' => OAUTH_CONSUMER_SECRET,
'user_token' => $oauth_token,
'user_secret' => $oauth_token_secret,
));
$image = "{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}";
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => " " . $status, //A space is needed because twitter b0rks if first char is an #
'lat' => $lat,
'long' => $long,
),
true, // use auth
true // multipart
In PHP code, the OAuth class has a request method. In C# side, I used Twitterizer library which hasn't any request method in OAuth class. Then I used Webclient instead of request method. But I need to some Credentials to post data. But I don't know what/why I use username and password. Actually, I don't want to use any credentials. What can I use instead of credentials?
Second problem is, I always get an authorized errors (401) here is code
OAuthTokenResponse responseToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerSecret, oauth_token, oauth_verifier);
OAuthTokens accessToken = new OAuthTokens();
accessToken.AccessToken = responseToken.Token;
accessToken.AccessTokenSecret = responseToken.TokenSecret;
accessToken.ConsumerKey = ConsumerKey;
accessToken.ConsumerSecret = ConsumerSecret;
TwitterResponse<TwitterUser> twitterResponse = TwitterAccount.VerifyCredentials(accessToken);
System.Net.ServicePointManager.Expect100Continue = false;
if (twitterResponse.Result != RequestResult.Unauthorized)
{
try
{
string URL = "https://upload.twitter.com/1/statuses/update_with_media.json";
WebClient client = new WebClient();
client.Credentials = new System.Net.NetworkCredential(uName, pass);
NameValueCollection postData = new NameValueCollection();
postData.Add("status", status);
postData.Add("media[]", Encoding.ASCII.GetString(bytesOfImage));
byte[] b = client.UploadValues(URL, "POST", postData); // 401 error.
}
catch (Exception e)
{
return e.Message;
}
So where is the problem in my code?
You can do this in LINQ to Twitter, using the TweetWithMedia method, like this:
static void TweetWithMediaDemo(TwitterContext twitterCtx)
{
string status = "Testing TweetWithMedia #Linq2Twitter " + DateTime.Now.ToString(CultureInfo.InvariantCulture);
const bool possiblySensitive = false;
const decimal latitude = StatusExtensions.NoCoordinate; //37.78215m;
const decimal longitude = StatusExtensions.NoCoordinate; // -122.40060m;
const bool displayCoordinates = false;
const string replaceThisWithYourImageLocation = #"..\..\images\200xColor_2.png";
var mediaItems =
new List<Media>
{
new Media
{
Data = Utilities.GetFileBytes(replaceThisWithYourImageLocation),
FileName = "200xColor_2.png",
ContentType = MediaContentType.Png
}
};
Status tweet = twitterCtx.TweetWithMedia(
status, possiblySensitive, latitude, longitude,
null, displayCoordinates, mediaItems, null);
Console.WriteLine("Media item sent - Tweet Text: " + tweet.Text);
}
Joe

Simplest way to post to a facebook fan page's wall with C#!

I have a fan page setup for my company.
I want to automate the posting of regular updates to that page's wall from my C# desktop application.
Which Facebook C# library is the simplest?
How can I easily acquire the access token for this page?
What is the most concise code snippet that will simply allow me to then post to the wall?
I have read through all the docs and millions of stackoverflow and blog posts and it all seems very convoluted. Surely it can't be that hard..
I have setup an "application" within facebook that has its own App ID, API Key and App Secret etc.
#Aaron - the best library is the facebook c# sdk. I use it every day... granted I am biased as my company writes it - but it's a dynamic library and with the rate of updates from Facebook (every Tuesday) it is well suited for scalable development.
http://facebooksdk.codeplex.com/
I won't get into authentication with it - as on codeplex there are many examples:
http://facebooksdk.codeplex.com/wikipage?title=Code%20Examples&referringTitle=Documentation
But to do a post to a page, after you have authenticated and have an access token, the code would be something like this:
dynamic messagePost = new ExpandoObject();
messagePost.access_token = "[YOUR_ACCESS_TOKEN]";
messagePost.picture = "[A_PICTURE]";
messagePost.link = "[SOME_LINK]";
messagePost.name = "[SOME_NAME]";
messagePost.caption = "{*actor*} " + "[YOUR_MESSAGE]"; //<---{*actor*} is the user (i.e.: Aaron)
messagePost.description = "[SOME_DESCRIPTION]";
FacebookClient app = new FacebookClient("[YOUR_ACCESS_TOKEN]");
try
{
var result = app.Post("/" + [PAGE_ID] + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle something
}
catch (FacebookApiException ex)
{
//handle something else
}
Hope this helps.
I am posting this because of lack of good information on the internet that led to me spend more time than I needed. I hope this will benefit others. The key is adding &scope=manage_pages,offline_access,publish_stream to the url.
class Program
{
private const string FacebookApiId = "apiId";
private const string FacebookApiSecret = "secret";
private const string AuthenticationUrlFormat =
"https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials&scope=manage_pages,offline_access,publish_stream";
static void Main(string[] args)
{
string accessToken = GetAccessToken(FacebookApiId, FacebookApiSecret);
PostMessage(accessToken, "My message");
}
static string GetAccessToken(string apiId, string apiSecret)
{
string accessToken = string.Empty;
string url = string.Format(AuthenticationUrlFormat, apiId, apiSecret);
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
NameValueCollection query = HttpUtility.ParseQueryString(responseString);
accessToken = query["access_token"];
}
if (accessToken.Trim().Length == 0)
throw new Exception("There is no Access Token");
return accessToken;
}
static void PostMessage(string accessToken, string message)
{
try
{
FacebookClient facebookClient = new FacebookClient(accessToken);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
//messagePost.picture = "[A_PICTURE]";
//messagePost.link = "[SOME_LINK]";
//messagePost.name = "[SOME_NAME]";
//messagePost.caption = "my caption";
messagePost.message = message;,
//messagePost.description = "my description";
var result = facebookClient.Post("/[user id]/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
//handle something
}
catch (Exception ex)
{
//handle something else
}
}
}
Check my answer over here:
how to post to facebook page wall from .NET
Check full example:
http://klaatuveratanecto.com/posting-on-facebook-wall-feed-with-c-and-asp-net-mvc-5/

Categories

Resources