Skip to content

Instantly share code, notes, and snippets.

@codebycliff
Created September 5, 2013 18:01
Show Gist options
  • Save codebycliff/6453784 to your computer and use it in GitHub Desktop.
Save codebycliff/6453784 to your computer and use it in GitHub Desktop.
A settings Enum that can read from the appSettings section in the web.config through extension methods allowing for strongly typed setting keys and easy retrieval of their values.
using System.Linq;
using TweetSharp;
public class Example {
public static void Main(string[] args) {
// Get setting values
string consumerKey = Setting.TwitterConsumerKey.GetValue<string>();
string consumerSecret = Setting.TwitterConsumerSecret.GetValue<string>();
string oauthToken = Setting.TwitterOAuthToken.GetValue<string>();
string oauthTokenSecret = Setting.TwitterOAuthTokenSecret.GetValue<string>();
int maxTweets = Setting.TwitterMaxTweetsToPull.GetValue<int>();
// Create twitter client and fetch tweets
var service = new TwitterService(consumerKey, consumerSecret, oauthToken, oauthTokenSecret);
var options = new ListTweetsOnHomeTimelineOptions { Count = maxTweets };
var tweets = service.ListTweetsOnHomeTimeline(options);
// Print each tweet to the console
foreach(var tweet in tweets) {
Console.WriteLine(tweet.Text);
}
}
}
using System.ComponentModel;
public enum Setting {
[Description("Twitter:ConsumerKey")]
TwitterConsumerKey,
[Description("Twitter:ConsumerSecret")]
TwitterConsumerSecret,
[Description("Twitter:OAuthToken")]
TwitterOAuthToken,
[Description("Twitter:OAuthTokenSecret")]
TwitterOAuthTokenSecret,
[Description("Twitter:MaxTweetsToPull")]
TwitterMaxTweetsToPull
}
using System.Configuration;
public static class SettingExtensions {
public static string GetDescription(this Setting setting) {
var type = typeof (Setting);
var member = type.GetMember(setting.ToString());
var attrs = member[0].GetCustomAttributes(typeof (DescriptionAttribute), false);
var descAttr = attrs[0] as DescriptionAttribute;
return descAttr != null ? descAttr.Description : null;
}
public static object GetValue(this Setting setting) {
var key = GetDescription(setting);
return key != null ? ConfigurationManager.AppSettings[key] : null;
}
public static T GetValue<T>(this Setting setting) where T : class {
return setting.GetValue() as T;
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="Twitter:ConsumerKey" value="aaaaaaaaaaaaaaaaaaaaaa"/>
<add key="Twitter:ConsumerSecret" value="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"/>
<add key="Twitter:OAuthToken" value="000000000-cccccccccccccccccccccccccccccccccccccccc"/>
<add key="Twitter:OAuthTokenSecret" value="dddddddddddddddddddddddddddddddddddddddddd"/>
<add key="Twitter:MaxTweetsToPull" value="100"/>
</appSettings>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment