c# - How to Add Post Comment in LinkedIn? - c#

I'm trying to add post comment in LinkedIn for the past one week
I've written this code
protected void Page_Load(object sender, EventArgs e)
{
string xmlContent = "<?xml version='1.0' encoding='UTF-8'?>";
xmlContent += "<comment><text>Check out</text></comment>";
byte[] databytes = Encoding.Default.GetBytes(xmlContent);
var credentials = new Hammock.Authentication.OAuth.OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "*********",
ConsumerSecret = "*********",
Token = "*********",
TokenSecret = "*********",
Version = "1.0"
};
var client = new Hammock.RestClient() { Authority = "http://api.linkedin.com/v1/posts" };
var request = new Hammock.RestRequest() { Path = "/56787878/comments", Method = Hammock.Web.WebMethod.Post, Timeout = new TimeSpan(0, 0, 5), Credentials = credentials };
request.AddHeader("Content-Type", "application/xml");
client.AddParameter("","");
client.AddPostContent(Encoding.UTF8.GetBytes(xmlContent));
//request.AddPostContent(Encoding.UTF8.GetBytes(xmlContent));
var response = client.Request(request);
Response.Write(response.Content);
}
I get an error in the below Xml format
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<error>
<status>400</status>
<timestamp>1374494502579</timestamp>
<request-id>QM4MYPEKJJ</request-id>
<error-code>0</error-code>
<message>Couldn't parse message document: error: Unexpected end of file after null</message>\n</error>
Anybody handle this error? Thanks in advance.

Related

I can't get a soap message in C#

I'm getting an error:
A security error was encountered when verifying the message
Https is expected when I somehow overcome this error. But I have to use Http.
EndpointAddress address2 = new EndpointAddress("http://xx.xx.xxxx/ws/test?wsdl");
FactoryWebServiceClient client = new FactoryWebServiceClient();
client.Endpoint.Address = address2;
if (client.ClientCredentials != null)
{
client.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("username","password");
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
}
XmlDocument doc = new XmlDocument();
doc.Load("C:\\...\\test.xml");
byte[] bytes = Encoding.Default.GetBytes(doc.OuterXml);
var request2 = new factoryWSUpdateData
{
BeanXml = bytes,
Period = 1,
InputType = "xml",
OutputType = "json2",
CodeTemplate = 1
};
var result = client.create(request2);

Yahoo Weather API using Oauth

I am stuck on implementing the Yahoo Weather private API call. This is my code snippet, whenever I call it using valid clientId & Secret it returns 401 (unauthorized).
var outhWc = new WebClient();
outhWc.Credentials = new NetworkCredential(clientId, clientSecret);
outhWc.Headers.Add(HttpRequestHeader.Accept, "application/json");
var outhresponse = outhWc.DownloadData("https://query.yahooapis.com/v1/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json");
It always throws an exception. I also try to pass username and password in NetworkCredentials and also try to pass clientId and Secret in Header but I cannot find a successful call.
So I've been stuck with the same issue here. Finally I implemented the following code, based on the oAuth c# simple class found at http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs
public void LoadWeather() {
string URLDes, Params = "";
string Signature, BaseURL, cKey, cSecret = "";
OAuthBase oAuth = new OAuthBase();
BaseURL = "http://weather.yahooapis.com/forecastrss?w=" + textBox1.Text + "&u=f";
cKey = "YOUR API KEY";
cSecret = "YOUR API SECRET";
Signature = oAuth.GenerateSignature(new Uri(BaseURL), cKey, cSecret, "", "", "GET", oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out URLDes, out Params);
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri(String.Format("{0}?{1}&oauth_signature={2}", URLDes, Params, Signature)));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) {
if (e.Error == null) {
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
xdoc.Save("c:\\weather.xml");
richTextBox1.Text = xdoc.FirstNode.ToString();
} else {
richTextBox1.Text = e.Error.Message;
}
}
As you can see, I already have the city ID. This sample downloads the xml string returned by the API. Worked for me, hope it helps!

How to connect Amazon API in c#

I have tried with below stuffs to connect Amazon API but failed to connect it I am getting error as "The remote server returned an error: (400) Bad Request". How to resolve this issue. Any help would be appreciated.
Code:
protected void btnAmazonItemSerach_Click(object sender, EventArgs e)
{
string associateId = "**************";
string accessKey = "*************";
string secretKey = "**************************";
string url = "http://webservices.amazon.com/onca/xml";
HttpWebRequest oRequest = (HttpWebRequest)HttpWebRequest.Create(url);
oRequest.Method = "GET";
oRequest.ContentType = "application/xml";
oRequest.Headers.Add("AWSAccessKeyId", accessKey);
oRequest.Headers.Add("AssociateTag", associateId);
oRequest.Headers.Add("Keywords", "Blueant s4");
oRequest.Headers.Add("Operation", "ItemSearch");
oRequest.Headers.Add("Service", "AWSECommerceService");
Encoding oEncod = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1();
signature.Key = oEncod.GetBytes(secretKey);
string sign = Convert.ToBase64String(signature.Key);
oRequest.Headers.Add("Signature", sign);
oRequest.Headers.Add("SearchIndex", "All");
oRequest.Headers.Add("Version", "2011-08-01");
string dateval = DateTime.Now.ToString();
oRequest.Headers.Add("Timestamp", dateval);
HttpWebResponse oResponse =(HttpWebResponse) oRequest.GetResponse();
StreamReader oreader =new StreamReader(oResponse.GetResponseStream());
var val = oreader.ReadToEnd();
XmlDocument oxmldoc = new XmlDocument();
oxmldoc.LoadXml(val);
XmlElement oxmlelem = (XmlElement)oxmldoc.GetElementsByTagName("Items")[0];
if (oxmlelem != null)
{
List<string> olistItems = new List<string>();
XmlNodeList olist = oxmldoc.GetElementsByTagName("Item");
for (int i = 0; i < olist.Count; i++)
{
string asi = olist[i].FirstChild.InnerText;
olistItems.Add(asi);
}
}
}

HTTP POST is giving unauthorized 401 Exception

When calling the same method on google chrome postman after logging in, i'm getting the json object as shown below.
but when i try to get the same json result in codebehind (C#). I'm getting Unauthorized 401 exception.
I'm using my code like this.
using (var clientSideTab = new WebClient())
{
var valSideTab = new System.Collections.Specialized.NameValueCollection { { "username", UserID }, { "Password", strPassword } };
string UpldDataSideTab = "https://resapistage.namechanged.com/v3/secure/Login.aspx?userId=" + UserID + "&passwd=" + strPassword + " ";
SystemComponentWrapper SPPostWrapper = new SystemComponentWrapper();
SystemComponentData request = new SystemComponentData();
SystemComponentaddressId addressId = new SystemComponentaddressId();
addressId.type = "AddressId";
addressId.id = 19863;
addressId.serial = "";
request.addressId = addressId;
request.compId = null;
request.getCompParams = true;
request.filterForAddress = false;
SPPostWrapper.request = request;
var postJson = JsonConvert.SerializeObject(SPPostWrapper);
Encoding encoding = new UTF8Encoding();
string postData = postJson.ToString();
byte[] bdata = encoding.GetBytes(postData);
string URI = "https://resapistage.namechanged.com/v3/api/secure/json/AddressInfo.svc/getSystemComponentsV2";
clientSideTab.UploadValues(UpldDataSideTab, "POST", valSideTab);
clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
clientSideTab.Headers.Add("Accept","application/json");
clientSideTab.UploadString(URI,"POST", postData);
//clientSideTab.UploadData(URI, "POST", bdata);
String jsonresponse = "failed";
Label1.Text = jsonresponse;
}
I'm getting this error everytime. please help me.
use like this.
string cookie = strCookie[0]; // fetch your cookie after logging in
clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
clientSideTab.Headers.Add("Accept","application/json");
clientSideTab.m_container.SetCookies(URI, cookie);
//clientSideTab.Headers.Add(HttpRequestHeader.Cookie, cookie);
String resultJSON = clientSideTab.UploadString(URI,"POST", jsonData);
this worked for me. hope this will help you.

c# - How to reply for comment in LinkedIn?

I'm trying to integrate LinkedIn in our application. I just want to know how to reply for comment in LinkedIn.
I've written this code.
protected void Page_Load(object sender, EventArgs e)
{
string data = "<comments><comment><text>Check out the Reply!</text></comment></comments>";
byte[] databytes = Encoding.UTF8.GetBytes(data);
var request = new RestRequest { Path = "comments" };
var credentials = new Hammock.Authentication.OAuth.OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "kmkzt9cqml1s",
ConsumerSecret = "hNiwIrZWGSMykoD2",
Token = "b3cbdca7-37a7-474f-a9a6-e21bb89917fe",
TokenSecret = "990f1b78-79de-4490-b4e3-893b4e020e45",
};
var client = new RestClient()
{
Authority = "http://api.linkedin.com/v1/posts/g-457832-S-454334",
Credentials = credentials,
Method = WebMethod.Post,
};
client.AddHeader("Content-Type", "text/xml");
client.AddPostContent(databytes);
RestResponse response = client.Request(request);
string content = response.Content;
}
I'm getting an error in content in the below format
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<error>
<status>400</status>
<timestamp>1374494502579</timestamp>
<request-id>QM4MYPEKJJ</request-id>
<error-code>0</error-code>
<message>Couldn't parse message document: error: Unexpected end of file after null</message>\n</error>\n"
Any ideas? Thanks in advance.

Categories

Resources