Using a Public Dropbox File as Data Source for Our Apps – Boredom Challenge Day 5

Standard

If you are an individual developer (and especially a new-grad or a student), chances are you won’t have the resources to have a backend for your app, or maybe you need to just keep a small amount of information that you don’t want to get a server or hosting provider for. In this case, we can use an online storage service (SkyDrive, Dropbox, Google Drive, whatever you wish) to provide read only data for our apps.

1

For example, you want to create a TV app that gets video streams for multiple different TV channels. If you hard-code them into your app, you’ll start getting errors when a TV channel decides to change the address of their stream, and to replace it you have to change the link in your code and publish an update for you application (which will take several days, at least). Instead, you could put the links of the streams in a public file and then read them in your app when your app starts, which will give you the opportunity to change them any time, and your changes will be effective instantly. Heck, don’t just keep the links, keep the name and picture link and any other information you want about that TV channel (you can use XML or Json formatting) and then read all of this data in your app: This way you can instantly add new channels, edit existing ones or remove them whenever you want.

Therefore, if it is not a problem for the file to be publicly visible, this is a free (emphasis on free), quick, easy to use and effective method for providing read only data to our apps. In this article, we’ll use a public Dropbox file and see how we can use this in a Windows Store app.

As always, we start by creating a blank Windows Store App project in Visual Studio.

2

For this example, I wish to display a list of video games that I read from my file. So first we will create a VideoGame class in MainPage.xaml.cs:

    public class VideoGame
    {
        public string Name { get; set; }
        public string PictureLink { get; set; }
        public string Developer { get; set; }
        public string Year { get; set; }
        public double Rating { get; set; }
    }

Then, since I wanted to use Json in my Dropbox file, we will add Json.NET library to our project, by right-clicking References in Solution Explorer and selecting “Manage NuGet Packages” and installing Json.NET.

3

Next, we prepare a simple interface for our app in MainPage.xaml, which will contain a GridView for the game list and a button for refreshing the list. We will also add an item template for the GridView in App.xaml.

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <GridView x:Name="GridViewGames" Margin="100,123,0,50" ItemTemplate="{StaticResource DataTemplateGridViewGames}"/>
        <Button x:Name="ButtonRefresh" Content="Refresh" HorizontalAlignment="Left" Margin="100,80,0,0" VerticalAlignment="Top" Click="ButtonRefresh_Click"/>
    </Grid>
            <DataTemplate x:Key="DataTemplateGridViewGames">
                <Grid Width="450" Height="191" Background="#FF173A6E">
                    <Image HorizontalAlignment="Left" Height="171" Margin="10,10,0,0" VerticalAlignment="Top" Width="125" Stretch="UniformToFill" Source="{Binding PictureLink}"/>
                    <TextBlock Margin="145,20,10,0" VerticalAlignment="Top" FontSize="20" FontFamily="Segoe UI" FontWeight="Light" Text="{Binding Name}"/>
                    <TextBlock Margin="145,62,10,0" VerticalAlignment="Top" FontSize="20" FontFamily="Segoe UI" FontWeight="Light" Text="{Binding Developer}"/>
                    <TextBlock Margin="145,104,10,0" VerticalAlignment="Top" FontSize="20" FontFamily="Segoe UI" FontWeight="Light" Text="{Binding Year}"/>
                    <TextBlock Margin="145,146,10,0" VerticalAlignment="Top" FontSize="20" FontFamily="Segoe UI" FontWeight="Light" Text="{Binding Rating}"/>
                </Grid>
            </DataTemplate>

Now, we need to prepare our file in Dropbox. Create a file in your Dropbox public folder (I named it GameList.json) and fill it like below. Also, get the file’s public link because we’ll be using it in the next step.

[ { "Developer" : "Bethesda Game Studios",
    "Name" : "The Elder Scrolls V: Skyrim",
    "PictureLink" : "http://upload.wikimedia.org/wikipedia/en/1/15/The_Elder_Scrolls_V_Skyrim_cover.png",
    "Rating" : 4.7,
    "Year" : "2011"
  },
  { "Developer" : "Obsidian Entertainment",
    "Name" : "Fallout: New Vegas",
    "PictureLink" : "http://upload.wikimedia.org/wikipedia/en/3/34/Fallout_New_Vegas.jpg",
    "Rating" : 4.8,
    "Year" : "2010"
  },
  { "Developer" : "Firaxis Games",
    "Name" : "XCOM: Enemy Unknown",
    "PictureLink" : "http://upload.wikimedia.org/wikipedia/en/f/fd/XCOM_Enemy_Unknown_Game_Cover.jpg",
    "Rating" : 4.6,
    "Year" : "2012"
  }
  { "Developer" : "4A Games",
    "Name" : "Metro 2033",
    "PictureLink" : "http://upload.wikimedia.org/wikipedia/en/0/07/Metro_2033_Game_Cover.jpg",
    "Rating" : 4.3,
    "Year" : "2010"
  }
  { "Developer" : "Valve Corporation",
    "Name" : "Portal 2",
    "PictureLink" : "http://upload.wikimedia.org/wikipedia/en/f/f9/Portal2cover.jpg",
    "Rating" : 4.9,
    "Year" : "2011"
  }
]

4

Finally, in MainPage.xaml.cs we will write the code that reads our file, converts the contents to a VideoGame list, and sets that list as the source of our ListView:

using Newtonsoft.Json;
using System.Net;
using System.Text;
        public MainPage()
        {
            this.InitializeComponent();
            this.Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            GetGamesFromFile();
        }

        async private void GetGamesFromFile()
        {
            Uri address = new Uri("https://dl.dropboxusercontent.com/u/85324883/GameList.json"); //public link of our file
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
            WebResponse response = await request.GetResponseAsync();
            Stream stream = response.GetResponseStream();
            string content = ReadStreamAsString(stream);
            GridViewGames.ItemsSource = JsonConvert.DeserializeObject(content, typeof(List<VideoGame>));
        }

        public static string ReadStreamAsString(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Count());
            }
        }

        private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
        {
            GetGamesFromFile();
        }

That’s it. Now run the app and you’ll see that we can view the list of games:

5

Now, without closing the application, change the contents of our GameList.json file (add, change or remove some games) and wait for it to be sychronized with dropbox. Then refresh the list:

6

Keep in mind that your file is public so everyone with an internet connection has access to it, and even though it isn’t seen directly anyone can find its link by monitoring the network while your app runs. Therefore, don’t keep anything that you don’t want people to see. 🙂

You can get the source code here.

Thank you for reading. 🙂

Advertisements

3 thoughts on “Using a Public Dropbox File as Data Source for Our Apps – Boredom Challenge Day 5

  1. Mike Lane

    So the Json data is downloaded and then stored in RAM? If the json is not available (outage for example) the data is not cached locally?

    • No, it is not cached locally. You can, however, implement this cache functionality easily by saving the JSon content to a local file and reading from it first. To make it easier, you could even add a version (or date) to your JSon data and check your cache if it is the latest one.

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