C# HTTP Flurl Examples – Download JSON and Show

C# Flurl HTTP Client Tutorial and Examples involving downloading JSON and rendering on listview and listbox

Flurl is a modern, fluent, asynchronous, testable, portable, buzzword-laden URL builder and HTTP client library for .NET.

Flurl Installation

Install-Package Flurl.Http -Version 2.4.0

Find more info here.

(a). C# Flurl HTTP – Download JSON,Fill ListBox

C# Flurl HTTP with ListBox Example and Tutorial.

In this piece we see how to download JSON data from online asynchronously via Async Await and then populate a ListBox. We will be using the Flurl HTTP library.

Video Tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials.

Code

APIs we use

We start by specifying our importss. In C# we import classes and namespaces using the using directive.
Among the imports include:

  1. Flurl.Http : This namespace contains classes that allow us make our HTTP requests using Flurl.For example the GetJsonAsync() which allow us download our data in JSON format, then map that JSON into a generic List class.
  2. System.Windows.Forms - Provides us with several windows forms classes like the Form class as well as the ListBox class.
  3. System.Collections.Generic - allows us use generic collection classes like the List<T>.
  4. System.Threading and System.Threading.Tasks - these namespaces provide us with high level asynchrony classes. For example from the former, we have the SynchronizationContext class which provides the basic functionality for propagating a synchronization context in various synchronization models. Then in the latter, we have for example the Task class that represents an asynchronous operation.

Classes we Create

Once we've imported our namespaces we will create a POCO class. This class will represent a single user. The user will have the following properties:

  1. Id - a string.
  2. Name - string.
  3. Email - string.
    class User
    {
       ...
    }
    class Program
    {
        ...
    }

The Program class is our main class. It will have the downloadJSONData(). This method is an asynchronous method as we mark it with the async keyword. This method will be responsible for downloading our JSON data from online. For that we will use our Flurl HTTP's GetJsonAsync() method. That method will map our JSON data to a List<User>.

Here's the full class.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Flurl.Http;

namespace JSONListBox
{
    /*
     * User class. A POCO class.
     */
    class User
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
    class Program
    {
        private static SynchronizationContext synchronizationContext;
        private static async void downloadJSONData()
        {
            try
            {
                //PERFORM IN BACKGROUND
                await Task.Run(async () =>
                {
                    List<User> users = await "https://jsonplaceholder.typicode.com/users".GetJsonAsync<List<User>>();
                    foreach (User user in users)
                    {
                        synchronizationContext.Post(value =>
                        {
                            //UPDATE LISTBOX
                            myListBox.Items.Add((string) value);

                        }, user.Name);
                    }
                });
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        private static readonly ListBox myListBox = new ListBox
        {
            Location = new Point(30, 70),
            Size = new Size(500, 400),
            Font = new Font(FontFamily.GenericSansSerif, 15)
        };
        /*
         * ListBox SelectedIndexChanged event handler. We display a messagebox when item is selected.
         */
        private static void myListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int selectedIndex = myListBox.SelectedIndices[0];
                if (selectedIndex != -1)
                {
                    string name = myListBox.Items[selectedIndex].ToString();
                    MessageBox.Show(name);
                }
            }
            catch (ArgumentOutOfRangeException argumentOutOfRangeException)
            {
                MessageBox.Show(argumentOutOfRangeException.Message);
            }
        }
        /*
     * Create a Form, Set its properties and run the application.
     */
        private static void createForm()
        {
            synchronizationContext = SynchronizationContext.Current;

            Form myForm = new Form
            {
                Text = "C# Flurl HTTP : ListBox - Fill From JSON - Camposha.info",
                ClientSize = new Size(564, 520),
                BackColor = Color.MediumSeaGreen
            };
            myListBox.SelectedIndexChanged += myListBox_SelectedIndexChanged;
            myForm.Controls.Add(myListBox);
            Application.EnableVisualStyles();
            Application.Run(myForm);
        }
        /*
        * Main method
        */
        public static void Main()
        {
            downloadJSONData();
            createForm();
        }
    }
}

That's it.

(b). C# Flurl HTTP – Download JSON,Fill ListView

C# HTTP Flurl ListView JSON Tutorial Example.

In this tutorial we see a practical example of how to download and parse JSON data from online and bind the data in a C# windows forms listview.

C# HTTP Flurl ListView

Video Tutorial

Here's the video tutorial version of this class.

Demo

Program.cs

Here's the full Program.cs file.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Flurl.Http;

namespace JSONListView
{ /*
     * User class. A POCO class.
     */
    class User
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
    class Program
    {
        private static SynchronizationContext synchronizationContext;
        private static ListView myListView;
        private static Label progressLabel;
        /*
         * Setup ListView. Instantiate, then add columns then register the ItemSelectionChanged events
         */
        private static void setupListView()
        {
            myListView = new ListView { Location = new Point(30, 70), Size = new Size(400, 400), View = View.Details, FullRowSelect = true, Alignment = ListViewAlignment.SnapToGrid };
            myListView.Columns.Add("ID", 100);
            myListView.Columns.Add("NAME", 150);
            myListView.Columns.Add("EMAIL", 150);

            myListView.ItemSelectionChanged += myListView_ItemSelectionChanged;

            progressLabel = new Label()
            {
                Location = new Point(50, 50),
                ClientSize = new Size(200, 15),
                ForeColor = Color.AliceBlue,
                Text = "Downloading data.........Please wait"
            };
        }
        /*
         * Listen to ItemSelectionChange events for our ListView.
         * Then show the name in a messagebox
         */
        static void myListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            ListViewItem listViewItem = e.Item;
            String name = listViewItem.SubItems[1].Text;
            if (e.IsSelected)
            {
                MessageBox.Show(name,"ListView JSON",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }
        /*
         * Download json data from online using Http Flurl. Do it asynchronously.
         */
        private static async void downloadJSONData()
        {
            try
            {
                //PERFORM IN BACKGROUND
                await Task.Run(async () =>
                {
                    List<User> users = await "https://jsonplaceholder.typicode.com/users".GetJsonAsync<List<User>>();
                    foreach (User user in users)
                    {
                        synchronizationContext.Post(value =>
                        {
                            var mUser = (User)value;
                            progressLabel.Text = "Download Complete.";
                            myListView.Items.Add(new ListViewItem(new[] { mUser.Id, mUser.Name, mUser.Email }));

                        }, user);
                    }
                });
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        /*
     * Create a Form, Set its properties and run the application.
     */
        private static void createForm()
        {
            synchronizationContext = SynchronizationContext.Current;

            Form myForm = new Form
            {
                Text = "C# Flurl HTTP : ListView - Fill From JSON",
                ClientSize = new Size(564, 520),
                BackColor = Color.MediumSeaGreen
            };

            myForm.Controls.Add(progressLabel);
            myForm.Controls.Add(myListView);
            Application.EnableVisualStyles();
            Application.Run(myForm);
        }
        /*
        * Main method
        */
        public static void Main()
        {
            setupListView();
            downloadJSONData();
            createForm();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *