LinqToTwitter OAuth Unauthorised - c#

I'm following the article in the LinqToTwitter documentation:
http://linqtotwitter.codeplex.com/wikipage?title=Implementing%20OAuth%20for%20ASP.NET%20Web%20Forms&referringTitle=Learning%20to%20use%20OAuth
in order to allow users to log into my C# web application with Twitter.
Here's my code
private WebAuthorizer auth;
private TwitterContext twitterCtx;
protected void Page_Load(object sender, EventArgs e)
{
IOAuthCredentials credentials = new SessionStateCredentials();
if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
{
credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
}
auth = new WebAuthorizer
{
Credentials = credentials,
PerformRedirect = authUrl => Response.Redirect(authUrl)
};
if (!Page.IsPostBack)
{
auth.CompleteAuthorization(Request.Url);
}
twitterCtx = new TwitterContext(auth);
}
protected void AuthorizeTwitterButton_Click(object sender, EventArgs e)
{
auth.BeginAuthorization(Request.Url);
}
However I'm getting a Http 401 from the line:
auth.BeginAuthorization(Request.Url);
Here's the stack trace:
at LinqToTwitter.OAuthTwitter.WebResponseGet(HttpWebRequest webRequest)
at LinqToTwitter.OAuthTwitter.WebRequest(HttpMethod method, String url, String authHeader, IDictionary`2 postData)
at LinqToTwitter.OAuthTwitter.OAuthWebRequest(HttpMethod method, Request request, IDictionary`2 postData, String callback)
at LinqToTwitter.OAuthTwitter.AuthorizationLinkGet(String requestToken, String authorizeUrl, String callback, Boolean forceLogin, AuthAccessType authAccessToken)
at LinqToTwitter.WebAuthorizer.BeginAuthorization(Uri callback, Boolean forceLogin)
at LinqToTwitter.WebAuthorizer.BeginAuthorization(Uri callback)
at TwitterTest.Default.AuthorizeTwitterButton_Click(Object sender, EventArgs e) in c:\Users\agriffiths.SDASOL\Documents\Visual Studio 11\Projects\TwitterTest\TwitterTest\Default.aspx.cs:line 47
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
The credentials have both the ConsumerKey and ConsumerSecret for my Twitter application set.
How can I authorise my users?

There are many reasons that Twitter API returns the HTTP 401 Unauthorized. I've put together a LINQ to Twitter FAQ that has an item on resolving 401's.
The LINQ to Twitter Downloads page has a WebFormsDemos project you can try and there's also a WebForms demo with the downloadable source code.

Related

UserManager Keeps throwing a System.ArgumentNullException

I am trying to implemented the standard Id in AspNetUsers from nvarchar to int. I've manage to get that side working. However my issue is when I try to login I keep getting an error from the UserManager class.
My code is below:
public class UserManager : UserManager<ApplicationUser, int>
{
public UserManager(IUserStore<ApplicationUser, int> store)
: base(store)
{
}
And on the login page I've got
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<UserManager>();
var user = manager.Find(UserName.Text, Password.Text); //This line throws the error
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
Response.Redirect("~/Home.aspx"); }
else
{
FailureText.Text = "Invalid username or password.";
ErrorMessage.Visible = true;
}
}
The error I keep getting is System.ArgumentNullException: Value cannot be null.
Parameter name: manager. Has anyone else come across this issue? Thanks in advance for your help
Stack Trace
[ArgumentNullException: Value cannot be null.
Parameter name: manager]
Microsoft.AspNet.Identity.UserManagerExtensions.Find(UserManager`2 manager, String userName, String password) +221
Account_Login.LogIn(Object sender, EventArgs e) in Login.aspx.cs:17
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628026
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.<ProcessRequestMainAsync>d__14.MoveNext() +5226
Make sure that UserManager is registered in you OWIN context. You should have something like this in your Startup class:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
Also ensure that you have [assembly: OwinStartup(typeof(YourNamespace.Startup))] attribute applied to your web assembly.
the manager.Find() method only search in primary key of table, you must use something like :
Context db = new Context();
if (db.Users.Select(u => u).Where(u => u.Username == Username && u.Pass == Password).ToList().Count() == 1)
{
// login
}
I think the problem comes from the very basic of setups. Can you check that you're user manager is registered in your OWIN context.
And In any case you've extended the Identity ApplicationUser attributes, please do ensure that you've made them public and that they have getters and setters.

c# asp.net System.Net.Mail.SmtpFailedRecipientException

I've a problem. I was sending newsletters to my users, I've more of 10000 email addresses. When i tried to send it with only 6/7 email it worked, now it doesn't work anymore. Why?
I receive this error:
Exception Details: System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.1.1 Too many bad domains
[SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.1.1 <rsv1979#yahoo.com> Too many bad domains]
[SmtpFailedRecipientsException: Unable to send to a recipient.]
System.Net.Mail.SmtpClient.Send(MailMessage message) +1648
Admin_InviaNewsLetter.SendEmailButton_Click(Object sender, EventArgs e) +3013
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
I can't understand why! If u need the code, here it is:
for (int i = 0; i < 501; i++)
{
destinatario = HttpUtility.HtmlDecode(Convert.ToString(Convert.ToString(dt.Rows[i][0])));
msg.To.Add(destinatario);
}
string body = HttpUtility.HtmlDecode(BodyMessageTextBox.Text);
msg.From = new MailAddress("email#address.it");
msg.Subject = HttpUtility.HtmlDecode(ObjectTextBox.Text);
msg.IsBodyHtml = true;
msg.Body = pzzsopra + body + pzzsotto;
SmtpClient sc = new SmtpClient("smtp.sitedomain.it");
sc.Port = 25;
sc.Credentials = new NetworkCredential("email#address.it", "");
sc.EnableSsl = false;
sc.Send(msg);
I hope to find the solution. Thank you before!
This could be a problem with that email address, in which case your loop logic needs to handle such errors, forget that one and proceed onwards. However it might be that your domain is blacklisted by the recipient mail server (or their infrastructure).
Try this for starters - http://www.aweber.com/blog/email-deliverability/whitelisting-feedback-loops.htm
In my experience, it's better to use a trusted 3rd party to send bulk emails. Try mailchimp or google for 'email campaign software' / 'email newsletter software' - there are lots of providers, most of which have API's your ASP.NET site can talk to.

Merging WCF webservice to my web application returns an exception

I would like to add an reference for WCF weather forecast webservice in my application.The thing is I have done everything correctly,but i am lacking somewhere else.It throws an Exception.The Exception message is in the bottom of this post.Somebody out there please help me to fix this.Unles or until fixing this i couln't move to the next phase.
My Source Code is here:
public partial class Testing : System.Web.UI.Page
{
weather.WeatherForecastServiceClient ws = new weather.WeatherForecastServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
SortedDictionary<string, string> objDic = new SortedDictionary<string, string>();
foreach (CultureInfo ObjectCultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
RegionInfo objRegionInfo = new RegionInfo(ObjectCultureInfo.Name);
if (!objDic.ContainsKey(objRegionInfo.EnglishName))
{
objDic.Add(objRegionInfo.EnglishName, ObjectCultureInfo.Name);
}
}
foreach (KeyValuePair<string, string> val in objDic)
{
Country.Items.Add(new ListItem(val.Key, val.Value));
}
}
protected void callwebservice_Click(object sender, EventArgs e)
{
Result.Text = "Result" + ws.GetForecastByCity(City.SelectedItem.ToString(), Country.SelectedItem.ToString());
}
protected void Country_SelectedIndexChanged(object sender, EventArgs e)
{
string[] cities = ws.GetCitiesByCountry(Country.SelectedItem.ToString());
City.DataSource = cities;
City.DataBind();
}
}
This is my Exception
Server Error in '/' Application.
**The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ServiceModel.FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Source Error:
Line 310:
Line 311: public testing.weather.Weather GetForecastByCity(string City, string Country) {
Line 312: return base.Channel.GetForecastByCity(City, Country);
Line 313: }
Line 314: }
Source File: E:\***\WeatherForecast\testing\Service References\weather\Reference.cs Line: 312
Stack Trace:
[FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9442991
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
testing.weather.IWeatherForecastService.GetForecastByCity(String City, String Country) +0
testing.weather.WeatherForecastServiceClient.GetForecastByCity(String City, String Country) in E:\sasi\WeatherForecast\testing\Service References\weather\Reference.cs:312
testing.Testing.callwebservice_Click(Object sender, EventArgs e) in E:\sasi\WeatherForecast\testing\Testing.aspx.cs:40
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272**
You have implemented the service correctly. You can confirm this by running GetCitiesByCountry (it will return a list of cities). It is just that the method GetForecastByCity does not currently work.
Try any of these APIs instead.

Connecting to new Facebook Client with access token

I finally got the right Facebook access token generated from the code. However now I have another problem. Using that access token to fetch user data. Every time I use the token to fetch data, it returns with an exception !String.IsNullOrEmpty(accessToken).
Full stack Trace:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Diagnostics.Contracts.__ContractsRuntime+ContractException: Precondition failed: !string.IsNullOrEmpty(accessToken)
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ContractException: Precondition failed: !string.IsNullOrEmpty(accessToken)]
Facebook.Web.FacebookWebClient..ctor(String accessToken) +137
Facebook_Photo_App._Default.Button1_Click(Object sender, EventArgs e) in Default.aspx.cs:105
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
My code:
To generate the access token on the page load:
string code;
code = Request.QueryString["code"];
//TextBox1.Text = code;
string token;
string url = "https://graph.facebook.com/oauth/access_token?client_id=XXX&redirect_uri=http://apps.facebook.com/dutch-vegas/&client_secret=XXX&code=" + code;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
token = reader.ReadToEnd();
string decodedtoken = token;
TextBox1.Text = decodedtoken;
decodedtoken = decodedtoken.Replace("access_token=", "");
int start = decodedtoken.IndexOf("&");
int count = decodedtoken.Length - decodedtoken.IndexOf("&");
decodedtoken = decodedtoken.Remove(start, count);
On the button implement the Access token to fetch user data
var client = new FacebookClient(decodedtoken);
dynamic me = client.Get("me");
string email = me.email;
string firstname = me.first_name;
string lastname = me.last_name;
string birthday = me.birthday;
TextBox1.Text = email;
Everything seems to be generating correctly. Even after getting the wrong access token (which was a lot shorter than it is suppose to be) for about a week, I got it sorted. And now I am stuck.
I have also noticed in the C# sdk for Facebook you can create multiple instances for FacebookWebClient, FacebookApp, FacebookClient.
Which one do I use and could this be part of my problem?
There are utility classes in the Facebook SDK that deal with the access token for you. They were a little flaky when I looked at them a few weeks ago though.
I ended up using the javascript code instead - http://www.patternwebsolutions.com/2011/03/07/facebooksdk-connect-mvc3/

How can i get a list of the websites in IIS from within a ASPX page using c#?

I'm trying to use
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC/1/Root");
foreach (DirectoryEntry de in root.Children)
{
}
but I keep getting
[COMException (0x80005000): Unknown error (0x80005000)]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +557
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_IsContainer() +42
System.DirectoryServices.ChildEnumerator..ctor(DirectoryEntry container) +36
System.DirectoryServices.DirectoryEntries.GetEnumerator() +36
IISVdir.List(String RootWeb) in c:\Development\Testing\App_Code\IISVdir.cs:116
_Default.Page_Load(Object sender, EventArgs e) in c:\Development\Testing\Default.aspx.cs:11
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +42
System.Web.UI.Control.OnLoad(EventArgs e) +132
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428
In Windows 7/8 go Control Panel / Program And Features / Turn Windows features on or off, and check all items from: Web Managment Tools, (it's include: IIS Managment Service, II 6 Managment Compatibility).
And you can use the code:
public static void OpenWebsite(string name)
{
DirectoryEntry Services = new DirectoryEntry("IIS://localhost/W3SVC");
IEnumerator ie = Services.Children.GetEnumerator();
DirectoryEntry Server = null;
string nombre = "";
while (ie.MoveNext())
{
Server = (DirectoryEntry)ie.Current;
if (Server.SchemaClassName == IIsWebServer)
{
nombre = Server.Properties["ServerComment"][0].ToString();
if (nombre == name)
{
break;
}
}
}
Console.Write(nombre);
}
I'm not too sure what the error is but at a guess it might be installation issue or permissions.
For installation type issues:
http://blogs.msdn.com/b/jpsanders/archive/2009/05/13/iis-7-adsi-error-system-runtime-interopservices-comexception-0x80005000-unknown-error-0x80005000.aspx
For permissions type issues adding something to config like:
<identity impersonate="true" userName="AdminUserName" password="password" />
Or changing the user context that the application pool runs under to one that has local admin rights could work.
Also, the children of IIS://localhost/W3SVC/1/Root will be Virtual Directories or Folders. Websites would be IIS://localhost/W3SVC.

Categories