Monthly Archives: September 2010

Why Is A Jedi Running For Auckland Councillor

Surely if you were a Jedi, you would have better things to do; such as hunting down Sith Lords, flying spaceships at great speeds in very tight spaces, and convincing people that these aren’t the droids you are looking for.

But no. There is actually a Jedi running for Auckland Super City leadership. I have been told it isn’t a joke. I don’t know how to feel. I quote:

My name is Craig Thomas, I am a Jedi. For too long the Jedi Order and politics have been kept separate. But no more. The Waitemata Board is desperately in need of my infinite Jedi wisdom….Support light-sabre based progress. Do, or do not, there is no try; Vote for Jedi Craig.

He won’t be needing to send me a letter with five people’s names on it to lose my vote…

Also, his picture looks ridiculous.

Cropping Images in Windows Phone 7

Recently I had to do some work in cropping an image programmatically through Windows Phone 7, and while it’s not hard, it wasn’t immediately obvious how to do it, so I thought I would share.

While the Clip property does seem to crop images, the image still remains its original size, making it not a true “crop”. Instead, we’ll use the WriteableBitmap class found as part of Silverlight.

WriteableBitmap takes in a few constructors, including a fixed pixel width/height constructor, and once constructed, you call the .Render() method and pass in UIElements (so that’s Textblocks, Buttons, etc – but most importantly: Image), and a Transform if you want to resize/translate your UIElement.

Therefore, to crop an image, we just need to create a WriteableBitmap with the size of the target cropped area, and pass in a transform that will move the Image to the right area within the crop surface.

After rendering all the UIElements required on the WriteableBitmap, we need to call the .Invalidate() method to force it to redraw its contents and display properly.

Here’s some sample code that crops an image (provided as stream data from, say, a WebService class) to a square:

[sourcecode language="csharp"]
internal static Stream CropSquare(Stream stream)
{
//turn stream into bitmapimage object
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);

//calculate bounding box
int iOriginalWidth = bitmapImage.PixelWidth;
int iOriginalHeight = bitmapImage.PixelHeight;

if (iOriginalWidth == iOriginalHeight)
{
//image is already square – return it
return stream;
}

int smallestSide = (iOriginalHeight < iOriginalWidth) ? iOriginalHeight : iOriginalWidth;

//generate temporary control to render image
Image temporaryImage = new Image { Source = bitmapImage, Width = iOriginalWidth, Height = iOriginalHeight };

//create writeablebitmap
WriteableBitmap wb = new WriteableBitmap(smallestSide, smallestSide);
wb.Render(temporaryImage, new TranslateTransform { X = (iOriginalWidth – smallestSide) / -2, Y = (iOriginalHeight – smallestSide) / -2 });
wb.Invalidate();

//get stream from writeablebitmap
Stream streamResizedImage = new MemoryStream(); //will need to be disposed by whatever is using this method
wb.SaveJpeg(streamResizedImage, smallestSide, smallestSide, 0, 70);
return streamResizedImage;
}
[/sourcecode]

As shown above, we can resize, skew and pretty much do anything we want to an image by passing in the correct combination of translations to the render method of the WriteableBitmap. Note that to convert the WriteableBitmap to a stream, the .SaveJpeg() method was called. I’m not entirely sure which version of Silverlight supports this, or whether it’s a Windows Phone 7 specific extension as I couldn’t find it on MSDN, but it works in the RTM WP7 tools so I imagine it’s not going to be a problem.

Here is a sample project that I made while working all this out, which demonstrates the code I provided in this post in use.

Hope that was helpful!

Dinosaur Club Is Famous

So, the band I play in (Dinosaur Club) has had one of its songs as the backing for a news piece on Stuff.co.nz. It’s kind of weird watching it, because it’s like…it’s like a whole new context.

None of this probably would have happened without twitter – NZStuff put out a request for music, and I just happened to follow them on twitter, and sent the details on, and voila there you go – all parties involved win. I used to really think Twitter was a really dumb medium (140 characters?!), but the sheer real-time and collaborative nature of it, as you can see, is effective.

Awesome times!

Windows Phone 7 ListBoxItem Full Horizontal Fill

Dear Windows Phone 7,

Why is it not enough to set the HorizontalContentAlignment to Stretch on ListBox.ItemContainerStyle in order to allow my ListBoxItems stretch and fill the available space? It apparently works with Silverlight 3.

[sourcecode language="xml"]
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
[/sourcecode]

Thank you, Dan DeSousa, for providing the solution – it turns out that you also need to override the entire Template.

[sourcecode language="xml"]

<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentControl x:Name="ContentContainer"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
[/sourcecode]

Note that I chose not to include most of the bindings for the Template and only implemented the ones I cared about (Content, ContentTemplate and HorizontalContentAlignment).

Now that the RTM WP7 Dev Tools have been released, there is a pretty high chance that this blog post was already obsolete before I made it. Oh well!

EDIT: And just like that, they fixed it; well, they fixed having to define your own template (it did seem very much like a bug). Now all you need to do for horizontal fill is set the ItemContainerStyle to have HorizontalContentAlignment=”Stretch”, as in the first code snippet above, and everything will work just fine.

Sometimes I Wish I Was An Art Historian

Though it’s not very often.

An awesome quote from Donald Rumsfeld, former Defense Secretary, on why American troops were not dispatched to stop the looting of Baghdad museums:

The images you are seeing on television you are seeing over, and over, and over, and it’s the same picture of some person walking out of some building with a vase, and you see it 20 times, and you think, “My goodness, were there that many vases?” (Laughter.) “Is it possible that there were that many vases in the whole country?

You’re right, Donald. There is only room for 19 vases in Iraq.

Search Results For Anonymous Users in Sharepoint 2010

If you’re using SharePoint for any public facing websites and are integrating search and are wondering why search results are not coming up when you’re not logged in to the site, you aren’t alone! Try performing the following simple steps:

In your Sharepoint site, head to Site Settings –> Site Administration –> Search and Offline Availability, and change the Indexing ASPX Page Content setting to “Always index all Webparts on this site”.

Then, head to Central Administration and re-run a search crawl for the appropriate content source.

Once the content has been crawled, you should now be able to get search results when running queries as an anonymous user.

More information on the search visibility settings can be found here.

Zune 4.0

For a product from one of the world’s greatest hardware and software designers, iTunes is an exceedingly ugly program that is really beginning to show its age. From the decidedly QuickTime inspired now playing display block at the top of the screen, to the highly overrated coverflow visuals, iTunes is really not as good looking as it deserves to be, especially considering how good the rest of the Apple products on the market look.

Enter Zune comes in. Outside of the United States, Zune is a bit of a mystery – especially since the Zune HD players aren’t sold here in good old New Zealand. To be quite honest, the first time I saw it was earlier this year when a seminar presenter had it in the background and quickly skimmed over it. Just the single flash though, the quick glimpse of the decidedly “Metro” look and feel immediately grabbed my interest, and I knew I had to find out more about it, and try it.

And now, a few days later, I’m a convert. Zune does a lot of things well, but none better than sitting there looking gorgeous. The now playing screen (and many other elements of Zune) cycles through subtle colour shifts, and lots of large, crisp text and gentle animation and automatically loaded artist images and pictures adorn the screen while you listen to music. Which would you rather spend time looking at?

Apart from looking great, Zune does a few things which iTunes could learn from. My favourite is the “Find Album Info” ability, allowing you to search for albums by artist/title and update the metadata for your music collection very easily. While not every album I own had any relevant search results, the very fact that it allows you do so and has mostly relevant results is a huge timesaver, especially for songs you know belong on an album but have interesting names such as “01″ and “Untitled #5″, or have just been spelt wrong.

Being outside of America, I can’t say anything about how good Zune Pass is (although the concept of unlimited streaming music and 10 free downloads a month for a subscription does sound pretty good), but Zune’s slideshow functionality, while basic, is still beautiful and certainly more exciting than your standard Windows slideshow. The mini-player is absolutely great – with very little screen estate, you get your essential volume controls, play pause next, seek, durations, a snapshot of what songs are coming up next in the playlist, and if you pause it allows you to resume or play either all your music shuffled, a smart DJ list (similar to Apple’s Genius), or a pinned item.

Still, nothing’s perfect; the lack of internet/streaming media support, the rather short length of Smart DJ playlists (although this could be something to do with my eclectic music collection) and the restrictive rating system (sometimes, you don’t just like or hate a song) are all things that should be improved.

With Windows Phone 7 launching later this year, Zune is something I’ll definitely have to get used to. While it certainly has its drawbacks, Zune is definitely the media player that I’d rather have on my computer in the background with friends over – easily being my pick over iTunes, and miles ahead of the UI disaster that is Windows Media Player.

Meet The Spartans: F-

I made the horrifying mistake of attempting to watch this movie the other night. I know for a fact that spoof/parody films have gone decidedly downhill in quality since the heyday of Scary Movie, but I wasn’t quite prepared for just how bad things had gotten.

With a lovely 2% on RottenTomatoes, it’s a serious contender for the worst movie I’ve ever seen; no other movie has managed to make me hate it within the first five ninutes. It isn’t actually funny at all – instead, it’s just a whole bunch of lame pop culture references strung together in an unrelated and haphazard fashion. I also feel that any screenwriter who decides to fill the first five minutes of a movie with not one, not two but at least three “balls” jokes should be taken out to pasture and shot. (One ball joke was already too many in Transformers 2, and it barely got away with it – mainly cause the audience was distracted by Michael Bay slowmotion explosions)

The “celebrity lookalikes” they managed to get were also, really, really bad. Are we really supposed to believe that’s Simon Cowell? He looks nothing like the guy…and neither did Britney Spears, or anyone else they were trying to make fun of.

This movie’s only saving grace is that it’s short – barely getting past an hour (but I promise you won’t make it that far), and roughly 20 minutes of “credits and outtakes”, filled with the jokes that didn’t make the cut to a really bad movie. If a joke was cut from this movie, it’s guaranteed bad.

Don’t. Watch. This. Film.

Windows Phone 7 – Isolated Storage and Persistance

Recently, I’ve added persistence / data storage to my Windows Phone 7 application, making it infinitely more useful and it wasn’t as hard as I expected.

In Windows Phone 7, there’s two kinds of storage. Firstly, there’s the State property bag which you can access from PhoneApplicationService.Current.State. However, as far as I know, this State bag is not saved when the phone is turned off, so for more permanent storage, we need to write to a file. Because WP7 apps run under partial trust, we don’t get access to the underlying file system, but we have access to Isolated Storage.

We can read/write files to Isolated Storage as expected, and there is also the IsolatedStorageSettings.ApplicationSettings dictionary which is a good place to store (you guessed it) application settings or small chunks of string data.

The best way to get your classes into binary data which you can write to Isolated Storage is by using the DataContractSerializer, and decorating the class you want to write to the filesystem with the [DataContract] attribute, and the properties you want to persist with the [DataMember] attribute. To use the DataContractSerializer, you’ll need to add a reference to the System.Runtime.Serialization assembly. Below is a quick example of a class ready to be serialized, and some code to write it to IsolatedStorage.

[sourcecode language="csharp"]

[DataContract]
public class MyClass : INotifyPropertyChanged
{
private DateTime _startTime;
[DataMember]
public DateTime StartTime
{
get { return _startTime; }
set
{
if (value != _startTime)
{
_startTime = value;
NotifyPropertyChanged("StartTime");
}
}
}
}

[/sourcecode]

[sourcecode language="csharp"]

using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(SAVE_PATH, System.IO.FileMode.Create, appStorage))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));
serializer.WriteObject(stream, this);
}
}

[/sourcecode]

Two more gotchas: your DataMembers must be declared as public (partial trust does not allow for private setters to be serialized with the DataContractSerializer), and note that the IsolatedStorage on the beta developer tools doesn’t persist across emulator reboots, so don’t panic if you restart the emulator and you find that the files you’ve written to IsolatedStorage no longer exist.