Friday, February 27, 2009

Twitter a Exchange Calendar using Powershell and EWS - Exchange 2007

Micro-Blogging is one of the Web 2.0 technologies that has been getting a bit of run of late its one of the tools a seemingly new breed of politicians are using to garner support and awareness of their movements. But its also used by a growing number of everyday people and businesses as a method of pervaying certain messages and other sometimes seemly useless pieces of information. Maybe one of the keys to twitter's success is it fills the gap between availibilty and straight calendaring. I think the scope of what could be done with twitter when you start to intergrate this into traditional communication technology should see this technology expand even more (well as long as we get some creative people pushing the limits).

Exchange mostly provides the same type of information in different formats so using the Twitter API and the Exchange API's you can start to combine the functionality of both systems to start providing different new funcationality. Eg in this sample Im using a script to query an Exchange calendar and then take the text from the current appointment (if there is one) trim it to 140 characters and then post this as a Twitter update. There's logic in the script to first check the current twitter status so the script can be run at intervals and ensure that multiple updates wont be sent for multiple appointments. If you have more then one appointment scheduled at the same time it will just use the first.

So what could you use it for ?.. well any compay,club or small group who has a calendar or events can create twitter feed for these event by simply placeing the events in a Exchange calendar and then let the script read and twitter the status updates. Most of our lives are scripted by our calendar anyway so here a way to save on typing.

How does it work.

There are already a few good Powershell twitter scripts so i grabbed some code out of Mike Ormonds's Sample and started working in some other code. The first thing the scirpt does is goes and grabs the current twitter status. It then goes and queries the mailbox calendar to see if there are any appointments that are in the current time frame. If it find one it then posts the subject of the appointment as a twitter status update. To do the Exchange side I've use Exchange Web Services via some code i've packed into my EWSUtil powershell library (actually im reusing the stuff from the RSS feed script).

Making it work

To make this work you first need a twitter account and a Exchange 2007 Mailbox you need to put your twitter username and password in the following varibles

$twitterusername = "username"
$twitterpassword = "password"

Then put the Email address of the mailbox with the calendar you want to pull the data from and the Exchange Username and password to access this mailbox (or you can use EWS impersonation if you wanted to agregate several mailboxes) in the following varibles.

$emEmailAddress = "twittest@domain.com"
$userName = "twittest"
$password = "Password"
$domain = "domain"

In the

$ExchangeServername = "servername"

put the CAS Servername

If your using a cloud mailbox on Microsoftonline set the domain to blank and use something like (I've built this using a BPOS mailbox)

$emEmailAddress = "twittest@youdomain.microsoftonline.com"
$userName = "twittest@youdomain.microsoftonline.com"
$password = "youpassword"
$domain = ""

To use this you need the EWSUtil library I've put a download of this script here the script itself looks like (note this script is pretty alpha issh so do your own testing first)

$twitterusername = "username"
$twitterpassword = "password"
$ExchangeServername = "servername"
$emEmailAddress = "twittest@domain.com"
$userName = "twittest"
$password = "Password"
$domain = "domain"

function updateTwiterStatus($PostString){

$tweetstring = [String]::Format("status={0}", $PostString )
[System.Net.ServicePointManager]::Expect100Continue = $false
$request = [System.Net.WebRequest]::Create("http://twitter.com/statuses/update.xml")
$request.Credentials = new-object System.Net.NetworkCredential($twitterusername,$twitterpassword)
$request.Method = "POST"
$request.ContentType = "application/x-www-form-urlencoded"
$formdata = [System.Text.Encoding]::UTF8.GetBytes($tweetstring)
$request.ContentLength = $formdata.Length
$requestStream = $request.GetRequestStream()
$requestStream.Write($formdata, 0, $formdata.Length)
$requestStream.Close()
$response = $request.GetResponse()
$reader = new-object System.IO.StreamReader($response.GetResponseStream())
$returnvalue = $reader.ReadToEnd()
$reader.Close()

}

function GetTwitterStatus(){
[System.Net.ServicePointManager]::Expect100Continue = $false
$request = [System.Net.WebRequest]::Create("http://twitter.com/users/show/" + $twitterusername)
$request.Credentials = new-object System.Net.NetworkCredential($twitterusername,$twitterpassword)
$request.Method = "GET"
$request.ContentType = "application/x-www-form-urlencoded"
$response = $request.GetResponse()
$ResponseStream = $response.GetResponseStream()
$ResponseXmlDoc = new-object System.Xml.XmlDocument
$ResponseXmlDoc.Load($ResponseStream)
$StatusNodes = @($ResponseXmlDoc.getElementsByTagName("status"))
$returnStatus = $StatusNodes[0].text
$ResponseXmlDoc.Save("c:\dd.xml")
return $returnStatus.ToString()
}


$casURL = "https://" + $ExchangeServername + "/EWS/Exchange.asmx"
[void][Reflection.Assembly]::LoadFile("C:\temp\EWSUtil.dll")
$ewc = new-object EWSUtil.EWSConnection($emEmailAddress,$false, $userName, $password,$domain, $casURL)
$drDuration = new-object EWSUtil.EWS.Duration
$drDuration.StartTime = [DateTime]::UtcNow
$drDuration.EndTime = [DateTime]::UtcNow.AddMinutes(15)
$upset = 0
[EWSUtil.EWS.DistinguishedFolderIdType] $dType = new-object EWSUtil.EWS.DistinguishedFolderIdType
$dType.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::calendar
$qfolder = new-object EWSUtil.QueryFolder($ewc,$dType, $drDuration,$false,$true)
foreach ($item in $qfolder.fiFolderItems){
if ($item.Location -ne $null){
$twitString = $item.Subject.ToString() + " " + $item.Location.ToString()
}
else{
$twitString = $item.Subject.ToString()
}
if ($twitString.Length -gt 140){$twitString = $twitString.Substring(0,139)}
[String]$currentStatus = GetTwitterStatus
$twitString = $twitString.Substring(0,$twitString.length-1)
write-host $twitString.ToLower().ToString()
write-host $currentStatus.ToLower().ToString()
if ($currentStatus.ToLower().ToString() -ne $twitString.ToLower().ToString()){
if ($statusup -ne 3){$statusup = 1}
$upset = 1
}
else{
$statusup = 3
}
}
if ($statusup -eq 1){
updateTwiterStatus($twitString)
"Twitter Status Updated"
}
else {"Nothing changed since last update"}

1 comment:

Jonny said...

You rock!!!!!
THANKS