How can I post something to a Wall using Facebook Developer Toolkit? - c#

Does anyone have experience using the Facebook Developer Toolkit? I am trying to post something to a Facebook user's Wall, but can't figure out how to use the API? Could someone could give me an example or point me to some documentation on the API's usage?

I actually found documentation and samples to do what I was looking for here: http://facebooktoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=28001
EDIT:
After initializing the Facebook session I called the Stream.Publish() method on the API.
FacebookService.API.stream.publish(...);

I created a video tutorial showing how to do exactly this. Here is the link:
http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet
And here is the 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" });
}
}
}
}

Bit late, but maybe it still helps others: http://facebooktoolkit.codeplex.com/Thread/View.aspx?ThreadId=75412

Related

Rest URL consumption guidance required

I have a rest url provided by client , It looks something like www.baseurl/api// I couldn't get result if I try to consume it from console application getting error 503.
However I m able to browse it from my browser and it returns the proper json of Entity Details. Please help me with this.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp15
{
public class Class1
{
private const string URL = "www.baseurl/api/<EntityName>/<EntityID>";
static void Main(string[] args)
{
Class1.CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
}
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
}
}
}
}

when im using facebook wall post it give me error

When im using Mark Hagan Facebook wall post source code it give me error like length cannot be zero.
im trying to facebook wall post using users.
here is my code please help me, what is the issue in this 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 PayPalAPISample
{
public partial class facebooksync : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAuthorization();
}
private void CheckAuthorization()
{
string app_id = "App Id";
string app_secret = "App Secret";
string scope = "publish_actions,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" });
}
}
}
}
Help !!!. Thanks in Advance.

Error with C# Web crawler

Can some one please assist me with this webcrawler, I keep getting the error :
Cannot implicitly convert type
'System.Collections.Generic.ISt' to 'string.
This error is in line where it is String Links = GetNewLinks(Rstring);, can someone please help, here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace Crawler
{
public partial class Crawler : Form
{
String Rstring;
public Crawler()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebRequest myWebRequest;
WebResponse myWebResponse;
String URL = txt1.Text;
myWebRequest = WebRequest.Create(URL);
myWebResponse = myWebRequest.GetResponse();
Stream streamResponse = myWebResponse.GetResponseStream();
StreamReader sreader = new StreamReader(streamResponse);
Rstring = sreader.ReadToEnd();
String Links = GetNewLinks(Rstring);
txt2.Text = Rstring;
txt3.Text = Links;
sreader.Close();
streamResponse.Close();
myWebResponse.Close();
}
public ISet<string> GetNewLinks(string content)
{
Regex regexL = new Regex("(?<=<a\\s*?href=(?:'|\"))[^'\"]*?(?=(?:'|\"))");
ISet<string> newLinks = new HashSet<string>();
foreach (var match in regexL.Matches(content))
{
if (!newLinks.Contains(match.ToString()))
newLinks.Add(match.ToString());
}
return newLinks;
}
}
}
GetNewLinks() returns a set of strings (ISet<String>), not one only. So if you want to assign to a single string (String Links) then you have to select a string from the set, e.g. using First().

Creating a login session to a webpage

I hope I ask in the correct way in here as it is my first in stackoverflow.
I am pretty new in C# and WP8, but I am working on a small project where I through my WP8 app login to my page and then my wish is to be able to, after the login, to somehow use the session/cookie from the login to navigate in a WebBrowser control through the other "protected" pages.
I have indeed searched the forums and the net, but I have not found the specific answer elsewhere.
Below I have my login session which works and "result" gives me the HTML of the page after login. But then I am a bit stuck...
Maybe there is a better/smarter/easier way?
Best Regards
Martin
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using HTTPPost.Resources;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace HTTPPost
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
System.Uri myUri = new System.Uri("http://homepage.com/index.php");
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Create the post data
string postData = "user=usernamepass=password";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result;
result = httpWebStreamReader.ReadToEnd();
MiniBrowser.NavigateToString(result);
Debug.WriteLine(result);
}
}
}
}
Well, there is lots of answers about getting and storing cookies, but I have a trick to avoid using them. The trick is to use same instance of WebClient for all requests on this page after login sequence. See my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SomeApp
{
public class WebRequests
{
//Making property of HttpClient
private static HttpClient _client;
public static HttpClient Client
{
get { return _client; }
set { _client = value; }
}
//method to download string from page
public static async Task<string> LoadPageAsync(string p)
{
if (Client == null)// that means we need to login to page
{
Client = await Login(Client);
}
return await Client.GetStringAsync(p);
}
// method for logging in
public static async Task<HttpClient> Login(HttpClient client)
{
client = new HttpClient();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("email", "someone#example.com"),
new KeyValuePair<string, string>("password", "SoMePasSwOrD")
});
var response = await client.PostAsync("https://www.website.com/login.php", content);
return client;
}
var page1Html = await LoadPageAsync("https://www.website.com/page1.php");
}
}

Cannot use Google Translate API because of missing namespaces

The following is my code for using Google Translate. I have one dll I added as a reference: Google.Apis.Translate.V2
I also bought Google Translate API key.
I have 5 errors since I don't know what dll I need more: These objects do not exist missing namespace: DataContractJsonSerializer , TranslationRootObject , TranslationRootObject
What dll reference do I need for these namespaces?
This is my code, without my API key:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
namespace Google_Translate
{
public partial class Form1 : Form
{
static string apiKey = "";
static string texttotranslate = "hello world";
string text;
static String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
static String url = String.Format(apiUrl, apiKey, "en", "ge", texttotranslate);
Stream outputStream = null;
byte[] bytes = Encoding.ASCII.GetBytes(url);
// create the http web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
public Form1()
{
InitializeComponent();
webRequest.KeepAlive = true;
webRequest.Method = "POST";
// Overrride the GET method as documented on Google's docu.
webRequest.Headers.Add("X-HTTP-Method-Override: GET");
webRequest.ContentType = "application/x-www-form-urlencoded";
// send POST
try
{
webRequest.ContentLength = bytes.Length;
outputStream = webRequest.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();
}
catch (HttpListenerException e)
{
/*...*/
}
translate();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private string translate()
{
try
{
// get the response
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK && webRequest != null)
{
// read response stream
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string lista = sr.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationRootObject));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(lista));
TranslationRootObject tRootObject = (TranslationRootObject)serializer.ReadObject(stream);
string previousTranslation = string.Empty;
//deserialize
for (int i = 0; i < tRootObject.Data.Detections.Count; i++)
{
string translatedText = tRootObject.Data.Detections[i].TranslatedText.ToString();
if (i == 0)
{
text = translatedText;
}
else
{
if (!text.Contains(translatedText))
{
text = text + " " + translatedText;
}
}
}
return text;
}
}
}
catch (HttpListenerException e)
{
/*...*/
}
return text;
}
}
}
Can someone fix my code or tell me whats wrong please ?
What I need is to translate 29-33kb text file size and I wonder if it's possible to translate it as fast as it does online when using the Google Translate site.
I also found this link Google Translate V2 cannot hanlde large text translations from C# which someone say the translation can't translate big files so I wonder if 29-33kb files are counting as big? If so maybe someone can take a look at the link and fix my code according to the answer in the link I tried a lot now and didn't understand it really. But first I need to find why my original code here doesn't work.
In your project, add a reference to this assembly:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
There may be others you need, I just looked up this one.

Categories

Resources