Here’s another SQL Server 2005 geek out moment, a CLR SPROC that tweets to Twitter. Big shoutout to Danny Battison for sharing the C# code to post to Twitter. This is what got me started on the C# side of things. Also, you can skip all my ramblings here and just download code here and fire it up. The zip file contains all the source code, the compiled assembly file, and install.sql that shows you how to hook this up.
Being the SQL junky that I am, I was interested in trying out SQL Server’s new CLR Stored Procedures. A CLR sproc is a stored procedure that is able to use .net code that you’ve compiled into an assembly file. For you classic ASP heads out there, think of the ASP page being the sproc, and the .net assembly being your COM object ( cringe, let’s talk about classic ASP ). While there are plenty of great articles on writing CLR stored procedures, I’m going to breeze through the code that makes up this project.
First make a .net class library that will be compiled into an assembly file.
using System;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
/// <summary>
/// This assembly will be used by a SQL2005 SPROC to communicate
/// with twitter.com
/// </summary>
public sealed class tweetsproc
{
/*
* TWITTER CODE BORROWED FROM :
* http://www.dreamincode.net/code/snippet2556.htm
*
* A function to post an update to Twitter programmatically
* Author: Danny Battison
* Contact: gabehabe@hotmail.com
*/
/// <summary>
/// Post an update to a Twitter acount
/// </summary>
/// <param name="username">The username of the account</param>
/// <param name="password">The password of the account</param>
/// <param name="tweet">The status to post</param>
[Microsoft.SqlServer.Server.SqlProcedure(Name = "PostTweet")]
//public static void PostTweet( string username, string password, string tweet)
public static void PostTweet( SqlString username,
SqlString password,
SqlString tweet)
{
try
{
// encode the username/password
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username.ToString() + ":" + password.ToString()));
// determine what we want to upload as a status
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet.ToString());
// Create a WebPermission.
WebPermission myWebPermission1 = new WebPermission();
// Allow Connect access to the specified URLs.
myWebPermission1.AddPermission(NetworkAccess.Connect,new Regex("http://www\\.twitter\\.com/.*",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline));
myWebPermission1.Demand();
// connect with the update page
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
// set the method to POST
request.Method = "POST";
request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
// set the authorisation levels
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType = "application/x-www-form-urlencoded";
// set the length of the content
request.ContentLength = bytes.Length;
// set up the stream
Stream reqStream = request.GetRequestStream();
// write to the stream
reqStream.Write(bytes, 0, bytes.Length);
// close the stream
reqStream.Close();
// Let's get the Response from Twitter
var webresp = request.GetResponse();
// Let's read the Response
var sread = new StreamReader( webresp.GetResponseStream() );
// Use SqlContext to return data to the QueryAnalyzer results window
SqlContext.Pipe.Send( sread.ReadToEnd() );
}
catch (Exception exc)
{
// send error back
SqlContext.Pipe.Send(exc.Message);
}
}
}
Here’s the app.config for this assembly.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<trust level="Full" processRequestInApplicationTrust="true" originUrl="" />
</system.web>
</configuration>
Once you build this project, you should have your assembly ( tweetsproc.dll ) which will be used by your CLR Sproc. Now it’s time to do some SQL server work.
Enable CLR access for SQL server
EXEC sp_configure @configname = 'clr enabled', @configvalue = 1 RECONFIGURE WITH OVERRIDE GO
Create the SQL Assembly
CREATE ASSEMBLY tweetsproc_clr_assembly from 'C:\Users\eric\Desktop\blog\tweetsproc.dll' WITH PERMISSION_SET = EXTERNAL_ACCESS GO
Create your SPROC
CREATE PROC tweetsproc_tweet( @username as nvarchar(50), @password as nvarchar(50), @tweet as nvarchar(140) ) AS -- [Assembly Name].[Class Name].[CLR function Name] EXTERNAL NAME tweetsproc_clr_assembly.tweetsproc.PostTweet GO
Tweet from a sproc
EXEC tweetsproc_tweet 'TwitterUsername', 'TwitterPassword', 'Hey @ericfickes, I''m tweeting from my database too!'
Running this sproc returns the XML response from Twitter.
That’s one sample CLR SPROC in the bank! Feel free to download this code and try it out yourself. I’d love to get some feedback on anybody looking to use this for real. While tweeting from a stored procedure probably isn’t a hot topic for anybody, this is a nice teaser for what you can do with CLR sprocs now.
Inside this zip you’ll find this.
- install.sql is everything you need to install this on your database
- tweetsproc.dll is the twitter assembly used by the sproc
- tweetsproc folder is the .net class library project



Nice post! I'm not familiar with the Twitter API. Is 'tweetsproc' broadcasting a users' Twitter password in plaintext?
Thanks Free. The user and password get encoded into a Base64 string.
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username.ToString() + ":" + password.ToString()));
Just wanted to say I loved the information you had here will deff help me out. Thanks!
Hallo from Australia! I have found your link on alltheweb. Handful content! Angela E. King x
Pingback: sql stored procedure
If you add support for lists it would be perfect. Just add the list as an optional parameter
Feel free to download the code and extend how you wish. If you make anything cool I'd love to hear about it.
If you add support for lists it would be perfect. Just add the list as an optional parameter
Hey Bruce,
What sort of list feature are you looking for?
Is this sort of post going to continue working when the new OAuth security is in place for Twitter (in ten days).
Hey Keith,
I'm not really sure. Last I read they were closing the HTTP api down in June? This particular widget has fallen low on my priorities list so I'll have to come back to this one.
Hello. The BASIC Auth mechanism was scheduled to be shutdown on June 30th but has been extended 6 weeks to August 16th.
You can read about it here: http://countdowntooauth.com/
and here: http://dev.twitter.com/announcements
OAuth does take a bit more work and setup but is certainly doable. Without trying to take away from the project described in this blog, I will say that I have a SQLCLR project called SQL# (SQLsharp) that includes quite a few Twitter functions and works with OAuth. It is in a transitional phase at the moment since it currently accepts Usernames and Passwords but in the end will most likely accept Auth Tokens and Secrets. I do not give away the source code but the Twitter functions are free. If interested you can download SQL# at:
http://www.SQLsharp.com/