Skip to content

Communities

CouchDB Moving Into the Cloud

Apache CouchDB is one of the more promising technologies under the NoSQL distinction.  The project is strongly supported by commercial backers such as Cloudant, who plans to sell cloud services for CouchDB.  By making the non-relational database more scalable, Cloudant hopes it can increase CouchDB adoption.Eric Florenzano's blog on NoSQL technologies spoke highly of Couch DB:
Categories: Communities

Everything You Need to Know About ColdFusion Builder

ColdFusion Builder is the first IDE built specifically for ColdFusion.  Currently in its third beta, CF Builder doesn't use a GUI interface for designing interfaces in WYSIWYG fashion.  Instead, it breaks free from the pre-packaged functionality with extensions to expand the Eclipse-based environment.  An introduction to CF Builder is given by Simon Free, who works with E-Bim. ...
Categories: Communities

IntelliJ Idea9 ActionScript 3/Flex Workflow Part 2

InsideRIA - 7 hours 39 min ago
Welcome to part 2 of my IntelliJ Idea 9 ActionScript 3/Flex workflow series. If you followed part 1 you should have a HelloWorldProject setup along with a HelloWorld module. Now it is time to learn how to compile our SWF and go over the other core features IntelliJ Idea 9 has to offer. Lets not waste any more time, here we go!
Categories: Communities

Is WebKit too fast for its own good?

Let me start by saying I have the utmost respect for the WebKit team, and all the amazing things they have delivered with their rendering engine. Also, very important, for putting pressure on other rendering engine vendors and making them step up. What I would like to talk about today is the rendering speed in WebKit. As we all know, it is very fast and has gotten very good standards...
Categories: Communities

Creating Flex Applications for Mobile Devices

Adobe: References Reference:  Flex and mobile, a whitepaper to create Flex application for mobile devices Mitchell Pronsc...
Categories: Communities

Appcelerator Titanium Releases for General Availability

Ajax Alliance Portal - 9 hours 59 min ago
MOUNTAIN VIEW, CALIF. – March 8, 2010 – Appcelerator®, the leading platform for rapidly developing native mobile, desktop, and iPad applications using web technologies, announced today the release of its flagship product, Appcelerator ...
Categories: Communities

Spectrum Visualization with the HTML5 Audio Data API

Ajaxian - 10 hours 19 min ago

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:
  1.  
  2. <audio src="song.ogg" controls="true"
  3.            onaudiowritten="audioWritten(event);">
  4. </audio>
  5.  

that lets you get access to info such as the spectrum:

PLAIN TEXT JAVASCRIPT:
  1.  
  2.       function audioWritten(event) {
  3.         spectrum = event.mozSpectrum;
  4.        
  5.         var specSize = spectrum.length, magnitude;
  6.        
  7.         // Clear the canvas before drawing spectrum
  8.         ctx.clearRect(0,0, canvas.width, canvas.height);
  9.        
  10.         for ( var i = 0; i <specSize; i++ ) {
  11.           magnitude = spectrum.item(i) * 4000; // multiply spectrum by a zoom value
  12.          
  13.           // Draw rectangle bars for each frequency bin
  14.           ctx.fillRect(i * 4, canvas.height, 3, -magnitude);
  15.         }
  16.       }
  17.  

Add to that the ability to write audio....

PLAIN TEXT JAVASCRIPT:
  1.  
  2. var audioOutput = new Audio();
  3. audioOutput.mozSetup(2, 44100, 1);
  4.  
  5. var samples = [0.242, 0.127, 0.0, -0.058, -0.242, ...];
  6. audioOutput.mozAudioWrite(samples.length, samples);
  7.  

Nice work all around.

Categories: Communities

Favorite Tool and Library Downloads for Silverlight

Adam Kinney has a list with 17 tools that you need to know about when working with 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.

Categories: Communities

Introducing the Earthquake Locator – A Bing Maps Silverlight Application, Part 1

Bobby Diaz has created a nice Bing Maps application that shows the location and relative strength of recent seismic activity.

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.

Categories: Communities

MVVM with Prism 101 – Part 6b: Wrapping IClientChannel

In his last MVVM with Prism post, Mark J. Miller talks about 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:
Categories: Communities

1 Simple Step for Commanding in Silverlight

Christopher Bennage has a blog post about commands in Silverlight 4.

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.

Categories: Communities

Uploading and downloading images from WCF in Silverlight

Uploading and downloading images using a WCF service with 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.

Picture1

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 server

We’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 servoce

To 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 application

The 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.

Picture2

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.

Picture3

Let’s now look at how we can download files.

Downloading files from the server

When 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 changes

For 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 client

Within 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.

Categories: Communities

A syntax highlighting TextBlock for Silverlight 3

Jeff Wilcox has adapted a syntax highlighting engine to generate a syntax highlighting TextBlock control for Silverlight

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

Categories: Communities

Cool demonstration of Silverlight VideoBrush

Tim Greenfield has a demonstration of a fun and novel use of the VideoBrush in Silverlight.

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.

Categories: Communities

360|Flex Day 1 Recap

InsideRIA - 14 hours 22 min ago
360|Flex day 1 recap. I attended a few sessions and give summaries here as well as some general thoughts on how things are going so far.
Categories: Communities

25 Inspiring Silverlight Websites, Videos and Customer Stories

Arturo Toledo has published a list with the coolest Silverlight videos, websites 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.

Categories: Communities

DZone Daily Dose - 3/9

Former Novell CTO Becomes W3C CEO
Categories: Communities

Literate Programming

About a decade ago, I discovered the concept of Literate Programming. It's seductive. The idea is to write elegant documentation that embeds the actual working code. For tricky, complex, high-visibility components, a literate programming approach can give people confidence that the software actually works as advertised. References Reference:  ...
Categories: Communities

R.I.P. Felipe Gaúcho: DZone MVB & Tireless Java Advocate

R.I.P. Felipe Gaúcho: DZone MVB & Tireless Java Advocate The DZone team was very sad to read the news that Felipe Gaúcho had passed away this weekend. Felipe has been an active member of JavaLobby for many years, as well as being a key JUG leader.
Categories: Communities

The Future of Web Applications

The Ajax revolution saw a sea change in web application development. By taking advantage of long-dormant browser capabilities, we were able to take our craft to new levels--reinventing well-established genres, challenging desktop applications, and jump-starting a renaissance in web start-ups. List in Express Request?:  ...
Categories: Communities