Uploading Photos and Videos to Facebook in Windows Store Apps – Boredom Challenge Day 15

Standard

In this article we’ll be continuing the Facebook integration in Windows Store apps, by looking at how we can upload photos and videos from a Windows Store app to Facebook.

1

Again, we’ll be using Facebook for .NET SDK, and to make things easy I’ll show how this can be done using the example app we’ve created in this article’s part 1. If you wish to follow this article and do it yourself, you can get the first part’s example here. If you don’t, the completed source code is at the end of this article.

Let’s open up the project from part 1. We’ll rename the solution to FacebookAppV3 and then add a few items to the existing ones in MainPage.xaml: Two buttons for selecting an image and a video, an Image for showing the selected image and a textblock for showing the selected video’s information.

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <ProgressBar x:Name="ProgressBar" VerticalAlignment="Top" Visibility="Collapsed"/>
        <Button x:Name="ButtonSignIn" Content="Sign In" HorizontalAlignment="Left" Margin="100,100,0,0" VerticalAlignment="Top" Width="93" Click="ButtonSignIn_Click"/>
        <Image x:Name="ImageUser" HorizontalAlignment="Left" Height="150" Margin="100,143,0,0" VerticalAlignment="Top" Width="150"/>
        <TextBlock x:Name="TextBlockUserName" HorizontalAlignment="Left" Margin="100,298,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="15"/>
        <TextBlock x:Name="TextBlockGender" HorizontalAlignment="Left" Margin="100,321,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="15"/>
        <TextBlock x:Name="TextBlockBirthday" HorizontalAlignment="Left" Margin="100,344,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="15"/>
        <TextBlock x:Name="TextBlockHometown" HorizontalAlignment="Left" Margin="100,367,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="15"/>
        <StackPanel Margin="507,143,0,0" HorizontalAlignment="Left">
            <Image x:Name="ImagePost" MaxWidth="400" MaxHeight="400" HorizontalAlignment="Center"/>
            <TextBlock x:Name="TextBlockVideo" HorizontalAlignment="Left" Margin="10,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" FontSize="15" Visibility="Collapsed"/>
            <TextBox x:Name="TextBoxPost" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Height="150" Width="400" Margin="0,10,0,0"/>
            <Button x:Name="ButtonPost" Content="Post Status" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Click="ButtonPost_Click" Width="124"/>
            <Button x:Name="ButtonPicture" Content="Select Picture" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Click="ButtonPicture_Click"/>
            <Button x:Name="ButtonVideo" Content="Select Video" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Click="ButtonVideo_Click" Width="124"/>
        </StackPanel>
    </Grid>

Then, we will add the click events for ButtonImage and ButtonVideo:

using Windows.Storage.Pickers;
        StorageFile pictureToUpload;
        StorageFile videoToUpload;

        async private void ButtonPicture_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add(".png");
            filePicker.FileTypeFilter.Add(".jpg");
            filePicker.ViewMode = PickerViewMode.Thumbnail;
            filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            pictureToUpload = await filePicker.PickSingleFileAsync();

            if (pictureToUpload != null)
            {
                ButtonPicture.Visibility = Visibility.Collapsed;
                ButtonVideo.Visibility = Visibility.Collapsed;
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(await pictureToUpload.OpenReadAsync());
                ImagePost.Source = bitmapImage;
            }
        }

        async private void ButtonVideo_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker filePicker = new FileOpenPicker();
            filePicker.FileTypeFilter.Add(".wmv");
            filePicker.FileTypeFilter.Add(".avi");
            filePicker.FileTypeFilter.Add(".mp4");
            filePicker.FileTypeFilter.Add(".mov");
            filePicker.ViewMode = PickerViewMode.Thumbnail;
            filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            videoToUpload = await filePicker.PickSingleFileAsync();

            if (videoToUpload != null)
            {
                ButtonPicture.Visibility = Visibility.Collapsed;
                ButtonVideo.Visibility = Visibility.Collapsed;
                TextBlockVideo.Text = "Video to upload: " + videoToUpload.Name;
                TextBlockVideo.Visibility = Visibility.Visible;
            }
        }

As you can see, they are pretty straightforward (and nearly the same). Also, we’ve limited the video file extensions to .wmv, .avi, .mp4 and .mov for simplicity; Facebook supports many video types (full list here). Now, the final thing we need to do is to modify the existing ButtonPost click event to check if a picture or video is selected and post them:

using Windows.Storage.Streams;
        async private void ButtonPost_Click(object sender, RoutedEventArgs e)
        {
            ProgressBar.IsIndeterminate = true;
            ProgressBar.Visibility = Visibility.Visible;
            ButtonPost.IsEnabled = false;
            if (fbAccessToken != null)
            {
                try
                {
                    if (pictureToUpload == null && videoToUpload == null)
                    {
                        var postparameters = new
                        {
                            access_token = fbAccessToken,
                            message = TextBoxPost.Text
                        };
                        dynamic result = await facebookClient.PostTaskAsync("me/feed", postparameters);
                        ProgressBar.IsIndeterminate = false;
                        ProgressBar.Visibility = Visibility.Collapsed;
                        ButtonPost.IsEnabled = true;
                        MessageDialog messageDialog = new MessageDialog("Post successful, check your Facebook page. :)");
                        await messageDialog.ShowAsync();
                    }
                    else if (pictureToUpload != null)
                    {
                        FacebookMediaObject picture = new FacebookMediaObject();
                        picture.ContentType = "image/" + pictureToUpload.FileType.Substring(1, 3);
                        picture.FileName = pictureToUpload.Name;

                        byte[] fileBytes = null;
                        using (IRandomAccessStreamWithContentType stream = await pictureToUpload.OpenReadAsync())
                        {
                            fileBytes = new byte[stream.Size];

                            using (DataReader reader = new DataReader(stream))
                            {
                                await reader.LoadAsync((uint)stream.Size);
                                reader.ReadBytes(fileBytes);
                            }
                        }
                        picture.SetValue(fileBytes);
                        var postparameters = new
                        {
                            access_token = fbAccessToken,
                            message = TextBoxPost.Text,
                            source = picture
                        };
                        dynamic result = await facebookClient.PostTaskAsync("me/photos", postparameters);
                        ProgressBar.IsIndeterminate = false;
                        ProgressBar.Visibility = Visibility.Collapsed;
                        ButtonPost.IsEnabled = true;
                        MessageDialog messageDialog = new MessageDialog("Image successfully posted.");
                        await messageDialog.ShowAsync();
                    }
                    else if (videoToUpload != null)
                    {
                        FacebookMediaObject video = new FacebookMediaObject();
                        video.ContentType = "video/" + videoToUpload.FileType.Substring(1, 3);
                        video.FileName = videoToUpload.Name;

                        byte[] fileBytes = null;
                        using (IRandomAccessStreamWithContentType stream = await videoToUpload.OpenReadAsync())
                        {
                            fileBytes = new byte[stream.Size];

                            using (DataReader reader = new DataReader(stream))
                            {
                                await reader.LoadAsync((uint)stream.Size);
                                reader.ReadBytes(fileBytes);
                            }
                        }
                        video.SetValue(fileBytes);
                        var postparameters = new
                        {
                            access_token = fbAccessToken,
                            description = TextBoxPost.Text,
                            source = video
                        };
                        dynamic result = await facebookClient.PostTaskAsync("me/videos", postparameters);
                        ProgressBar.IsIndeterminate = false;
                        ProgressBar.Visibility = Visibility.Collapsed;
                        ButtonPost.IsEnabled = true;
                        MessageDialog messageDialog = new MessageDialog("Video successfully posted.");
                        await messageDialog.ShowAsync();
                    }
                }
                catch
                {
                    ProgressBar.IsIndeterminate = false;
                    ProgressBar.Visibility = Visibility.Collapsed;
                    ButtonPost.IsEnabled = true;
                    MessageDialog messageDialog = new MessageDialog("The internet has been deleted. There is no Facebook any more. Sorry.");
                    messageDialog.ShowAsync();
                }
            }
            else
            {
                MessageDialog messageDialog = new MessageDialog("Please sign in to Facebook first.");
                await messageDialog.ShowAsync();
            }
        }

The photo – video upload part could have been written smaller (since they share the same code for the most part) but since this is an example I just left them. We use FacebookMediaObject class from Facebook for .NET SDK which represents a media object (photo or video), then set its contents with the selected image or video and then use it for posting. It’s quite simple thanks to Facebook for .NET SDK, really (the alternative is using http multipart/form data upload, which I intend to write an article about).

Our app is complete. You can now run the app, sign in to Facebook and try posting a picture or a video, with the following results:

2

3

Since we’ve posted the picture to “me/photos”, Facebook will automatically create an album for our app and post the pictures there. If you do not want this, you can post to “{Album ID}/photos” to add the picture to a specific album.

You can get the source code of our app here.

Thank you for reading.

Advertisements

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s