Integrating API in c#

Asked

Viewed 76 times

0

I would like to pass the result of this API to a TextBox. I’m having a hard time getting the information from this class to the graphic part.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;
namespace WindowsFormsApplication3
{
    static class Program
    {
        static async Task<string> LookupMac(string MacAddress)
        {
            var uri = new Uri("http://api.macvendors.com/" + WebUtility.UrlEncode(MacAddress));
            using (var wc = new HttpClient())
                return await wc.GetStringAsync(uri);
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            foreach (var mac in new string[] { "88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D" })
            Console.WriteLine(mac + "\t" + LookupMac(mac).Result);
            Console.ReadLine();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

        }
    }
}
  • Explain your problem.

  • I would like to pass on to a Textbox the information that this API is returning!

  • I am not able to pass the information to the form to manipulate them!

  • You better put the code in the form load event.

  • @Marcoswilian solved?

  • Solved! Thank you

Show 1 more comment

1 answer

0


You need to make your public method within the class Program... but if it will not be accessed at all Forms, I see no reason why it should be available here and not within the partial form.

static class Program
{

    public static async Task<string> LookupMac(string MacAddress)
    {
        var uri = new Uri("http://api.macvendors.com/" + WebUtility.UrlEncode(MacAddress));
        using (var wc = new HttpClient())
            return await wc.GetStringAsync(uri);
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

So you can run it from your form and build the content to display on textBox

public partial class Form1 : Form
 {

    public Form1()
    {
        StringBuilder sb = new StringBuilder();
        foreach (var mac in new string[] { "88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D" })
        {
            var result = Program.LookupMac(mac).Result;
            sb.AppendLine(string.Format("{0} \t {1}", mac, result));

        }

        textBox.Text = sb.ToString();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.