Push tweets to a Windows Phone 7 device (via push notifications)

April 1st, 2010 skeevs No comments

After reading about how simple it was to push notifications over to a Windows Phone device from Sgt.Conkers article, I dug out some old codes from my archives. I had previously written some codes to retrieve a user’s mentions/replies from Twitter over an interval and to push these tweets as notifications via Prowl to the iPhone. I changed some codes and made it to push to the Microsoft Push Notification Service instead. So,once that message goes to the Service, it’ll push that message to the Windows Phone device.

To make this happen, I have small desktop app which runs and polls twitter on an interval for any new mentions/replies for the user logged on. What’s needed is the :

  • Twitter account username
  • Twitter account password
  • Notification URI to the Windows Phone device (more on this in a bit)

Not forgetting that we also need the actual client application on the Windows Phone device to receive the push notifications. To receive notifications, we need to create a Notification Channel so here we say that we need to have a channel created, and if it already exists then just find it from it’s name.

string channelName = "www.skeevs.com";
HttpNotificationChannel channel;

try
{
	channel = new HttpNotificationChannel(channelName);
	channel.ChannelUriUpdated +=
		(s, e) =>
		{
			Debug.WriteLine(e.ChannelUri.ToString());
		};
	channel.Open();
	channel.BindToShellNotification();
}
catch (NotificationChannelExistsException )
{
	channel = HttpNotificationChannel.Find(channelName);
	Debug.WriteLine(channel.ChannelUri.ToString());
}

The Channel URI is important since this will be the destination URI for the push notifications from the service, which directly indicates the Windows Phone device. Once the application is running on the emulator, the ‘output’ window in your VS2010 IDE will contain the Channel URI. This URI highlighted below is the URI that is entered into the desktop app mentioned above.

You can give it a test by mentioning the @user and should then see the notification appear on the emulator. I’m wondering how is it possible to have the notification message wrap nicely on the screen.

It would probably be easier to see it working for yourself, so I’ve included the source code to this demo : WP7PushTweets.zip

There are 2 folders in the zip:

  1. WP7PushTest – Silverlight client application for the Windows Phone.
  2. WP7PushTweets – Desktop application that retrieves the user’s tweets.

References

  1. Windows Phone 7 Push Notifications – Sgt Conker
  2. Developing an application for Push Notifications
Categories: coding Tags: ,

First steps Windows Phone 7 dev: Building a simple flickr polarized photo viewer

March 28th, 2010 skeevs No comments

I downloaded the development toolkit for Windows Phone 7 as soon as I read about it’s release.First few thoughts was that I should’ve invested way more time into Silverlight development prior to this. The fact is : every Silverlight developer is now a Windows Phone developer!

My first step was to attempt converting photogger into Silverlight. Concept of photogger is simple : it pulls a users photo’s from flickr, and then renders it in polaroid style.

The concept is similar for this : Pull the data via flickr’s API, and then render the photo’s in a list box (polaroid style). The short demo code posted by ScottGu was really helpful in which I based it on.

To implement the ‘polarized’ photo:

  • define the listbox’s item template with a StackPanel that contains an Image and a TextBlock control
  • bind the control’s properties to the class’ properties, eg. {Binding Title}
<ListBox Grid.Column="0" Height="521" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="476">
	<ListBox.ItemTemplate>
	<DataTemplate>
		<StackPanel Orientation="Vertical" Height="200" Width="240" Background="White">
			<Image Source="{Binding ImageSource}" HorizontalAlignment="Center" Height="160"  VerticalAlignment="Top"  Margin="5,3,5,0"/>                        
			<TextBlock Text="{Binding Title}" HorizontalAlignment="Center" TextWrapping="Wrap" Margin="40,0,40,0"  Foreground="Black" FontFamily="Courier New" FontSize="18" FontWeight="Bold"/>                        
		</StackPanel>                    
	</DataTemplate>
	</ListBox.ItemTemplate>
</ListBox>

Next, we define a class that will contain the data returned from the flickr API, based on the attributes and URL documentation. The ImageSource property will format the property values and construct the URL to the photo.

public class Photo
{
	public string Id { get; set; }
	public string Secret { get; set; }
	public string Server { get; set; }
	public string Farm { get; set; }
	public string Title { get; set; }

	public string ImageSource
	{
		get
		{
			return String.Format("http://farm{0}.static.flickr.com/{1}/{2}_{3}_m.jpg",Farm,Server,Id,Secret);

		}            

	}
}

We’ll use the WebClient class to make the actual call to the flickr API.Note that the WebClient call in Silverlight is asynchronous. So to keep the code simple, we’ll just chain 2 requests via the WebClient class(2 requests is necessary at the moment):

  1. Retrieve the user’s actual flickr user id, which is a long string of alphanumerics.
  2. Retrieve the user’s stream of photo’s by passing in the search parameters and user id.
  3. Parse the XML data returned from flickr, and populate a resultset using LINQ for XML.
  4. Bind the ListBox’s ItemSource property to the resultset.

(I’m sure there’s a better way of doing this, but it’s for the sake of simplicity)

private void ClickMeButton_Click(object sender, RoutedEventArgs e)
{
	WebClient flickr = new WebClient();
	// get flickr id first
	flickr.DownloadStringCompleted += new DownloadStringCompletedEventHandler(flickr_getUserName);
	flickr.DownloadStringAsync(new Uri("http://api.flickr.com/services/rest/?method=flickr.urls.lookupUser&api_key=ca082c27ada9e92cda462404588f1c39&url=www.flickr.com/photos/" + UserName.Text));
}

void flickr_getUserName(object sender, DownloadStringCompletedEventArgs e)
{
	if (e.Error != null)
		return;

	XElement xmlUser = XElement.Parse(e.Result);
	string userid = xmlUser.Element("user").Attribute("id").Value;
	WebClient flickr = new WebClient();

	flickr.DownloadStringCompleted += new DownloadStringCompletedEventHandler(flickr_getData);
	flickr.DownloadStringAsync(new Uri("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=<YourFlickrAPIKey>&user_id=" + userid + "&per_page=15&sort=date-taken-desc"));
}

void flickr_getData(object sender, DownloadStringCompletedEventArgs e)
{

	if (e.Error != null)
		return;

	XElement xmlPhotos = XElement.Parse(e.Result);
	listBox1.ItemsSource = from p in xmlPhotos.Descendants("photo")
			select new Photo
			   {
				   Id = p.Attribute("id").Value,
				   Secret = p.Attribute("secret").Value,
				   Server = p.Attribute("server").Value,
				   Farm = p.Attribute("farm").Value,
				   Title = p.Attribute("title").Value
			   };
}

This is the end result:

Source code for this sample project can be downloaded here : WP7FlickrPolarized.zip

Categories: coding Tags: , ,