Get deals for games with the CheapShark API

by CameronM 7. August 2014 14:24

CheapShark provides a list of deals for games from many of the big suppliers, like Amazon. As part of the service, CheapShark provides an API that allows you to search for deals for a specific game.

In this post, we’ll look at how you can use the CheapShark API to build a Windows Phone 8 “Best-Price” app for games.

Creating our Visual Studio solution

Add a two new folders to the project, one named Models and the other ViewModels. Using nuget, either via the ‘Manage Packages’ context menu, or using the console, add the Microsoft HTTP Client Libraries and the Json.NET packages. These will help us call the web service and then convert the resulting Json.

Querying the CheapShark service

The Url for the CheapShark API is as follows:

http://www.cheapshark.com/api/1.0/games?title=[Search Term]

Using Json2CSharp, copy and paste the Json formatted results from a call to the above Url into the textbox, hit Generate get to resulting C# class. Add this into the Models folder as class named Result.

public class Result
{
    public string gameID { getset; }
    public string steamAppID { getset; }
    public string cheapest { getset; }
    public string cheapestDealID { getset; }
    public string external { getset; }
    public string thumb { getset; }
}

The MainViewModel contains an ObservableCollection of Result objects and a single asynchronous call to the CheapShark web service.

public class MainViewModel : NotifyBase
{
    string baseUrl = "http://www.cheapshark.com/api/1.0/";
 
    public MainViewModel()
    {
    }
 
    private ObservableCollection<Result> _Results;
    public ObservableCollection<Result> Results
    {
        get { return _Results; }
        set
        {
            _Results = value;
            OnPropertyChanged("Results");
        }
    }
 
    public async Task LoadDataAsync(string Title)
    {
        Uri uri = new Uri(string.Format("{0}games?title={1}", baseUrl, Title));
 
        await FetchDataAsync(uri);
    }
 
    private async Task FetchDataAsync(Uri uri)
    {
 
        HttpClient client = new HttpClient();
        try
        {
            var response = await client.GetStringAsync(uri);
 
            var results = JsonConvert.DeserializeObject<List<Result>>(response);
            this.Results = new ObservableCollection<Result>(results);
        }
        catch (System.Net.WebException exception)
        {
            string responseText;
 
            using (var reader = new System.IO.StreamReader(exception.Response.GetResponseStream()))
            {
                responseText = reader.ReadToEnd();
                throw new Exception(responseText);
            }
        }
    }
}

Creating the Windows Phone project

With the basics methods and properties in our PCL, it’s time to add a new Windows Phone App (found in the C#/Store Apps category in Visual Studio).

Add a reference to the CheapShark.PCL project so that we can use our MainViewModel and the nuget package for the Windows Phone Toolkit (just in case!).

Create an application property that exposes our MainViewModel, so that it can be referenced throughout the app. In the App.xaml.cs file add the following code.

private static MainViewModel _ViewModel;
public static MainViewModel ViewModel
{
    get 
    { 
        if(_ViewModel==null)
            _ViewModel = new MainViewModel();
        return _ViewModel;
    }
    set { _ViewModel = value; }
}

Calling the ViewModel from the MainPage

We’ll override the OnNavigatedTo event to link the MainPage with the MainViewModel. This ensure that the ViewModel is available whenever the page gets called. In the MainPage.cs file add the following code.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    this.DataContext = App.ViewModel;
 
    await App.ViewModel.LoadDataAsync("Batman");
 
    base.OnNavigatedTo(e);
}

To start with, we’re going to hard code the search term we’re interested in, to confirm that everything is wired up correctly. 

Now that we’ve linked the ViewModel, it’s time to add the XAML that will display the results. Once again we'll use our derived LongListSelector control, so add a new xmlns named local to your MainPage.xaml as follows:

xmlns:local="clr-namespace:GameSearch.WP"    

Inside the ContentPanel Grid control, add the following mark-up:

<local:LongListSelector ItemsSource="{Binding Results}">
    <local:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0,0,0,12" >
                <Image Source="{Binding thumb}"
                       Width="100" 
                       VerticalAlignment="Top" 
                       HorizontalAlignment="Left"/>
                <StackPanel Margin="12,0,0,0" VerticalAlignment="Top" >
                    <TextBlock Text="{Binding external}" 
                                HorizontalAlignment="Left" 
                                VerticalAlignment="Top" 
                                FontSize="{StaticResource PhoneFontSizeLarge}" />
                    <TextBlock Text="{Binding cheapest}" 
                                HorizontalAlignment="Left" 
                                Style="{StaticResource PhoneTextSubtleStyle}" 
                                Margin="0,0,12,0" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </local:LongListSelector.ItemTemplate>
</local:LongListSelector>

Run the app on your device and test out the results – you should get a list of results that match your search term.

Tags: ,

C# | Windows Phone 8