CouchDB Moving Into the Cloud
Everything You Need to Know About ColdFusion Builder
IntelliJ Idea9 ActionScript 3/Flex Workflow Part 2
Is WebKit too fast for its own good?
Creating Flex Applications for Mobile Devices
Appcelerator Titanium Releases for General Availability
Spectrum Visualization with the HTML5 Audio Data API
The HTML5 specification introduces the and media elements, and with them the opportunity to dramatically change the way we integrate media on the web. The current HTML5 media API provides ways to play and get limited information about audio and video, but gives no way to programatically access or create such media. We present a new extension to this API, which allows web developers to read and write raw audio data.
The above quote is from the Audio Data API extension that joins a bunch of juicy developer work in Firefox 3.7.
Thomas Sturm has taken that API and created a spectrum visualization a kin to some of the great work by Scott Schiller (using Flash).
There is a new onaudiowritten attribute:
PLAIN TEXT HTML:- <audio src="song.ogg" controls="true"
- onaudiowritten="audioWritten(event);">
- </audio>
that lets you get access to info such as the spectrum:
PLAIN TEXT JAVASCRIPT:- function audioWritten(event) {
- spectrum = event.mozSpectrum;
- var specSize = spectrum.length, magnitude;
- // Clear the canvas before drawing spectrum
- ctx.clearRect(0,0, canvas.width, canvas.height);
- for ( var i = 0; i <specSize; i++ ) {
- magnitude = spectrum.item(i) * 4000; // multiply spectrum by a zoom value
- // Draw rectangle bars for each frequency bin
- ctx.fillRect(i * 4, canvas.height, 3, -magnitude);
- }
- }
Add to that the ability to write audio....
PLAIN TEXT JAVASCRIPT:- var audioOutput = new Audio();
- audioOutput.mozSetup(2, 44100, 1);
- var samples = [0.242, 0.127, 0.0, -0.058, -0.242, ...];
- audioOutput.mozAudioWrite(samples.length, samples);
Nice work all around.
Favorite Tool and Library Downloads for Silverlight
I’ve created my list of favorites tools and libraries and posted them to the Downloads page on the Project Rosetta site. After posting the updated list yesterday I realized I missed two big ones: SilverSprite and Balder.
Breaking the new list down into categories, I ended up with 3 Essential, 4 Optional and 10 Specialty downloads.
Introducing the Earthquake Locator – A Bing Maps Silverlight Application, Part 1
The recent wave of earthquakes (no pun intended) being reported in the news got me wondering about the frequency and severity of earthquakes around the world. Since I’ve been doing a lot of Silverlight development lately, I decided to scratch my curiosity with a nice little Bing Maps application that will show the location and relative strength of recent seismic activity.
MVVM with Prism 101 – Part 6b: Wrapping IClientChannel
I could have used the title “Ditching Client Service Proxy” or “Avoiding Add Service Reference”, but that’s not what the meat of the post is about. However, that is essentially the goal of this post. The client service proxy generated when you use “Add Service Reference…” to reference your web service from your client project is used by almost every demo I know. It quickly generates a proxy class for you that at first blush is “the bee’s knees”.
Here you can find all parts from the series:- Part 1: The Bootstrapper
- Part 2: The Shell
- Part 3: Regions
- Part 4: Modules
- Part 5: The View-Model
- Part 6: Commands
1 Simple Step for Commanding in Silverlight
Silverlight 4 is now supporting the commanding that we’ve come to love from WPF. Commanding was a foundational feature for MVVM. It’s what enabled us to bind to methods on our view models.
Uploading and downloading images from WCF in Silverlight
Quite often, when browsing the web, we encounter a situation where we are required to upload a file. When I want to register myself on a forum, I often get the question if I want to upload an avatar. Or when using a social networking site such as Facebook, I can upload pictures of me doing something that probably no one is interested in. The point I’m trying to make here is that when developing in Silverlight, we’ll also come in a situation where we want our users to upload files such as images to the server. Next to uploading, users may want to download files such as images, which are stored as a physical file on the server as well.
In both cases, WCF can help us out, allowing us to create services that are capable of working with an uploaded file as well as processing a requested file for download. In this article, I’ll be showing a sample Silverlight application where users can upload and download images from using a WCF service. The interface is very simple; a screenshot is shown below.
Included with this article is the sample code, which can be downloaded here. We’ll be using this code to show how the upload and download process works.
Uploading a file to the serverWe’ll start by looking at the upload process. We need to write code both on the server side and on the client side.
Server-side: a WCF servoceTo allow a Silverlight application to send files to the server-side and store these on the file system of the server, we’ll start by creating a WCF service. In the sample code, this service is named PictureService. In the service contract, IPictureService, we define a method called Upload, which accepts an instance of PictureFile.
[ServiceContract]
public interface IPictureService
{
[OperationContract]
bool Upload(PictureFile picture);
}
The PictureFile class is defined as DataContract; it defines two fields namely the filename and the contents of the file. The latter is stored as a byte stream. Both these properties are attributed with the DataMemberAttribute, meaning that both will travel over the wire when send from and to the service.
[DataContract]
public class PictureFile
{
[DataMember]
public string PictureName { get; set; }
[DataMember]
public byte[] PictureStream { get; set; }
}
Now that we have defined the contract for the service, let’s take a look at the implementation. The logic here relies on System.IO. Basically, the Silverlight client application will upload a file as a stream of bytes (using an instance of the above defined class PictureFile). This stream of bytes is to be converted to a file on the server. The following code does just that: using a BinaryWriter, we grab the sent bytes and save them as a file. The location of the upload directory is stored here in the web.config.
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class PictureService : IPictureService
{
public bool Upload(PictureFile picture)
{
FileStream fileStream = null;
BinaryWriter writer = null;
string filePath;
try
{
filePath = HttpContext.Current.Server.MapPath(".") +
ConfigurationManager.AppSettings["PictureUploadDirectory"] +
picture.PictureName;
if (picture.PictureName != string.Empty)
{
fileStream = File.Open(filePath, FileMode.Create);
writer = new BinaryWriter(fileStream);
writer.Write(picture.PictureStream);
}
return true;
}
catch (Exception)
{
return false;
}
finally
{
if (fileStream != null)
fileStream.Close();
if (writer != null)
writer.Close();
}
}
}
By default, WCF only accepts messages with a maximum length of 65536 bytes. This is however, not enough for sending normal files to the server. We should therefore make some configuration changes to our service so that the larger uploads are accepted. To do so, I’m specifying a custom binding configuration for the basic HTTP binding. Here, I’m allowing uploads of 2.000.000 bytes, meaning 2MB, you can of course specify another value here.
<bindings>
<basicHttpBinding>
<binding name="PictureBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
<readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
</binding>
</basicHttpBinding>
</bindings>
Because this WCF service is to be connected to from Silverlight, the binding itself should of course be a BasicHttpBinding and not a wsHttpBinding which is the default for WCF.
At this point, our service has all it needs to start accepting uploads from Silverlight. Let’s turn our attention to the client now.
Client side: the Silverlight applicationThe first thing we should do is letting our Silverlight application know about the PictureService by adding a service reference to the service within the Silverlight project. Here I set the namespace to PictureService.
Visual Studio creates for us a proxy. Included in the client proxy is a client side copy of the PictureFile class.
To allow the user of the application to upload a file from the local file system, we use the OpenFileDialog class. Within Silverlight, this class gives us a read-only stream to a local file. Apart from reading the contents of the file, Silverlight can’t perform other actions on the file such as deleting or renaming. Using the OpenRead method, we get access to the above mentioned stream which we can then read out using the Read method into a byte array.
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "JPEG files|*.jpg";
if (openFileDialog.ShowDialog() == true)
{
Stream stream = (Stream)openFileDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
string fileName = openFileDialog.File.Name;
}
We’re can now try uploading the file. We therefore create a new instance of the PictureFile class, passing in a name for the file and the byte array.
PictureService.PictureFile pictureFile= new FileUpAndDownload.PictureService.PictureFile();
pictureFile.PictureName = fileName;
pictureFile.PictureStream = bytes;
All that’s left now is creating a proxy instance. As with all other service communication within Silverlight, service communication works asynchronously. Therefore, we define a callback which will be invoked when the upload is finished.
PictureService.PictureServiceClient client = new FileUpAndDownload.PictureService.PictureServiceClient();
client.UploadCompleted += new EventHandler
<FileUpAndDownload.PictureService.UploadCompletedEventArgs>(client_UploadCompleted);
client.UploadAsync(pictureFile);
In the callback, we can check if the service interaction went OK or if there where any errors.
void client_UploadCompleted(object sender, FileUpAndDownload.PictureService.UploadCompletedEventArgs e)
{
if (e.Error == null)
{
if (e.Result)
{
ResultTextBlock.Text = "Upload succeeded :)";
}
else
{
ResultTextBlock.Text = "Upload failed :(";
}
}
}
With that, we are ready to try our upload process. The image below shows the upload working.
Let’s now look at how we can download files.
Downloading files from the serverWhen it comes to downloading images, we could in most cases solve things by simply using a link to the original file and sending this link back to the client Silverlight application. However, in some cases, this link can’t be created. Take for example the case where images are stored within a database. Or another possibility here is that images are stored on a non-publicly available folder on the server. In both these cases, we need to send the byte information to the client using a service again. In the client Silverlight application, we can then recreate the file and use it within our app. Let’s look at the code to do this.
Service changesFor this sample, we’ll allow the user to enter the name of the picture he or she wishes to download, so we’ll pass in a string as argument for a new method, quite logically named Download, on our WCF service. In the service contract, I added the following code:
[OperationContract]
PictureFile Download(string pictureName);
As we can see here, this operation defines that we are sending to the client an instance of the PictureFile class (the same class as we used for the upload process). The file that will thus be sent to the client, will be sent as a byte array. In the implementation code, we check if the file exists first. If it does, we use a BinaryReader to read the contents of the file, create he PictureFile instance and return it.
public PictureFile Download(string pictureName)
{
FileStream fileStream = null;
BinaryReader reader = null;
string imagePath;
byte[] imageBytes;
try
{
imagePath = HttpContext.Current.Server.MapPath(".") +
ConfigurationManager.AppSettings["PictureUploadDirectory"] +
pictureName + ".jpg";
if (File.Exists(imagePath))
{
fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
reader = new BinaryReader(fileStream);
imageBytes = reader.ReadBytes((int)fileStream.Length);
return new PictureFile() { PictureName = pictureName, PictureStream = imageBytes };
}
return null;
}
catch (Exception)
{
return null;
}
}
The service’s configuration code does not need to be changed for this new operation.
Changes to the Silverlight clientWithin the Silverlight client, update the web service reference. Visual Studio will update the proxy class, making the new Download method available. Upon clicking the button, we’ll launch a request to the service asynchronously, passing in the filename.
private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
PictureService.PictureServiceClient client =
new FileUpAndDownload.PictureService.PictureServiceClient();
client.DownloadCompleted +=
new EventHandler<FileUpAndDownload.PictureService.DownloadCompletedEventArgs>(client_DownloadCompleted);
client.DownloadAsync(FileNameTextBox.Text);
}
Upon completion of the service call, the callback method is invoked. If no errors occur, we receive a PictureFile instance, containing the bytes of the requested file. Here we know that the file is in fact an image, so we use it to display the picture in an Image control.
BitmapImage image = new BitmapImage();
if (e.Error == null)
{
if (e.Result != null)
{
ImageDownloadService.ImageDownload imageDownload = e.Result;
MemoryStream stream = new MemoryStream(imageDownload.Image);
image.SetSource(stream);
ResultImage.Source = image;
}
else
{
ErrorTextBlock.Text = "No image with that name exists";
}
}Summary
To send files from and to a service from within a Silverlight application, we can use a WCF service, which accepts a byte array, optionally wrapped in a class like we did here with the PictureFile class. In this example, we looked at how to do this with images; however, the method is similar for other file types.
Gill Cleeren is Microsoft Regional Director (www.theregion.com), MVP ASP.NET, INETA speaker bureau member and Silverlight Insider. He lives in Belgium where he works as .NET architect at Ordina. Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF. He also leads Visug (www.visug.be), the largest .NET user group in Belgium. He’s the author of the upcoming book called Silverlight 4 Data and Services Cookbook. You can find his blog at www.snowball.be.
A syntax highlighting TextBlock for Silverlight 3
Add the control assembly to your Silverlight project. Then, add an XMLNS prefix to your Silverlight page where you’d like to use the control.
There are two properties of interest that should be set or bound: SourceCode (the actual source text), and SourceLanguage
Cool demonstration of Silverlight VideoBrush
Silverlight provides a variety of brushes that can be used to paint just about any area in your app: from text to shapes to borders. The most common brushes are for painting color and images: SolidColorBrush,LinearGradientBrush, RadialGradiantBrush, and ImageBrush.However, today I paired the less common VideoBrush with an unusual visual element.
360|Flex Day 1 Recap
25 Inspiring Silverlight Websites, Videos and Customer Stories
As part of the CRE8 Conference last week in Miami, August de los Reyes and I presented a collection of the cool videos, websites and customer stories. Here is a great list for you with the best of best in Silverlight and UX.