Oct 30

I recently needed to use Twitter’s API along with it’s OAuth 1.0 implementation in .NET Core. As part of this work I created a DalSoft.RestClient Handler, and released it as a full SDK.

DalSoft.RestClient already has Handlers to support “application/x-www-form-urlencoded” and “multipart/form-data” so I was half way there. I just needed to find a simple C# example using OAuth 1.0 and Twitter’s API – I found these excellent blog posts:

https://blog.dantup.com/2016/07/simplest-csharp-code-to-post-a-tweet-using-oauth/

https://retifrav.github.io/blog/2017/11/24/csharp-dotnet-core-publish-twitter/

Armed with the code from these blog posts I ported the examples to a DalSoft.RestClient Handler, and released a full Twitter SDK in about 3 hours.

To use you just add the handler with your creds, and access the Twitter API like you would any other API with DalSoft.RestClient.

Here are some examples:

Search

dynamic restClient = new RestClient("https://api.twitter.com/1.1", new Config
(
	new TwitterHandler
	(
		consumerKey: "your-key", 
		consumerKeySecret: "your-secret", 
		accessToken: "your-token", 
		accessTokenSecret: "your-secret"
	)
));

var result = await restClient.Search.Tweets.Query(new { q = "Hello World" }).Get();

Timeline

dynamic restClient = new RestClient("https://api.twitter.com/1.1", new Config
(
	new TwitterHandler
	(
		consumerKey: "your-key", 
		consumerKeySecret: "your-secret", 
		accessToken: "your-token", 
		accessTokenSecret: "your-secret"
	)
));

var result = await restClient.Statuses.Home_Timeline.Get();;

Post Status Update

dynamic restClient = new RestClient("https://api.twitter.com/1.1", new Config
(
	new TwitterHandler
	(
		consumerKey: "your-key", 
		consumerKeySecret: "your-secret", 
		accessToken: "your-token", 
		accessTokenSecret: "your-secret"
	)
));

var result = await restClient.Statuses.Update.Post( new 
{ 
	status = "Posted using DalSoft.RestClient", 
	trim_user = "1" 
});

Post Status Update With Upload

dynamic restClient = new RestClient("https://api.twitter.com/1.1", new Config
(
	new TwitterHandler
	(
		consumerKey: "your-key", 
		consumerKeySecret: "your-secret", 
		accessToken: "your-token", 
		accessTokenSecret: "your-secret"
	)
));

Stream stream = new FileStream("c:\DalSoft1.jpg", FileMode.Open, FileAccess.Read);

var mediaUploadResult =  await restClient.Media.Upload.Post( new { media = stream } );
var statusUpdateResult = await restClient.Statuses.Update.Post( new { status = "Upload" , trim_user = "1", media_ids = mediaUploadResult.media_id } );

To find out more about DalSoft.RestClient including the new TwitterHandler head over to https://restclient.dalsoft.io

Leave a Reply

preload preload preload