4 people like it.
Like the snippet!
Twitter API (Old School)
Old School Way to Query Twitter API(Works in VS 2010, without a Type Provider). Ported from partially working C# snippets on another blog. Fully tested and working. Define your own string parmeters for OAuthToken
OAuthConsumerKey
OAuthTokenSecret
OAuthConsumerSecret
ScreenName
to get this sample to work.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
|
module TwitterFeed
open System
open System.Configuration
open System.IO
open System.Xml
open System.Linq
open System.Xml.Linq
open System.Xml.XPath
open System.Web
open System.Net
open System.Collections.Generic
open System.Text
open System.Security.Cryptography
open System.Runtime.Serialization.Json
// create the signature for a twitter web request
let createSignature (reqMethod : string) (url : string) (parameters : (string*string) list) (oAuthParameters : (string*string) list) (oAuthConsumerSecret : string) (oAuthTokenSecret : string) =
let sigBaseString = System.Text.StringBuilder()
sigBaseString.Append(reqMethod) |> ignore
sigBaseString.Append("&") |> ignore
sigBaseString.Append(Uri.EscapeDataString(url)) |> ignore
sigBaseString.Append("&") |> ignore
List.append parameters oAuthParameters
|> List.sort
|> List.iter (fun (key, value) -> sigBaseString.Append(Uri.EscapeDataString(System.String.Format("{0}={1}&", key, value))) |> ignore)
let signatureBaseString = sigBaseString.ToString().Substring(0, sigBaseString.Length - 3)
let signatureKey = Uri.EscapeDataString(oAuthConsumerSecret) + "&" + Uri.EscapeDataString(oAuthTokenSecret)
let hmacsha1 = new HMACSHA1(ASCIIEncoding().GetBytes(signatureKey))
let signatureString = Convert.ToBase64String(hmacsha1.ComputeHash(ASCIIEncoding().GetBytes(signatureBaseString)))
signatureString
// create the authorization header for a twitter web request
let createAuthorizationHeaderParameter (signature : string) (oAuthParameters : (string*string) list) =
let authorizationHeaderParams = System.Text.StringBuilder()
authorizationHeaderParams.Append("OAuth ") |> ignore
oAuthParameters @ [("oauth_signature", signature)]
|> List.sort
|> List.iteri (fun i (key, value) ->
if i > 0 then authorizationHeaderParams.Append(", ") |> ignore
authorizationHeaderParams.Append(key) |> ignore
authorizationHeaderParams.Append("=\"") |> ignore
authorizationHeaderParams.Append(Uri.EscapeDataString(value)) |> ignore
authorizationHeaderParams.Append("\"") |> ignore)
authorizationHeaderParams.ToString()
// perform a twitter query - be careful to not exceed the twitter limits - 1 per minute should be enough
let query() =
let baseUrl = "https://api.twitter.com/1.1/statuses/home_timeline.json"
let parameters = [("screen_name", ScreenName); ("count", "20")]
let oAuthParameters =
[("oauth_consumer_key", OAuthConsumerKey);
("oauth_nonce", System.Guid.NewGuid().ToString());
("oauth_signature_method", "HMAC-SHA1");
("oauth_timestamp", System.Math.Round(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds, 0).ToString());
("oauth_token", OAuthToken);
("oauth_version", "1.0");]
let url = System.Text.StringBuilder()
url.Append(baseUrl) |> ignore
parameters |> List.iteri (fun i (key, value) ->
if i = 0 then url.Append("?") |> ignore
else url.Append("&") |> ignore
url.Append(key) |> ignore
url.Append("=") |> ignore
url.Append(value) |> ignore)
let signature = createSignature "GET" baseUrl parameters oAuthParameters OAuthConsumerSecret OAuthTokenSecret
let authorizationHeaderParams = createAuthorizationHeaderParameter signature oAuthParameters
let twitterQuery = WebRequest.Create(url.ToString());
twitterQuery.Method <- "GET"
twitterQuery.Headers.Add("Authorization: " + authorizationHeaderParams)
let response = twitterQuery.GetResponse();
let responseText = (new System.IO.StreamReader(response.GetResponseStream())).ReadToEnd()
responseText
|
module TwitterFeed
namespace System
namespace System.Configuration
namespace System.IO
namespace System.Xml
namespace System.Linq
Multiple items
namespace System.Linq
--------------------
namespace Microsoft.FSharp.Linq
namespace System.Xml.XPath
namespace System.Web
namespace System.Net
namespace System.Collections
namespace System.Collections.Generic
namespace System.Text
namespace System.Security
namespace System.Security.Cryptography
namespace System.Runtime
namespace System.Runtime.Serialization
val createSignature : reqMethod:string -> url:string -> parameters:(string * string) list -> oAuthParameters:(string * string) list -> oAuthConsumerSecret:string -> oAuthTokenSecret:string -> string
Full name: TwitterFeed.createSignature
val reqMethod : string
Multiple items
val string : value:'T -> string
Full name: Microsoft.FSharp.Core.Operators.string
--------------------
type string = String
Full name: Microsoft.FSharp.Core.string
val url : string
val parameters : (string * string) list
type 'T list = List<'T>
Full name: Microsoft.FSharp.Collections.list<_>
val oAuthParameters : (string * string) list
val oAuthConsumerSecret : string
val oAuthTokenSecret : string
val sigBaseString : StringBuilder
Multiple items
type StringBuilder =
new : unit -> StringBuilder + 5 overloads
member Append : value:string -> StringBuilder + 18 overloads
member AppendFormat : format:string * arg0:obj -> StringBuilder + 4 overloads
member AppendLine : unit -> StringBuilder + 1 overload
member Capacity : int with get, set
member Chars : int -> char with get, set
member Clear : unit -> StringBuilder
member CopyTo : sourceIndex:int * destination:char[] * destinationIndex:int * count:int -> unit
member EnsureCapacity : capacity:int -> int
member Equals : sb:StringBuilder -> bool
...
Full name: System.Text.StringBuilder
--------------------
StringBuilder() : unit
StringBuilder(capacity: int) : unit
StringBuilder(value: string) : unit
StringBuilder(value: string, capacity: int) : unit
StringBuilder(capacity: int, maxCapacity: int) : unit
StringBuilder(value: string, startIndex: int, length: int, capacity: int) : unit
StringBuilder.Append(value: char []) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: obj) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: uint64) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: uint32) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: uint16) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: decimal) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: float) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: float32) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: int64) : StringBuilder
(+0 other overloads)
StringBuilder.Append(value: int) : StringBuilder
(+0 other overloads)
val ignore : value:'T -> unit
Full name: Microsoft.FSharp.Core.Operators.ignore
Multiple items
type Uri =
new : uriString:string -> Uri + 5 overloads
member AbsolutePath : string
member AbsoluteUri : string
member Authority : string
member DnsSafeHost : string
member Equals : comparand:obj -> bool
member Fragment : string
member GetComponents : components:UriComponents * format:UriFormat -> string
member GetHashCode : unit -> int
member GetLeftPart : part:UriPartial -> string
...
Full name: System.Uri
--------------------
Uri(uriString: string) : unit
Uri(uriString: string, uriKind: UriKind) : unit
Uri(baseUri: Uri, relativeUri: string) : unit
Uri(baseUri: Uri, relativeUri: Uri) : unit
Uri.EscapeDataString(stringToEscape: string) : string
Multiple items
type List<'T> =
new : unit -> List<'T> + 2 overloads
member Add : item:'T -> unit
member AddRange : collection:IEnumerable<'T> -> unit
member AsReadOnly : unit -> ReadOnlyCollection<'T>
member BinarySearch : item:'T -> int + 2 overloads
member Capacity : int with get, set
member Clear : unit -> unit
member Contains : item:'T -> bool
member ConvertAll<'TOutput> : converter:Converter<'T, 'TOutput> -> List<'TOutput>
member CopyTo : array:'T[] -> unit + 2 overloads
...
nested type Enumerator
Full name: System.Collections.Generic.List<_>
--------------------
List() : unit
List(capacity: int) : unit
List(collection: IEnumerable<'T>) : unit
val append : list1:'T list -> list2:'T list -> 'T list
Full name: Microsoft.FSharp.Collections.List.append
val sort : list:'T list -> 'T list (requires comparison)
Full name: Microsoft.FSharp.Collections.List.sort
val iter : action:('T -> unit) -> list:'T list -> unit
Full name: Microsoft.FSharp.Collections.List.iter
val key : string
val value : string
Multiple items
type String =
new : value:char -> string + 7 overloads
member Chars : int -> char
member Clone : unit -> obj
member CompareTo : value:obj -> int + 1 overload
member Contains : value:string -> bool
member CopyTo : sourceIndex:int * destination:char[] * destinationIndex:int * count:int -> unit
member EndsWith : value:string -> bool + 2 overloads
member Equals : obj:obj -> bool + 2 overloads
member GetEnumerator : unit -> CharEnumerator
member GetHashCode : unit -> int
...
Full name: System.String
--------------------
String(value: nativeptr<char>) : unit
String(value: nativeptr<sbyte>) : unit
String(value: char []) : unit
String(c: char, count: int) : unit
String(value: nativeptr<char>, startIndex: int, length: int) : unit
String(value: nativeptr<sbyte>, startIndex: int, length: int) : unit
String(value: char [], startIndex: int, length: int) : unit
String(value: nativeptr<sbyte>, startIndex: int, length: int, enc: Encoding) : unit
String.Format(format: string, [<ParamArray>] args: obj []) : string
String.Format(format: string, arg0: obj) : string
String.Format(provider: IFormatProvider, format: string, [<ParamArray>] args: obj []) : string
String.Format(format: string, arg0: obj, arg1: obj) : string
String.Format(format: string, arg0: obj, arg1: obj, arg2: obj) : string
val signatureBaseString : string
StringBuilder.ToString() : string
StringBuilder.ToString(startIndex: int, length: int) : string
property StringBuilder.Length: int
val signatureKey : string
val hmacsha1 : HMACSHA1
Multiple items
type HMACSHA1 =
inherit HMAC
new : unit -> HMACSHA1 + 2 overloads
Full name: System.Security.Cryptography.HMACSHA1
--------------------
HMACSHA1() : unit
HMACSHA1(key: byte []) : unit
HMACSHA1(key: byte [], useManagedSha1: bool) : unit
Multiple items
type ASCIIEncoding =
inherit Encoding
new : unit -> ASCIIEncoding
member GetByteCount : chars:string -> int + 2 overloads
member GetBytes : chars:char * charCount:int * bytes:byte * byteCount:int -> int + 2 overloads
member GetCharCount : bytes:byte * count:int -> int + 1 overload
member GetChars : bytes:byte * byteCount:int * chars:char * charCount:int -> int + 1 overload
member GetDecoder : unit -> Decoder
member GetEncoder : unit -> Encoder
member GetMaxByteCount : charCount:int -> int
member GetMaxCharCount : byteCount:int -> int
member GetString : bytes:byte[] * byteIndex:int * byteCount:int -> string
...
Full name: System.Text.ASCIIEncoding
--------------------
ASCIIEncoding() : unit
val signatureString : string
type Convert =
static val DBNull : obj
static member ChangeType : value:obj * typeCode:TypeCode -> obj + 3 overloads
static member FromBase64CharArray : inArray:char[] * offset:int * length:int -> byte[]
static member FromBase64String : s:string -> byte[]
static member GetTypeCode : value:obj -> TypeCode
static member IsDBNull : value:obj -> bool
static member ToBase64CharArray : inArray:byte[] * offsetIn:int * length:int * outArray:char[] * offsetOut:int -> int + 1 overload
static member ToBase64String : inArray:byte[] -> string + 3 overloads
static member ToBoolean : value:obj -> bool + 17 overloads
static member ToByte : value:obj -> byte + 18 overloads
...
Full name: System.Convert
Convert.ToBase64String(inArray: byte []) : string
Convert.ToBase64String(inArray: byte [], options: Base64FormattingOptions) : string
Convert.ToBase64String(inArray: byte [], offset: int, length: int) : string
Convert.ToBase64String(inArray: byte [], offset: int, length: int, options: Base64FormattingOptions) : string
HashAlgorithm.ComputeHash(buffer: byte []) : byte []
HashAlgorithm.ComputeHash(inputStream: Stream) : byte []
HashAlgorithm.ComputeHash(buffer: byte [], offset: int, count: int) : byte []
val createAuthorizationHeaderParameter : signature:string -> oAuthParameters:(string * string) list -> string
Full name: TwitterFeed.createAuthorizationHeaderParameter
val signature : string
val authorizationHeaderParams : StringBuilder
val iteri : action:(int -> 'T -> unit) -> list:'T list -> unit
Full name: Microsoft.FSharp.Collections.List.iteri
val i : int
val query : unit -> string
Full name: TwitterFeed.query
val baseUrl : string
Multiple items
type Guid =
struct
new : b:byte[] -> Guid + 4 overloads
member CompareTo : value:obj -> int + 1 overload
member Equals : o:obj -> bool + 1 overload
member GetHashCode : unit -> int
member ToByteArray : unit -> byte[]
member ToString : unit -> string + 2 overloads
static val Empty : Guid
static member NewGuid : unit -> Guid
static member Parse : input:string -> Guid
static member ParseExact : input:string * format:string -> Guid
...
end
Full name: System.Guid
--------------------
Guid()
Guid(b: byte []) : unit
Guid(g: string) : unit
Guid(a: int, b: int16, c: int16, d: byte []) : unit
Guid(a: uint32, b: uint16, c: uint16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : unit
Guid(a: int, b: int16, c: int16, d: byte, e: byte, f: byte, g: byte, h: byte, i: byte, j: byte, k: byte) : unit
Guid.NewGuid() : Guid
type Math =
static val PI : float
static val E : float
static member Abs : value:sbyte -> sbyte + 6 overloads
static member Acos : d:float -> float
static member Asin : d:float -> float
static member Atan : d:float -> float
static member Atan2 : y:float * x:float -> float
static member BigMul : a:int * b:int -> int64
static member Ceiling : d:decimal -> decimal + 1 overload
static member Cos : d:float -> float
...
Full name: System.Math
Math.Round(d: decimal) : decimal
Math.Round(a: float) : float
Math.Round(d: decimal, mode: MidpointRounding) : decimal
Math.Round(d: decimal, decimals: int) : decimal
Math.Round(value: float, mode: MidpointRounding) : float
Math.Round(value: float, digits: int) : float
Math.Round(d: decimal, decimals: int, mode: MidpointRounding) : decimal
Math.Round(value: float, digits: int, mode: MidpointRounding) : float
Multiple items
type DateTime =
struct
new : ticks:int64 -> DateTime + 10 overloads
member Add : value:TimeSpan -> DateTime
member AddDays : value:float -> DateTime
member AddHours : value:float -> DateTime
member AddMilliseconds : value:float -> DateTime
member AddMinutes : value:float -> DateTime
member AddMonths : months:int -> DateTime
member AddSeconds : value:float -> DateTime
member AddTicks : value:int64 -> DateTime
member AddYears : value:int -> DateTime
...
end
Full name: System.DateTime
--------------------
DateTime()
(+0 other overloads)
DateTime(ticks: int64) : unit
(+0 other overloads)
DateTime(ticks: int64, kind: DateTimeKind) : unit
(+0 other overloads)
DateTime(year: int, month: int, day: int) : unit
(+0 other overloads)
DateTime(year: int, month: int, day: int, calendar: Globalization.Calendar) : unit
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : unit
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: DateTimeKind) : unit
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: Globalization.Calendar) : unit
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int) : unit
(+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, kind: DateTimeKind) : unit
(+0 other overloads)
property DateTime.UtcNow: DateTime
DateTime.Subtract(value: TimeSpan) : DateTime
DateTime.Subtract(value: DateTime) : TimeSpan
val url : StringBuilder
val authorizationHeaderParams : string
val twitterQuery : WebRequest
type WebRequest =
inherit MarshalByRefObject
member Abort : unit -> unit
member AuthenticationLevel : AuthenticationLevel with get, set
member BeginGetRequestStream : callback:AsyncCallback * state:obj -> IAsyncResult
member BeginGetResponse : callback:AsyncCallback * state:obj -> IAsyncResult
member CachePolicy : RequestCachePolicy with get, set
member ConnectionGroupName : string with get, set
member ContentLength : int64 with get, set
member ContentType : string with get, set
member Credentials : ICredentials with get, set
member EndGetRequestStream : asyncResult:IAsyncResult -> Stream
...
Full name: System.Net.WebRequest
WebRequest.Create(requestUri: Uri) : WebRequest
WebRequest.Create(requestUriString: string) : WebRequest
property WebRequest.Method: string
property WebRequest.Headers: WebHeaderCollection
Collections.Specialized.NameValueCollection.Add(c: Collections.Specialized.NameValueCollection) : unit
WebHeaderCollection.Add(header: string) : unit
WebHeaderCollection.Add(name: string, value: string) : unit
WebHeaderCollection.Add(header: HttpResponseHeader, value: string) : unit
WebHeaderCollection.Add(header: HttpRequestHeader, value: string) : unit
val response : WebResponse
WebRequest.GetResponse() : WebResponse
val responseText : string
Multiple items
type StreamReader =
inherit TextReader
new : stream:Stream -> StreamReader + 9 overloads
member BaseStream : Stream
member Close : unit -> unit
member CurrentEncoding : Encoding
member DiscardBufferedData : unit -> unit
member EndOfStream : bool
member Peek : unit -> int
member Read : unit -> int + 1 overload
member ReadLine : unit -> string
member ReadToEnd : unit -> string
...
Full name: System.IO.StreamReader
--------------------
StreamReader(stream: Stream) : unit
StreamReader(path: string) : unit
StreamReader(stream: Stream, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(stream: Stream, encoding: Encoding) : unit
StreamReader(path: string, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(path: string, encoding: Encoding) : unit
StreamReader(stream: Stream, encoding: Encoding, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(path: string, encoding: Encoding, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(stream: Stream, encoding: Encoding, detectEncodingFromByteOrderMarks: bool, bufferSize: int) : unit
StreamReader(path: string, encoding: Encoding, detectEncodingFromByteOrderMarks: bool, bufferSize: int) : unit
WebResponse.GetResponseStream() : Stream
More information