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.
Related
I am developing an app using ASMX webservice. I don't know how to connect it. I have referred here, https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/asmx.
But I am not clear about how to do this.. please can anyone provide simple app using ASMX webservice...
I will share my code as I also needed to connect to my asmx .NET web service and finally managed to do it after a lot of researching and some days trying things with no luck. I saw many posts explaying other ways to do it, but this is the easiest that I've found and the first one that has worked for me.
(I am connecting to a web service that run's in another Visual Studio in debugging mode)
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/WSLogin");
string wUser = "user";
string wPassword = "password";
string soapstr = string.Format(#"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<WSLogin xmlns=""http://tempuri.org/"">
<wUser>{0}</wUser>
<wPassword>{1}</wPassword>
</WSLogin>
</soap:Body>
</soap:Envelope>", wUser, wPassword);
var response = httpClient.PostAsync("http://localhost:49411/Default.asmx", new StringContent(soapstr, Encoding.UTF8, "text/xml")).Result;
var content = response.Content.ReadAsStringAsync().Result;
You just have to copy this code and modify it to point to your webservice URL, and change the function's name (in my case its WSLogin) and parameters. Or you can just simply copy the entire soap xml that the web service will show if you go to it's asmx file in any browser and then select the function you want to point to.
I read somewhere that iOs needs https to work, but I haven't tried it yet. It works fine on UWP and Android for me.
Hope this helps, this was driving me crazy :)
Edit: you may need this using statements
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Xamarin.Forms;
I have some data in my app's backend that I need to post from my application to another application.
I was thinking about creating form, filling it with the data and auto-posting with javascript within onLoad. But this seems somehow outdated practice for me. What would be the correct way to post from backend to some other application's url using ASP.NET 5 & MVC6 features?
Note: preferably, it should be JSON & RESTful design (controller will be accepting the data on another end), though I don't think this should change anything.
You should be able to use e.g. ordinary HttpClient. This is an example from the MS blog.
using System.Net.Http;
using (var client = new HttpClient())
{
var baseUri = "http://playapi.azurewebsites.net/api/products";
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.GetAsync(baseUri);
if (response.IsSuccessStatusCode)
{
var responseJson = await response.Content.ReadAsStringAsync();
//do something with the response here. Typically use JSON.net to deserialise it and work with it
}
}
This is a GET example, but POST should be pretty similar. If you control both servers, then you can use a fancy thing called Swagger (and Swashbuckle nuget package for .NET). It is kind of WSDL for the REST API, it can generate full proxy to access your API, similar to what WCF does + a nice page with documentation and testing forms.
P.S. Not sure of the state of Swashbuckle for ASP.NET Core, but the pre-release version is available on Nuget as well.
I'm trying to set up OWIN OpenIdConnect to authorize with google provider.
I have used:
http://blogs.msdn.com/b/webdev/archive/2014/03/28/owin-security-components-in-asp-net-openid-connect.aspx
as a tutorial for that, but it's designed for Azure AD provider, so i changed necessary information to google:
Startup.Auth:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(
new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "xxx.apps.googleusercontent.com",
Authority = "https://accounts.google.com",
RedirectUri = "https://localhost:44300/"
});
}
This causes redirect loop error in my browser.
To be sure, I have changed provider to Azure and it works perfectly.
Do you have idea how to fix that? In perfect I would like to integrate it with default membership provider, but for now I'm trying to get it work somehow.
EDIT:
I have found out that problem is in response_mode. Azure returns with POST, and google is returning GET.
Do you have any idea how to:
Make google returns with POST
Make OWIN OpenIdConnect read GET value property? Its separated from a url by '#', not '?'.
OWIN OpenIdConnectHandler only supports POST.
https://accounts.google.com/.well-known/openid-configuration
Doesn't specify response modes, so I am not sure if google+ signin does.
I followed an alternative approch without OWIN, as I tried to avoid using a lot of different libraries.
I basically bult a lightweight implementation especially for authentication against google (see description / documentation):
http://www.dominikamon.com/articles/3091/oidc-lightweight-library-for-aspnet.html
I've uploaded the code to Github:
https://github.com/DominikAmon/Amon.cc.OIDC
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.
I want my asp.net mvc framework system to send an e-mail everytime a certain action (inside a certain controller) is fired off. Are there any third party libraries or .net standard ways to accomplish this?
A more up to date method would be to use System.Net.Mail - this is the 2.0 replacement for System.Web.Mail.
Something like this, called from either a BaseController (if there are other controllers that need this) the actual controller in question.
I have the following code inside a static class to handle mailing simple plain text items from the server:
internal static void SendEmail(MailAddress fromAddress, MailAddress toAddress, string subject, string body)
{
var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
};
var client = new SmtpClient("smtpServerName");
client.Send(message);
}
Obviously, you'd probably want some error handling etc in there - Send can throw an exception for example if the server is refusing connections.
Create a BaseController from which all your other controllers inherits.
In the BaseController override the OnActionExecuted Method and insert your code for sending the email.
public class BaseController : Controller
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Send mail here
base.OnActionExecuted(filterContext);
}
}
The SmtpClient Class with the other System.Net.Mail classes are easily utilized from any .NET program to send mail. You just need to point it to an available and willing SMTP server.
Well its not really hard to send a Email using .NET. You can just send the mail from inside your action.
But, I think we talk little about logging here, and for logging there is a range of 3th party libraries. I know there is one called Log4Net.
Most of these logging frameworks makes it possible to config how logs are stored, and porsibly also a setting to send a email, when it logs something.
But in your scenario, it would just write a plain simple mail function, that sends the mail, when the user enters the action. You can make look at: http://www.developer.com/net/asp/article.php/3096831 - its a demo of sending a mail using .NET - webforms though, but the basic things still apply to MVC.