This project has moved and is read-only. For the latest updates, please go here.

mvc example with credentials in db

Dec 10, 2010 at 7:00 PM

Could you please guide me how to save the credentials in the db and then get them  subsequent times with respect to the mvc demo.

Thanks and best regards


Dec 11, 2010 at 3:03 AM


I have a sample in the downloadable source code on how to use LINQ to Twitter with OAuth and MVC.  The only part you need is saving in the database.  Here's some general guidance on how to point you in the right direction.

  1. I assume you already have a database and that you have a table to manage user names and passwords.
  2. If you're using the built-in ASP.NET security provider, you'll need to create a new table that has 3 columns: your application's User ID, OAuthToken, and AccessToken.  The UserID in this new table will hold the user id from the provider table - I think it's a GUID.
  3. If you have your own custom login tables, add two new columns to the user table for OAuthToken and AccessToken.
  4. You can save the ConsumerKey and ConsumerSecret in the config file, since they apply to your application and will always be the same.
  5. When the user first logs into your application, grab the OAuthToken and Access token from the DB and get the ConsumerKey and ConsumerSecret from the config file.
  6. If you want to use the SessionStateCredentials.Load, then build the comma-separated string and pass it to Load.  Alternatively, you can just assign values to the properties of the SessionStateCredentials instance. 
  7. Assign the SessionStateCredentials instance to the MvcAuthorizer after loading the values.
  8. If the user has never authenticated with Twitter, your database won't have an entry for OAuthToken and AccessToken.  If that's the case, then call CompleteAuthorize and BeginAuthorize, just like in the demo.
  9. After authorization is successful, read the OAuthToken and AccessToken from the SessionStateCredentials properties and save them in the database.
  10. If the user has already authorized with Twitter, then your database will have OAuthToken and AccessToken, which you can just read and assign to SessionStateCredentials, as described above.
  11. When the SessionStateCredentials has populated ConsumerKey, ConsumerSecret, OAuthToken, and AccessToken, then the IsAuthorized property will be true.
  12. After IsAuthorized is true, you don't need to perform OAuth authorization with Twitter (no calls to CompleteAuthorize and BeginAuthorize) and can query Twitter right away.

If I left anything out or something is not clear, come back and ask more questions.


Dec 12, 2010 at 1:33 PM

Joe, hi,

Thanks for the detailed reply. I sincerely appreciate it.

I should be able to do all the steps, just two things to confirm:

While reading the OAuthToken from the SessionStateCredentials properties, is the code block to do that "auth.OAuthTwitter.OAuthToken"

All twitter users should have a unique Id , is it auth.UserId

Thanks once again and best regards


Dec 12, 2010 at 5:17 PM


It's better to get OAuthToken and AccessToken from auth.Credentials.  (I'll likely be doing more refactoring of OAuthTwitter and it really should be internal).  Yes, auth.UserId is the place to get the user's Twitter User ID.  Also, auth ScreenName will give you the user's Twitter Screen Name. 


Dec 14, 2010 at 2:47 AM


Thanks for the reply,

If I want to get a list of users who are the logged in users friends or followers, what do I need to do?

 var users=
                (from tweet in twitterCtx.User
                where( tweet.Type == UserType.Friends ||tweet.Type == UserType.Followers)
                     && tweet.UserID == auth.UserId 
                     select new TweetViewModel
                     ImageUrl = ??????
                     ScreenName = ??????
                     UserId =  ???????                     //unique user id

Once I get this info, I would like to send them direct message, so can i just change the UserId value in place of "16761255",

var message = twitterCtx.NewDirectMessage("16761255", "Direct Message Test - " + DateTime.Now);


Dec 14, 2010 at 4:00 AM

This should be two separate queries, one for UserType.Friends and the other for UserType.Followers.  The LINQ to Twitter Type idiom works with a single type per query.  After you perform the queries, you can do a LINQ Union to pull them together.

For this query, you'll be working with User objects and the ScreenName and UserId in your TweetViewModel projection will come from the User.Identifier.ScreenName and User.Identifier.UserID, respectively.  The ImageUrl will be ProfileImageUrl.  As a matter of personal preference and coding style, I would probably use the name "user" instead of "tweet".

Here's a few tips to help discover what's available:

  • To see what type of data is returned in available fields of objects, such as Status and User, you can do a query without a custom projection, just selecting tweet, and inspect the return values in the debugger. 
  • Alternatively, you could look at the downloadable source code that shows the properties for the object.
  • The source code is also browsable in the on-line code to see the properties of each object.  This is geeky, fun, and there's also a diff tool that lets you see what changed between versions. :)
  • While you're coding, you can type tweet (dot) and use Intellisense to see available fields.  Nearly all objects, methods, and properties have XML docs, which show up in Intellisense.
  • I've written plenty of documentation with examples for most of the core functionality.  Some of the newer items are planned for addition.  You'll find most items in the section titled "Making API Calls".

Of course, you're always welcome to ask questions, but I add the tips above hoping they'll be useful for you and others.


Dec 14, 2010 at 6:04 PM

Dear Joe,

Thanks for the detailed mail.

The following is my code block::

IOAuthCredentials credentials = new SessionStateCredentials();

        private MvcAuthorizer auth;
        private TwitterContext twitterCtx;
        GiftSocialEntities storeDB = new GiftSocialEntities();
        public IEnumerable GetAllFriends()

            if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
                credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
                credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];


            credentials.OAuthToken = storeDB.TwitterUsers.Single(tu => tu.Username == User.Identity.Name).OAuthToken;
            credentials.AccessToken = storeDB.TwitterUsers.Single(tu => tu.Username == User.Identity.Name).AccessToken;
            auth = new MvcAuthorizer
                Credentials = credentials
            twitterCtx = new TwitterContext(auth);
            if (auth.IsAuthorized == true)
                var tree = true;
                var friendTweets =
                (from user in twitterCtx.User
                 where user.Type == UserType.Followers && user.UserID == auth.UserId
                 select new TwitterUserInfo
                     ImageUrl = user.ProfileImageUrl,
                     ScreenName = user.Identifier.ScreenName,
                     TwitterId = user.Identifier.UserID
                return friendTweets;


while I debug I can see that auth.IsAuthorized is true but in the next code block I'm getting stuck.

Copied exception::

System.NullReferenceException was unhandled by usercode     [[[[at line "return (string)(((ConstantExpression)expression).Value.ToString());" ]]]] 

Message=Object reference not set to an instance of an object.  Source=LinqToTwitter  StackTrace:       at LinqToTwitter.ExpressionTreeHelpers.GetValueFromExpression(Expression expression) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ExpressionTreeHelper.cs:line 135       at LinqToTwitter.ExpressionTreeHelpers.GetValueFromEqualsExpression(BinaryExpression be, Type memberDeclaringType, String memberName) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ExpressionTreeHelper.cs:line 110       at LinqToTwitter.ParameterFinder`1.VisitBinary(BinaryExpression be) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ParameterFinder.cs:line 90       at LinqToTwitter.ExpressionVisitor.Visit(Expression exp) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ExpressionTreeVisitor.cs:line 68       at LinqToTwitter.ExpressionVisitor.VisitBinary(BinaryExpression b) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ExpressionTreeVisitor.cs:line 176       at LinqToTwitter.ParameterFinder`1.VisitBinary(BinaryExpression be) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ParameterFinder.cs:line 98       at LinqToTwitter.ExpressionVisitor.Visit(Expression exp) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ExpressionTreeVisitor.cs:line 68       at LinqToTwitter.ParameterFinder`1.get_Parameters() in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\Common\ParameterFinder.cs:line 61       at LinqToTwitter.UserRequestProcessor`1.GetParameters(LambdaExpression lambdaExpression) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\User\UserRequestProcessor.cs:line 109       at LinqToTwitter.TwitterContext.GetRequestParameters[T](Expression expression, IRequestProcessor`1 reqProc) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\LinqToTwitter\TwitterContext.cs:line 786       at LinqToTwitter.TwitterContext.Execute[T](Expression expression, Boolean isEnumerable) in D:\projects\0312\LinqToTwitter-81507\LinqToTwitterAg\LinqToTwitter\TwitterContext.cs:line 728  InnerException: 


I even tried LinqToTwitterSource_v2.0.17 but same error.

I do have two followers:

Best  Regards


Dec 15, 2010 at 3:13 AM


There are a few issues here that make this confusing:

  1. auth.UserId is null.  The reason is that LinqToTwitter automatically populates UserId and ScreenName when OAuth authentication occurs.  Since you manually populated the credentials, an OAuth authentication session didn't occur and there's no way for LinqToTwitter to populate UserId.
  2. auth.UserId is readonly, meaning that you can't set it.  Therefore, the workaround is for you to use your own variable, as in "user.UserID == myUserID", where you've set myUserID yourself.  If you save the Twitter UserID and/or Screen name in your database with your other credentials, you can read them from the DB, assign one of them to a variable, and use them in your query.  I don't recall why I made this readonly, but I'll review it and see if it would make more sense to be read-write.
  3. I can see where the exception message you received is totally confusing and doesn't come close to revealing what the real problem is.  I'll take this as an issue to fix in a later release.


Dec 15, 2010 at 3:14 AM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.
Dec 15, 2010 at 4:40 PM


Thanks a lot.

I came across twitter limits( 

Is there a way to handle this such that the user gets to know if and why he is getting problems such as in sending direct messages.

Best Regards


Dec 16, 2010 at 2:11 AM


TwitterContext has 6 properties that give you the rate limits of the last query. RateLimitRemaining, RateLimitCurrent, and RateLimit reset hold general rate limits.  There's also FeaturedRateLimitCurrent, FeaturedRateLimitRemaining, and FeaturedRateLimitReset that apply to API's such as search.


Sep 30, 2013 at 10:15 PM
Hi Joe!
Great software. I am doing something similar but with the pin app. I've found the information you said to save above but I'm not sure how to recreate it when my app starts.

So basically the flow is the user auths via pin. I wanna add them to a textfile (this isn't serious stuff so... hobby work) that I can pull up later and run the app with out an auth.
Sep 30, 2013 at 10:28 PM
Hi Ariankooshesh,

After you complete authorization, the authorizer (sounds like PinAuthorizer in your case), will contain all 4 credentials. Save those credentials and associate them with the logged on user. The next time that user logs in, go to where you saved the credentials and load all 4 of them into the authorizer. When the authorizer contains all 4 credentials, you don't have to go through the authorization process and can do queries and commands right away.

Sep 30, 2013 at 10:43 PM
That worked perfectly. Posting my code here for others.
var auth = new PinAuthorizer()
                Credentials = new InMemoryCredentials
                        ConsumerKey = "**",
                        ConsumerSecret = "**"
            auth.OAuthTwitter.OAuthToken = "***";
            auth.OAuthTwitter.OAuthTokenSecret = "**";

            using (var twitterCtx = new TwitterContext(auth))
                twitterCtx.Log = Console.Out;

                var queryResults =
            from search in twitterCtx.Search
            where search.Type == LinqToTwitter.SearchType.Search &&
                  search.Query == "Linq to twitter"
            select search;
                foreach (var item in queryResults)

                    item.Statuses.ForEach(entry =>
                    "ID: {0, -15}, Source: {1}\nContent: {2}\n",
                    entry.StatusID, entry.Source, entry.Text));