Post comment to facebook wall using asp.net - asp.net

I have a website that I have registered as a facebook app - I now have an app ID.
My website is ASP.net C#. When the user clicks a button I'd like it to post a pre-defined message to their wall. I'm expecting Facebook to present a login dialog to the user - they login and grant publish permission to for my website app.
Does anyone have any sample code that would do this? I think I need to use the graph API but all the examples I've seen use PHP - which I know nothing about. I'm looking for an example that would use Java Script (of which I know almost nothing) or C# (beautiful!).
* Update *
I have managed to get the access_token. Now I make a call through the Facebook C# API to post to the wall. I get the error message:
(#803) Some of the aliases you requested do not exist: profile_id
I've stepped through the api code and found that it is trying to post to the following address: {https://graph.facebook.com/PROFILE_ID/feed}, the post data is: message=Sample+message+from+c%23+sdk&access_token=199209316768200|2.1avFTZuDGR4HJ7jPFeaO3Q__.3600.1302897600.1-100000242760733|R4DkNDf4JCb6B2F64n5TSQwBqvM
I'm pretty sure my token should be valid. Prior to requesting access token I requested publish_stream on the app authorization request as follows:
Response.Redirect ("https://www.facebook.com/dialog/oauth?client_id=" + myAppId + "&redirect_uri=" + myURL + "&scope=publish_stream");
The sdk code that actually makes the request is as follows:
private string MakeRequest(Uri url, HttpVerb httpVerb,
Dictionary<string, string> args)
{
if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
{
url = new Uri(url.ToString() + EncodeDictionary(args, true));
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = httpVerb.ToString();
if (httpVerb == HttpVerb.POST)
{
string postData = EncodeDictionary(args, false);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
}
try
{
using (HttpWebResponse response
= request.GetResponse() as HttpWebResponse)
{
StreamReader reader
= new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Can anyone see what I'm doing wrong?
Many thanks,
Rob.

First of all, you need to take care of Authentication. You need to create an Application, and use OAuth to get hold of the access token. It's all described in the Authentication guide.
To post something to the user's wall, take a look at the Graph API under Publishing.
As a start, you could use Facebook's C# SDK

You could look to use a .NET library like http://facebooknet.codeplex.com/ to do this. There are a couple out there, I just remembered this one...
HTH.

I created a video showing how to do this using OG: http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet
In case you don't have time to watch the video, here is the full code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace FBO
{
public partial class facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "374961455917802";
string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
string scope = "publish_stream,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
}
}
}
}

I am using this http://facebooksdk.codeplex.com/ . I am using the latest stable release, easy to use. To comment, just post with /OBJECT_ID/comments for more, refer http://developers.facebook.com/docs/reference/api/#publishing and http://developers.facebook.com/docs/reference/api/post/

How about trying this API tha I recently developed to make integrating with Facebook easier.
Here is a code sample for you there's more documentation on the site.
Authenticating Users
Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[application_id]","applicaiton_secret")
'Redirects user to facebooks
SI.AuthenticateUser("http://[my url]", New SessionInfo.PermissionsEnum(){SessionInfo.PermissionsEnum.email, SessionInfo.PermissionsEnum.read_stream}))
'Called when the user is returned to your page
Dim FSR = FS.ReadFacebooAuthResponse
Response.Write(FSR.Access_Token)
Response.Write(FSR.UserID)
Making Posts
Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[access_token]"))
Dim Posts = New Functions.Posts(SI)
Dim P As New Post
P.name = "name of post"
P.message = "message"
P.link = "www.cnn.com"
P.caption = "my caption"
Posts.PublishCreate("[object ID to post to]", P)
Dim PostID = P.id
Getting stuff from the graph.
Dim SI As New SessionInfo("[access_token]"))
Dim Req New Functions.Requests(SI)
Dim User = Req.GetUserInfo("[optional user ID]")
Response.Write(U.name)

Related

Asp.net HttpWebRequest I can not source code

I want html source code with asp.net HttpWebRequest but there is a problem.
I can get it. No problem that :
https://www.nesine.com/iddaa/default.aspx
But I do not get it :
http://www.iddaa.com/program/futbol.html
in my opinion problem url routing.
I use the code
public static string GetSourceCode(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sRead = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
return sRead.ReadToEnd();
}
help me please.
Thanks.
The http://www.iddaa.com/program/futbol.html url is heavily using javascript and AJAX in order to load its dynamic content. It's a SPA application. The HttpWebRequest class in .NET doesn't execute any javascript. It is simply loading the contents returned by the server at the specified location.
By inspecting the network traffic you will notice that the information you are interested in is located on the following location: http://www.iddaa.com/program/data?sportId=1&date=&sortType=&marketType=1
So you can go ahead and scrape this url:
using System;
using System.IO;
using System.Net;
static class Program
{
static void Main()
{
var request = WebRequest.Create("http://www.iddaa.com/program/data?sportId=1&date=&sortType=&marketType=1");
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string responseHtml = reader.ReadToEnd();
Console.WriteLine(responseHtml);
}
}
}
Obviously, as always with scraping, if the website changes the location of this dynamic url your application will stop working. That's why it's better to use an API if the website provides one. Contact the authors of the website for more information.

Trying to get DHL shipping rates using ASP.Net but DHL's docs/samples are J2EE-geared. Anyone doing this in .Net that can provide some direction?

I'd like to get DHL shipping rates either per transaction or in batch all at once (to store in a table for later use) from an ASP.Net e-commerce application that ships product internationally, but after downloading their J2EE-based toolkit (https://xmlpi-ea.dhl.com) and reviewing the documentation & samples, I'm not quite sure how to do it in .Net. If anyone has experience with getting DHL shipping rates, I'd appreciate a point in the right direction using .Net. as I don't know Java.
Edit
Just found out the servlet is not discoverable, which means I cannot WSDL it to get a proxy class and will have to rely on tons of their XML samples to build my own client. Anyone done this in .NET already?
Looks like they have web services that you can use.
http://www.dhl-usa.com/en/express/resource_center/integrated_shipping_solutions.html
Sorry to be late. I just finished developing an integration and I give you here the way.
First you have to use xsd2code++ because the XSD.EXE from Microsoft doesn't work. Don't ask me why but it doesn't find the import included in the XSD file or maybe I didn't dig enough why and once I tried xsd2code++ it was a breeze to just right click the XSD in Visual Studio and use the option there.
Once you have your XSD converted to classes you consume it with the 3 methods bellow. See the 2 following lines of code that use the methods. Don't forget to add the necessary usings for XDocument.
Once you register on DHL web site you can download the DHL Toolkit PI which contains the folder XSD where all the XSD files are located.
NOTE : An alternative to Xsd2Code++ is Xsd2code on CodePlex : XSD2CODE hurry up because CodePlex is closing
string Request = XDocument.Parse(SerializeToXML(Quote)).ToString();
string Response = XDocument.Parse(SendRequest(Request)).ToString();
if (Response.IndexOf("DCTResponse") != -1)
DCTResponse = DeserializeFromXML<DHL.Response.DCTResponse>(Response);
else
DCTErrorResponse = DeserializeFromXML<DHL.Response.ErrorResponse>(Response);
public static string SendRequest(string XML)
{
string Response = "";
try
{
HttpWebRequest myReq = null;
myReq = WebRequest.Create(Properties.Settings.Default.DHLURL) as HttpWebRequest;
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.Method = "POST";
using (System.IO.Stream stream = myReq.GetRequestStream())
{
byte[] arrBytes = ASCIIEncoding.ASCII.GetBytes(XML);
stream.Write(arrBytes, 0, arrBytes.Length);
stream.Close();
}
WebResponse myRes = myReq.GetResponse();
System.IO.Stream respStream = myRes.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.ASCII);
Response = reader.ReadToEnd();
myRes.Close();
myRes = null;
}
catch (Exception ex)
{
Response = ex.ToString();
}
return Response;
}
public static string SerializeToXML<T>(T toSerialize)
{
string Result = "";
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "");
using (TextWriter tw = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(tw, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
new XmlSerializer(typeof(T)).Serialize(writer, toSerialize, ns);
Result = tw.ToString();
}
}
return Result;
}
public static T DeserializeFromXML<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(xml));
}
Hope this helps...

Post on facebook user's wall on user make some interaction on website

There is a auction website in, the requirement is that everytime user make a bidding on an auction. That action will be posted on their facebook wall if the user allow us to post on their behalf. Is this possible to do and what i have to know to be able to do this. I don't know much about facebook application development.
I don't have knowledge of facebook-c#-sdk (as you tagged) but for this need to follow these steps
Authenticate user using facebook OAuth 2.0 with user_status permission
and the you need to call status api with required param
after googling I found a small solution to update status using facebook-c#-sdk
FacebookClient fbClient = new FacebookClient(accessToken);
parameters = new Dictionary<string, object> {
{ "message", "this is my test message" }
};
fbClient.Post("me/feed", parameters);
The answer above is a possible solution, but a bit clunky.
Leveraging Open Graph Actions would be better.
Your starting point would bd to read:
https://developers.facebook.com/docs/opengraph/
It's not quite as easy as FB suggest of course and the documentation is sketchy, but for an automated, 'frictionless' action as per your requirement, this is the route to follow.
I created an video tutorial and sample source code for doing exactly this.
Video/Code:
http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet
If you don't feel like going to my website, here is the source code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
namespace FBO
{
public partial class facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "374961455917802";
string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
string scope = "publish_stream,manage_pages";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
}
}
}
}

ASP.NET Why is this shortening url code redirecting to page

Hey I have the following method
public static string GetShortenedURL(String inURL)
{
String shortURL = "";
String queryURL = "http://api.bit.ly/shorten?version=2.0.1&longUrl=" + inURL + "&login=&apiKey=";
HttpWebRequest request = WebRequest.Create(queryURL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string jsonResults = reader.ReadToEnd();
int indexOfBefore = jsonResults.IndexOf("shortUrl\": \"") + 12;
int indexOfAfter = jsonResults.IndexOf("\"", indexOfBefore);
shortURL = jsonResults.Substring(indexOfBefore, indexOfAfter - indexOfBefore);
}
return shortURL;
}
Which worked fine on my development machine, but on live server for some reason whenever I call this method I actually seems to visit the URL aswell. The reason why this is a problem is because that URL updates a status of a record. But I only want to do this when the user clicks on the link in the mail but for some very weird reason when Im creating the email on my confirmation page of registration and call this shortened URL method so I can add the short URL in my mail to send out,
it seems to visit it by itself. Hence updating my status when it shouldnt yet.
Any Ideas ?
EDIT : This is how i call it
emailBody.Append(M1Utils.GetShortenedURL(ConfigurationSettings.AppSettings["strSite_FEURL"].ToString() + "login/verify.aspx?" + strEncrypted)).Append("\r\n\r\n");

ASP.net: Getting HTTPS data server-side?

I previously asked on StackOverflow how to parse XML downloaded programmatically by my ASP.net application. By this, I mean that the user visits https://www.example.com/page1.aspx. The code-behind for page1.aspx is supposed to somehow download and parse an xml file located at https://www.example.com/foo.xml.
I received good answers about how to parse the XML. However, I've been out of luck with being able to retrieve XML from my secure HTTPS server.
I am looking at a situation where https://www.example.com/foo.xml authenticates requests with a cookie. (third party system, not Forms Authentication). The answer I received to my question about how to download and parse XML suggested that I use the System.Net.WebClient class. I read that the WebClient class must be customized to work with cookies. Therefore, I wrote the following code:
public class WebClientWithCookies : WebClient
{
private CookieContainer m_container = new CookieContainer();
public CookieContainer CookieContainer
{
get { return m_container; }
set { m_container = value; }
}
public void addCookie(Cookie cookie)
{
m_container.Add(cookie);
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if ( request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
} // end class
However, when the request is received at https://www.example.com/foo.xml, there are no cookies in the request, and so it doesn't work.
How can I work around this problem?
Where are you creating the cookie? That seems to be a missing part from the code you are displaying. There is an "HttpCookie" class as part of the System.Web name space that may be useful.
Here's the code that I eventually wrote that solved the problem:
private XmlDocument getXmlData(string url)
{
System.Net.HttpWebRequest rq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.CookieContainer container = new System.Net.CookieContainer();
for (int i = 0; i < System.Web.HttpContext.Current.Request.Cookies.Count; i++)
{
System.Web.HttpCookie httpcookie = System.Web.HttpContext.Current.Request.Cookies[i];
string name = httpcookie.Name;
string value = httpcookie.Value;
string path = httpcookie.Path;
string domain = "my.domain";
System.Net.Cookie cookie = new System.Net.Cookie(name, value, path, domain);
container.Add(cookie);
}
rq.CookieContainer = container;
rq.Timeout = 10000;
rq.UserAgent = "Asset Tracker Server Side Code";
System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)rq.GetResponse();
System.Text.Encoding enc = System.Text.Encoding.GetEncoding(1252);
System.IO.StreamReader reader = new System.IO.StreamReader(rs.GetResponseStream());
System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
xml.Load(rs.GetResponseStream());
return xml;
}

Resources