C# Flurl HTTP - Download JSON,Fill ListBox

| Page Views: 241

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.

What is Flurl?

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.

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.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post