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

GoodReads API

by CameronM 6. August 2014 13:57

GoodReads provides a way to discover books you might like based on your reading habits. You can create digital bookshelves containing books you have read or want to read. You can also search for books by title, which is the API function we’re going to tacking in today’s API August post.

Sigining up for a GoodReads API Key

Like the Google APIs, you need to sign up for an API key. Head to the api page for more information.

Creating our Visual Studio solution

Start by creating a new Class Library (Portable) project. Name the project GoodReads.PCL and the solution GoodReads.

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.

Querying the GoodReads service

The Url for the GoodReads API is as follows:

http://www.goodreads.com/search/search?format=xml&key=[Your Key]&q=[Query] 

Unlike the Google Places API, GoodReads returns XML formatted results, so there are a couple of ways to create the C# classes to use for serialization. One option is to use the Paste XML as Class option from the Edit/Paste Special menu. Another is to use the xsd.exe tool, which is what I did when first investigating the GoodReads API some time ago.

The BookListViewModel contains an ObservableCollection of GoodreadsBook results and a single asynchronous call to the GoodReads web service.

public class BookListViewModel : NotifyBase
{
    string key = "[YourAPIKey]";
    string baseUrl = "http://www.goodreads.com/search/search?";
 
    public BookListViewModel()
    {
        this.Books = new ObservableCollection<GoodreadsBook>();
    }
    private ObservableCollection<GoodreadsBook> _books { getset; }
 
    public ObservableCollection<GoodreadsBook> Books
    {
        get { return _books; }
        set
        {
            _books = value;
            OnPropertyChanged("Books");
        }
    }
 
    public async Task LoadDataAsync(string Search)
    {
        try
        {
            Uri uri = new Uri(string.Format("{0}format=xml&key={1}&q={2}", baseUrl, key, Search));
 
            HttpClient client = new HttpClient();
            var response = await client.GetStringAsync(uri);
 
            StringReader sr = new StringReader(response);
 
            XmlSerializer xs = new XmlSerializer(typeof(GoodreadsResponse));
            GoodreadsResponse results = (GoodreadsResponse)xs.Deserialize(sr);
 
            // add each book from the works array
            for (int i = 0; i < results.Search.Results.Works.Length; i++)
            {
                this.Books.Add(results.Search.Results.Works[i].Books[0]);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
}

Creating the Windows Phone project

Add a new Windows Phone project to your solutions (it’s in the C#/Store Apps category in Visual Studio).

Add a reference to the GoodReads.PCL project so that we can use our ViewModel.

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

private static BookListViewModel _viewModel { getset; }
public static BookListViewModel ViewModel
{
    get
    {
        if (_viewModel == null)
            _viewModel = new BookListViewModel();
        return _viewModel;
    }
}

Calling the ViewModel from the MainPage

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

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    this.DataContext = App.ViewModel;
    base.OnNavigatedTo(e);
}

We’re using a simple textbox to collect the value to add to the search query so that users can enter the name of a book to search for. We’ve wired up the OnKeyDown event so that when the user taps the ‘enter’ key on the keyboard, the search is started.

private async void OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        _searchTerm = SearchTextBox.Text.Trim();
 
        if (String.IsNullOrEmpty(_searchTerm))
            return;
        this.Focus();
 
        // search the API
        await App.ViewModel.LoadDataAsync(_searchTerm);
 
    }
}

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

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

Replace the LayoutRoot Grid with the following mark-up:

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
 
    <StackPanel Grid.Row="0" Margin="12,17,0,12" >
        <TextBox x:Name="SearchTextBox"
                    InputScope="Search" 
                    KeyDown="OnKeyDown"/>
    </StackPanel>
 
    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <local:LongListSelector x:Name="lstResults" 
                ItemsSource="{Binding Books}"  
                ItemTemplate="{StaticResource BookItemTemplate}" />
    </Grid>
</Grid>

One change you'll notice is that we're using a resource called BookItemTemplate rather than simply adding the markup to the ItemTemplate tag as we did in the Google Places API post. This maks it much cleaner to read the markup and also enables reuse of your resources, if you make them application wide. In this case, the resource has been added at the page level, rather than application, so you'll need to add the following to your page XAML.

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="BookItemTemplate">
        <StackPanel Margin="12,12,0,12" Orientation="Horizontal">
            <Image Source="{Binding ThumbnailURL}"/>
            <StackPanel Margin="12,0,0,0">
                <TextBlock HorizontalAlignment="Left" 
                            Height="Auto" 
                            TextWrapping="Wrap" 
                            Text="{Binding Title}" 
                            VerticalAlignment="Top" 
                            Width="Auto" 
                            Style="{StaticResource PhoneTextAccentStyle}" 
                            Margin="0,0,0,0"/>
                <TextBlock HorizontalAlignment="Left" 
                            Height="Auto" 
                            TextWrapping="Wrap" 
                            Text="{Binding Author.Name}" 
                            VerticalAlignment="Top" 
                            Width="Auto" 
                            Margin="0,0,0,0"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

Run the app on your device and perform a search for your favourite book. You should end up with a list of results that match your search term.


Tags: ,

C# | Windows Phone 8

Google Places API - Part 1

by CameronM 4. August 2014 08:54

Apps that help you find restaurants, bars, cinemas and other businesses are extremely popular. Apps like Yelp are bringing local search and reviews to the fore, with many people relying on these services to help them decide where to spend their hard-earned money.

Many of the big names, such as Google, also provide services that can be used to create your very own place-finding app. In this post, we’ll look at how you can user Google Places API to build a Windows Phone 8 ‘What’s near me’ app.

Signing up for the Google Places API

The first step is to sign up for the Google Places API. To do that, you’ll need a Google account and access to the API Console. Check out this page for more information about how to add access to the Place API to your account.

Once you’ve added the Places API to your account, you’ll need the take a note of the API key associated with that account to make any requests to the web service.

Creating our Visual Studio solution

Okay, so now that we have our API key, it’s time to fire up Visual Studio. Start by creating a new Class Library (Portable) project. Name the project GooglPlaces.PCL and the solution GooglePlaces.

Add 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 handle the resulting Json.

Performing a location based search

The Url for performing a basic Places search if as follows:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=[Latitude],[Longitude]&radius=500&key=[Your API Key]

One handy tool you can use when dealing with API’s that return Json, is found at Json2CSharp. Copy and paste the Json formatted results from a call to the above Url into the textbox, hit Generate and a bunch of C# classes will be displayed.  These classes have been added to the Models folder of our project. For readability, each class was added to its’ own .cs file, however you could simply add them as a single file also.

The MainViewModel contains an ObservableCollection of results and a couple of asynchronous methods that call the Places API. This will be enough to get us started with creating a Windows Phone app and displaying a list of results.

In our app we’ll be retrieving the Latitude and Longitude from the device, so these will need to be variables we send to the web service. We’ll use a hard coded radius and create a class variable to hold the API Key.

public class MainViewModel : NotifyBase
{
    string baseUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch";
    string apiKey = "[Your API Key]";
 
    private ObservableCollection<Result> _Results;
    public ObservableCollection<Result> Results
    {
        get { return _Results; }
        set
        {
            _Results = value;
            OnPropertyChanged("Results");
        }
    }
 
    public async Task LoadDataAsync(double Lat, double Long)
    {
        // convert the lat and long to a string
        string LatLong = string.Format("{0},{1}", Lat.ToString("0.0000"), Long.ToString("0.0000"));
 
        // build the NearbySearch Uri
        Uri uri = new Uri(string.Format("{0}/json?location={1}&radius=500&key={2}", baseUrl, LatLong, apiKey));
 
        // await the call to the API
        await FetchDataAsync(uri);
    }
 
    private async Task FetchDataAsync(Uri uri)
    {
        HttpClient client = new HttpClient();
        var response = await client.GetStringAsync(uri);
 
        var results = JsonConvert.DeserializeObject<ListRootObject>(response);
        this.Results = new ObservableCollection<Result>(results.results);
    }
}

Creating the Windows Phone project

With the basic 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 GooglePlaces.PCL project.

Create an application property that exposes our MainView model, 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 ensures 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(37.422, -122.083);
 
    base.OnNavigatedTo(e);
}

In this post just hard coding the latitude and longitude, to confirm that everything is wired up correctly. In a future post, we'll modify the code from How to get the phone's current location for Windows Phone 8 to get the actual location from the device.

Displaying the results

Now that we’ve linked the ViewModel, it’s time to add the XAML that will display the results. 

Add a new xmlns named local to your MainPage.xaml as follows:

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

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

<local:LongListSelector ItemsSource="{Binding Results}">
    <local:LongListSelector.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="12,0,0,17" >
                <Image Source="{Binding icon}" 
                        Height="48" Width="48" 
                        VerticalAlignment="Top" 
                        Margin="0,0,8,0"/>
                <StackPanel Margin="12,0,0,17" 
                            Width="432"
                            VerticalAlignment="Top" >
                    <TextBlock Text="{Binding name}" 
                                HorizontalAlignment="Left" 
                                VerticalAlignment="Top" 
                                FontSize="{StaticResource PhoneFontSizeLarge}" 
                                FontFamily="{StaticResource PhoneFontFamilyNormal}" />
                    <TextBlock Text="{Binding vicinity}" 
                                HorizontalAlignment="Left" 
                                Style="{StaticResource PhoneTextSubtleStyle}" />
                </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 places in the vicinity of the Lat/Long you hard-coded.

Tags: ,

C# | Windows Phone 8

API August

by CameronM 1. August 2014 12:28

Welcome to API August, where we’ll be looking at how to build simple Windows Phone 8 apps using some of the more common, freely accessible API’s and web services.

All of the projects we’ll be building during API August will use an MVVM pattern, so that all of the heavy lifting is carried out by a Portable Class Library (PCL). We’ll use a Windows Phone 8 project to test the PCL functionality, however, if you’re keen to develop cross-platform, there’s nothing to stop you using the PCL in a Xamarin Studio solution and creating iOS or Android app as well.

As we’ll be focussing on how to call these APIs and return the results to the user, we’ll be keeping the UI very simple. Mostly we’ll just present the results as a list of records with an accompanying page to show the details of a single record. Occasionally we’ll add some searching or filtering, but we’ll leave the rest to your imagination. Having covered the basics in these posts, you’ll be able to go out and build fantastic, full-featured apps that take the world by storm. If that does happen, be sure to drop me a line, or offer me a job:)

As API August continues, we’ll update this post with links to the projects we’re creating, so take the time to bookmark this page and check back regularly.

Here's some basics that will apply across all of the solutions we'll cover in API August.

Solution Layout

Most of our sample solutions will follow a similar pattern. We’ll have an solution with two projects SolutionName.PCL – the portable class library and SolutionName.WP – the Windows Phone 8 app.

Views - ViewModels

Since our Views need to know whenever the underlying ViewModel has changed, all of our ViewModels need to implement INotifyPropertyChanged. We’ll create a single base class NotifyBase that handles the PropertyChanged events, which our ViewModes will inherit.
public class NotifyBase : INotifyPropertyChanged
{
 
    public event PropertyChangedEventHandler PropertyChanged;
 
    protected virtual void OnPropertyChanged([CallerMemberNamestring propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(thisnew PropertyChangedEventArgs(propertyName));
    }
 
}

LongListSelector with bindable SelectedItem

In the API August projects, we’ll use a class derived from the built-in LongListSelector to display lists of results. The derived class adds the implementation for the SelectedItem property. This is not supported in the built-in control, but is extremely handy. 
public class LongListSelector : Microsoft.Phone.Controls.LongListSelector
{
    public LongListSelector()
    {
        SelectionChanged += LongListSelector_SelectionChanged;
    }
 
    void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SelectedItem = base.SelectedItem;
    }
 
    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register(
            "SelectedItem",
            typeof(object),
            typeof(LongListSelector),
            new PropertyMetadata(null, OnSelectedItemChanged)
        );
 
    private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var selector = (LongListSelector)d;
        selector.SelectedItem = e.NewValue;
    }
 
    public new object SelectedItem
    {
        get { return GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }
}

Tags: ,

C# | Windows Phone 8