Http multipart/form-data Upload in Windows Store Apps – Boredom Challenge Day 16

Standard

If a service you want to use does not have an SDK or library for the programming language you are using, chances are you will be using their REST API to interact with the system. REST API works – excluding the technical specifications – by putting our parameters in the http query string and/or the http header and using Http POST, GET, PUT and DELETE methods to tell the API what we wish to do. For example;

This is the code used if we wish to post something in Facebook for .NET SDK:

var postparameters = new
{
    access_token = fbAccessToken,
    message = TextBoxPost.Text
};
dynamic result = await facebookClient.PostTaskAsync("me/feed", postparameters);

Doing the same action RESTfully would be like this:

                       HttpRequestMessage request = new HttpRequestMessage(
                                System.Net.Http.HttpMethod.Post,
                                new Uri(String.Format("https://graph.facebook.com/me/feed?access_token={0}&message={1}", fbAccessToken, WebUtility.HtmlEncode(TextBoxPost.Text))));

                        var response = await client.SendAsync(request);

As you can see, we set our parameters by adding them to the end of our URL. Actually, the former solution wraps the latter one for us, meaning that Facebook for .NET SDK gets the parameters from us and prepares the http requests itself to reduce our work amount.

Anyway, as I’ve said, we usually need to use REST APIs when we don’t have an SDK or library for the service we want to use. Judging from the code example above, it looks easy, right? Well, yes it is. As long as you have the documentation for it, you wouldn’t have any problems. Unless… you wanted to upload a file. Think of it, I said we put the parameters to the URL, but how do we do this with a file?

This is where multipart/form-data comes in, which is a standard way of encoding the files as byte arrays and sending them over with the http request. However, preparing our file as multipart/form-data is far from trivial, because it is very specific and requires you to delve deep into internet standards definitions to understand (if you wonder, try reading it: RFC 2388). And finally, if you wish to use it in Windows Store apps, another difficulty is that since the .NET classes are different for WinRT, the most common solutions on the internet are not usable in Windows Store apps. As of writing this, I was unable to find a working code sample.

Until now, of course. 🙂 In this article, we’ll see how we can prepare an http multipart/form-data request in Windows Store apps and upload a picture to Facebook with this method.

➤ It took me a complete (and very painful) day to put together the working code…

Advertisement

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.

➤ You can even tag them with your user’s friends…

Handling Suspension and Termination in Windows Store Apps – Boredom Challenge Day 14

Standard

It is not uncommon, especially in mobile app development, for our apps to be suspended or terminated in order to preserve the limited resources of a mobile device. Naturally, we would need to handle these situations in our apps, since there might be some final actions we need to do (such as saving our game’s progress, rolling back a not wholly completed calculation, or storing the contents of a half-filled form) before our app kicks the bucket. We would also need to handle the resuming in order to recover from suspension and termination.

Since Windows 8 emphasizes on being a mobile and power-saving OS, depending on the resources our app could get suspended when a user switches to another app or to desktop. Also, if the resources are low, the OS may deem it fit to outright terminate any suspended apps. Here’s a fancy diagram showing the Windows 8 app life cycle.

1

Apart from the power saving features of the OS, there is one more reason that makes it a good idea to handle suspension and termination in our apps, and this reason is the fact that there are no exit buttons. Our users can just close our apps with a signle flick gesture. We have no chance to give any warnings or prompts to our users like “Are you sure you want to exit?” or “Unsaved changes will be lost” and so on. So, you were uploading a file in the backround, or maybe you haven’t reflected a change you made in the app to the database yet. Well, tough luck, the user has just closed your app. Since the user (rightfully) doesn’t need to care about such things, it is our job to ensure the app overcomes these situations.

However, as you will see, it is quite easy to implement this feature, and in this article we will make a simple Windows Store app that handles suspension, termination and resuming.

➤ To suspend, or not to suspend. That is the question.

Integrating Facebook in Windows Store Apps Part 2 – Boredom Challenge Day 13

Standard

In my previous article, we’ve seen how we can sign in to Facebook, display our user’s data and share status updates in Windows Store apps. In this article, we will take our example app further by reading and displaying the user’s timeline and allowing the user to like/unlike posts, view a post’s comments and also add comments of his/her own.

1

We’ll start with the part 1’s completed app and continue from there. If you wish to go with the article step by step, you can get it here. If you’d rather not, jump to the end of the article for the completed source code. 😉

In this article, we will see how we can create Json classes for Facebook items, how we can read and display our user’s timeline, how we can like/unlike posts and how we can display and add comments. Apparently we have a lot of work to do.

➤ We’re basically making a Facebook client here…

Integrating Facebook in Windows Store Apps Part 1 – Boredom Challenge Day 12

Standard

I believe I don’t even need to tell you why it is a good idea to use Facebook in our applications. 🙂 Apart from the fact that it is the most widely used social media service, we can use it to allow our users to share something from our app (increasing our app’s publicity and usefulness), get posts – pictures – videos about a specific topic for our users (like latest news about a music group), or we can just use it as a user account system (as I’ve mentioned in one of my previous blog posts here). 1 For this purpose, we will use Facebook’s Graph API which allows us to do basically anything we could do on Facebook from inside our apps, and combine it with the Facebook SDK for .NET. Since there is a huge number of different functionalities provided by Graph API, I will be only showing about a handful of them (most used ones), so it is a good idea to keep the documentation for Facebook Graph API and .NET Facebook SDK at your side. 2 I’ve decided to split this article into several parts. In this first part, we will create a Windows Store app that signs the user in with a Facebook account, gets and displays our user’s information and finally allows our user to publish a status update. We’ll also see how we can get a long term access token from Facebook to keep our user signed in even after our app is closed.

➤ After these articles, just please don’t send tons of application requests to others…

Using Graphs and Charts in Windows Store Apps – Boredom Challenge Day 11

Standard

Graphs and charts are very effective tools for visualizing and summarizing data for our users. In apps they not only look cool, but also can be made interactive for further effectiveness. They are also an indispensible feature of financial apps or apps which need to show statistics.

1

In Windows Store apps, there isn’t a default XAML control in Visual Studio for graphs. However, we can easily use other libraries such as WinRT XAML Toolkit or Telerik RadControls for Windows 8 (there are many more). In this article we will create a sample app which uses different types of graphs and charts to show example data (pie chart, bar chart, line chart etc.) using WinRT XAML Toolkit.

➤ Bonus points for creating a “pie chart of my favorite bars” and “bar chart of my favorite pies”…

Integrating Microsoft Account (Live ID) in Windows Store Apps with Live SDK – Boredom Challenge Day 10

Standard

Integrating services like Microsoft Account, Google Account, Facebook, Twitter etc. in our apps undoubtedly provides several benefits, one of which is that we can use them as an account system for our app. From the developers’ point of view, it means not bothering with creating interfaces and functionalities for user profile creation – modification, not needing to mess with usernames and passwords, and also bypassing the secure storage of this information. From the users’ point of view, it means s/he won’t need to create an account for yet another app (which is a very good thing by the way, since users usually dislike creating accounts).

1

To integrate Microsoft Account, we will use Live SDK, which makes it very easy to use several Microsoft services such as SkyDrive, Outlook and Skype. Live SDK is available not only for Windows 8 and Windows Phone, but also for Android and iOS.

In this article, we will create an app that allows the user to sign in with a Microsoft account, displays the user’s name, and makes the user stay signed in until s/he wants to sign out (meaning the user won’t need to sign in everytime the app is opened).

➤ You can also use Live SDK in your website, too…

Using Multiple Item Templates Together: DataTemplateSelector – Boredom Challenge Day 9

Standard

If you spend some time developing Windows Store apps, you will notice that item templates play a major role since we have to use them to display data in many controls (most used ones are GridView and ListView). They give us total control over how we should present information to user, and if designed right, they can single-handedly make our app quite beautiful.

However, as you progress, you will also notice that sometimes just creating an item template is not enough: You may need to customize them based on the data you have. For this purpose, we can do several things that I’ve mentioned in my blog, such as using IValueConverter to bind your data to nearly every property, or creating a custom user control and using it in the item template. Still, however, if the amount of customization you need to do in the item template is way too much, you can instead decide to create several different item templates, and then use them at the same time via the DataTemplateSelector interface.

Screenshot from the example app we will create.

Screenshot from the example app we will create.

If this looks interesting to you, read on and we will create an app that uses the DataTemplateSelector interface. 🙂

➤ You can also use this for multiple GroupStyle or ItemContainerStyle items, but that is a little more advanced topic…

Tip: Passing Multiple Parameters to a New Page in Windows Store Apps – Boredom Challenge Day 8

Standard

Today’s post will be a small tip about how we can pass multiple parameters when navigating to another page in a Windows Store app.

Frame.Navigate() method, which is used for navigating to another page, allows us to send a parameter to the new page like this:

string parameter = "The information that you wish to send to the next page.";
Frame.Navigate(typeof(AnotherPage), parameter);

Then we get the parameter in OnNavigatedTo() function of AnotherPage, like this:

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string passedParameter = e.Parameter.ToString();
        }

So basically we can send any object we want this way. But what if we want to send more than one parameter (which is quite common)? We can not just do it like this:

string parameter = "The information that you wish to send to the next page.";
int parameter2 = 5;
Frame.Navigate(typeof(AnotherPage), argument, argument2);

In this case, we can use application level global variables (but that isn’t good practice, really), or we can use the following way of navigation instead of Frame.Navigate():

string parameter = "The information that you wish to send to the next page.";
int parameter2 = 5;
Window.Current.Content = new AnotherPage(parameter, parameter2);
        public AnotherPage(string firstArgument, int secondArgument)
        {
            this.InitializeComponent();
        }

If we use Window.Current.Content to change the page, we forgo the navigation support, and if you have more than a few pages in our app, going back and forth becomes very impractical and ineffective since you have to do everything manually.

Therefore, we can create a custom class called AnotherPagePayload instead, set our parameters in it, and send that object:

        public class AnotherPagePayload
        {
            public string parameter1 { get; set; }
            public int parameter2 { get; set; }
        }
AnotherPagePayload payload = new AnotherPagePayload();
payload.parameter1 = "Information you want to send to the next page.";
payload.parameter2 = 5;
Frame.Navigate(typeof(AnotherPage), payload);

And then retrieve it like this, in AnotherPage:

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            AnotherPagePayload passedParameter = e.Parameter as AnotherPagePayload;
            string parameter1 = passedParameter.parameter1;
            int parameter2 = passedParameter.parameter2;
        }

That’s it. It’s a small detail, but if you don’t know how to do it when you start developing your app, correcting it later takes some time.

Thank you for reading.

Creating and Using Custom User Controls in Windows Store Apps – Boredom Challenge Day 7

Standard

In a software, user controls are the building blocks of the user interface. A user control is basically a piece of interface and code mixture that is designed for a specific action or purpose, and they provide the interaction between users and our app. They range from simple textblocks to more complex ones such as buttons, sliders, scrollbars, lists and grids, or to even more complex ones such as webviews, maps, pie charts or graphs. As developers, we can customize these user controls as much as they allow, like changing their texts, colors, sizes or even events (like what happens when we click a button or move a slider).

Another aspect of user controls is this: They are repeated a lot. Think what would happen if you wanted to put a button to your app but there weren’t any button controls. You would need to put a rectangle first, then a textblock in front of it, then set a click event, then arrange it’s animations for clicking and so on. Just for one button. Then if you wanted to put another button, you would need to copy all that you’ve prepared and paste it to the place you want, which would result in an absurdly big markup code composed completely of basic controls and a maintenance nightmare.

Some of the XAML user controls in Windows Store apps.

Ok then, now that we know what user controls are and why they’re nice, we’ll come to the custom user control part. Well, apart from default user controls, you can broaden the number of your user controls via adding other libraries (for Windows Store apps, like WinRT XAML Toolkit, Telerik RadControls for Windows 8 or Bing Maps control). However, you might still have a specific part of your interface (unique to your needs) that you need to repeat a lot. If this is the case, we can create a custom user control composed of other user controls that will make our work a lot easier.

Before going on to make an example app, I’d like to make it clear how custom controls are useful in Windows Store apps:
– They increase maintainability. If you want to change how it looks or works later, just make your changes to the custom user control, instead of not using a user control and changing it in every place you’ve used.
– Combined with data binding, they can be very powerful and dynamic.
– Especially useful in places where you don’t have a codebehind file, such as the item templates for gridviews or listviews. Without them, you will not be able to easily put buttons or other interactive user controls in your item template.

Alright alright, enough ranting, let’s create an example app. 🙂 We’ll now create a Windows Store app which will have a custom user control in a GridView item template. It will be a mockup app, where we will show the user his/her incoming friendship requests and the user will either accept or ignore them. 🙂

➤ For bonus points, you can create custom controls and put them on the internet for other people to use…