I am trying to following tutorial to post tweet to twitter but it is not working for it
http://www.dotnettutorials.com/tutorials/advanced/ASP-Twitter-Posting.aspx
Is their another way or if some can point me to a good tutorial which show how toppost tweet using asp.net C# web application
protected void Button1_Click(object sender, EventArgs e)
{
string username = "YOUR_USER_NAME";
string password = "YOUR_PASSWORD";
string tweet = TextBox1.Text;
try
{
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
request.Method="POST";
request.ServicePoint.Expect100Continue = false;
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType="application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
}
catch (Exception ex)
{
/* DO NOTHING */
}
}
That's an old tutorial as Twitter deprecated basic authentication years ago. These days, you must use OAuth, which Twitter describes in their OAuth Documentation. If you prefer not to write your own OAuth code, you can do a search for 3rd party libraries, DotNetOpenAuth comes to mind, or use a library that does this for you, which you can find on the Twitter Libraries page.
Disclaimer: I wrote one of the libraries on the Twitter Libraries page, named LINQ to Twitter.
Note: You'll want to target the Twitter API v1.1 as the Twitter API v1.0 is now deprecated and will be turned off next month.
I also noticed that you seem to be having difficulty figuring out what the problem is. My best guess is that you're receiving an HTTP 401 Unauthorized response from Twitter. If you called GetResponse() on the request, this 401 response would cause an exception to be raised, but that isn't happening in your code because you're just pushing the request. You should call GetResponse to ensure you know how Twitter reacted to your code. Then you can hit a break point on your catch block or log the response to see what the problem is - sometimes you'll have to examine the fields of the exception to obtain more information. Another great debugging tool is Fiddler, which lets you examine the response from Twitter. FireBug and IE F12 tools are other options (there are probably more), but the goal is to see what Twitter is telling you.
Related
In my C# code running .NET 6 (Azure Function) I am sending an HttpRequestMessage using HttpClient. It doesn't work but it should work, so I want to get the raw request that I am sending, including the header, so I can compare with the documentation and see the differences.
In the past I have used Fiddler but it doesn't work for me now, probably because of some security settings on my laptop. So I am looking for a solution within the world of Visual Studio 2022 or .NET 6 where I can get the raw request out for troubleshooting purposes.
This question is not really about code, but here is my code anyway.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://myendpoint.com/rest/something");
var apiToken = "AOU9FrasdgasdfagtHJNV";
request.Headers.Add("Authorization", "Basic " + apiToken);
var message = new
{
sender = "Hey",
message = "Hello world",
recipients = new[] { new { id = 12345678} }
};
request.Content = new StringContent(JsonSerializer.Serialize(message), Encoding.UTF8, "application/json");
request.Headers.Add("Accept", "application/json, text/javascript");
HttpResponseMessage response = await httpClient.SendAsync(request);
When SendAsync is invoked, I wish to know what exactly is sent, both header and content.
If you cannot use any proxy solution (like Fiddler) then I can see 2 options. One is described in comments in your question to use DelegatingHandler. You can read more about this in documentation. What is interesting is that HttpClient supports logging out of the box which is described in this section https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0#logging of the article which describes DelegatingHandlers
If you are worried that something will manipulate the outgoing request then you can implement option 2. This is to create temporary asp.net core application with .UseHttpLogging() middleware plugged in into pipeline as described here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-logging/?view=aspnetcore-6.0 That way you will know exactly how your request looks like from application which is being requested point of view. Now if you will point your azure function to you temporary app - you should see what gets send
Hope it helps
PROBLEM:2nd call to the graph api fails every time with Bad Request 400 error
If I do the following things, I can never get past #4.
Authenticate with facebook to get authtoken. It redirects back to the page with code querystring param
I get the authtoken from param and make a call to the following url
string url = "https://graph.facebook.com/me?access_token=" + Token; (any graph api call works fine on the first call)
I get json data back. No problem. Now I have the id info from facebook.
I try to repeat the process. Every call to https://graph.facebook.com/me/xxxxxx fails. If I try getting a new token or using the initial token I get Bad Request 400 error.
There must be an order of operations that needs to occur (requests and getting tokens) that I don't understand.
(IT IS NOT AN apikey or apisecret PROBLEM)
What you describe should work. Be sure that when you get the 400-Bad Request error that you catch the WebException and read the content of the Response. It should provide you with the reason the API call failed. The catch portion of your try/catch block would look something like this:
catch (WebException ex)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
string jsonMessageString = reader.ReadToEnd();
}
}
Try this API, it's new and supported. (ie. I support it) See if it's authentication resolves your issue. If you're like me then this would have saved you hours of time fiddling with it. Well worth the 50 bucks.
I'm attempting to make use of the Facebook C# SDK in my existing ASP.NET webforms application. My intent is to allow users to bypass the forms authentication by clicking the Facebook link. The URL on that link is as follows..
facebook
Facebook handles the request and then redirects back to fboauth.aspx which has the following code behind...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Facebook;
using System.Net;
using System.IO;
namespace StorageByMail20
{
public partial class fboauth : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string code;
code = Request.QueryString["code"];
Label1.Text = code;
string token;
string url = "https://graph.facebook.com/oauth/access_token?client_id=000000000000000&redirect_uri=http://localhost:2708/fboauth.aspx&client_secret=000000000000000000000000&code=" + code;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
token = reader.ReadToEnd();
string decodedtoken = HttpUtility.UrlDecode(token);
Facebook.FacebookAPI api = new Facebook.FacebookAPI(decodedtoken);
JSONObject result = api.Get("/first_name");
string name = result.Dictionary["first_name"].String;
Label2.Text = token;
Label3.Text = name;
}
}
}
What I'm attempting to do on this page is the following:
Parse the authorization code from
the Facebook response
Use the authorization code to obtain the
authentication token from Facebook
Make a JSON call using the
authentication code to retreive
information about the user (name,
email, etc...)
Print that information to the page (eventually
I'll do something more interesting
with the data. For now I'm just
trying to get the API interactions
working correctly).
Everything works as intended up to the JSON call. If I comment out that line I'm OK. Otherwise Facebook returns the (400) Bad Request error. Can someone spot where I have gone wrong?
Note: there's a known bug reported here https://github.com/facebook/csharp-sdk/issues that relates to encoding issues with the access token. I think I've addressed that with the my use of UrlDecode. Also, please note that the SDK I'm attemtpting to use is the offical one (currently in Alpha) from Facebook. There are a few other C# SDKs that were created by the community.
Here are some particularly helpful articles I discovered while researching my issue.
onishimura.com/2010/08/11/facebook-c-and-asp-net-mvc-code-samples-for-friends-list-activities-list-and-wall-posts/
multitiered.wordpress.com/2010/08/05/getting-started-with-the-facebook-c-sharp-sdk/
*I removed "http://" from the links above. Evidently I need more reputation points before SO will allow me to include more than two links. Sorry folks!
The SDK you link to on Github is not the Facebook C# SDK, it is a very old and very buggy commit that Facebook submitted and then left alone. There is a much more up to date and widely used project called the Facebook C# SDK here.
It seems that you are doing a lot of leg-work that could easily be handled by either the registration plugin or the javascript sdk (which is the convention when developing Facebook Connect sites.
If you are doing any more Facebook calls server-side I strongly recommend you use the linked C# SDK. Have a look at the sample to see how little coding you have to do.
I am trying to "behind the scenes" log myself into a website, from the VB code behind my ASP.NET website. But I am dumbfounded as to how to do this.
As far as I know I should be using the WebRequest or Webclient class. That is about as much as I know. I am not sure how to use the class.
I want to click a button on my website and have its Click event send a username and password to another website. This other site isot affiliated with mine. I realize the concept may seem stupid, but I plan on taking this further later, but Just need to know this now.
If anyone could give me some code example with explanation or direct me to a good tutorial that would be greatly appreciated!
If it helps at all, the website I am trying to log into is www.Lockerz.com
Thanks!
If the client site uses basic authentication you can add credentials like this:
WebRequest myReq = WebRequest.Create(url);
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
If it uses form login, you can use Fiddler to sniff the data posted on a login, and perform the same request from a HttpWebRequest object. You might want to handle cookies as well if you have to perform multiple requests with the logged in user.
Reference:
Cookies: Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse
Cookies and POST: HttpWebRequest POST and Cookies
Download class: Characters in string changed after downloading HTML from the internet
I've got a problem here.
I've got an ASP.net website hosting a silverlight 2 application.
I'd like the site to communicate to and fro from the silverlight app, and I'm doing this via http requests. Incidentally, if anyone knows a better way, please do tell me.
My server's got the following http listener set up. I copied this from a tutorial site somewhere, since it's mainly experimentation at the moment :
HttpListener listener = new HttpListener ( );
listener.Prefixes.Add("http://localhost:4531/MyApp/");
listener.Start( );
// Wait for a client request:
HttpListenerContext context = listener.GetContext( );
// Respond to the request:
string msg = "You asked for: " + context.Request.RawUrl;
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount (msg);
context.Response.StatusCode = (int) HttpStatusCode.OK;
using (Stream s = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter (s))
writer.Write (msg);
listener.Stop( );
I'm using the following code to send a request :
private void MyButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
b.Content = "Hello World";
Uri serviceUri = new Uri("http://localhost:4531/MyApp/");
WebClient downloader = new WebClient();
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TestDownloadStoriesCompleted);
downloader.DownloadStringAsync(serviceUri);
}
void TestDownloadStoriesCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
TextBox1.Text = e.Result;
}
}
My problem is that I can connect to the webserver from a console application using pretty much the same code (I tested it by setting a breakpoint in the code), however nothing happens when I click the button in silverlight. (I've added the "Hello World" to test that I am indeed connecting the delegate to the button.)
I've read that silverlight needs policies to connect via webclient, but it shouldn't be the case if I'm using the same server and the same domain for both the server and the silverlight application!
Thanks for all your replies!
EDIT : I am recieving this exception :
System.Security.SecurityException ---> System.Security.SecurityException: Security error.
Also, based on what I'm reading apparently to be site-of-origin, the deployment URI of the xap and the request URI must also be of the same port.
However, when I set the properties for the server to be hosted on a specific port, and I set the listener to listen to that same port, it fails with the message that The process cannot access the file because it is being used by another process. I assume it is because the http listener can't listen to the same port being used to host it :|
But then how can I make Silverlight perform host of origin webclient requests?
Since this is only a test add an "else TextBox1.Text=e.Error.ToString();" in your TestDownloadStoriesCompleted handler to see what error you get.
EDIT:
You can't host both the asp.net app and your listener on the same port - you could fix this by using a different port and serving a clientaccesspolicy.xml from your httplistener.
However I think it would make more sense for you to take a look at WCF web services (you add the svc to your asp.net app). Here's a sample.
you can use tools like http://www.fiddler2.com/fiddler2/
to actually see what is going on during the request....
This can give some help for further debugging...
I am now using HTTP handlers for communication. It seems that they will work fine enough for my purpose, although I still want to try out some WCF.