0

I know the Title Issue is not unique and lot of Messages available. Reason why I am opening a thread is that I'm really struggling to understand the issue based on my project.

Recently I tried to start a WinForm to get values from an REST API.

Just as a beginning test on the Form1 once clicking the metroButton1 I should get a SessionToken to the metroTextBox1.Text, which works.

Where I'm struggling is to use that Output as an Input for the getvirtualmachine Class.

Once using the Form1.connect() in the class to get the SessionToken, i'am getting following Error:

An object reference is required for the non-static field, method, or property 'Form1.connect()'

Not sure how I could make that globally to use it as Input for several classes. Guessing I'm making somehow/somewhere a big mistake.

FORM1

public partial class Form1 : MetroFramework.Forms.MetroForm
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    { }

    public string connect()
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:35113/api/sessions/start");
        httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(metroTextBox3.Text + ":" + metroTextBox4.Text));
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = JsonConvert.SerializeObject(new
            {
                ServerPort = "35107",
                Username = metroTextBox3.Text,
                Password = metroTextBox4.Text,
                Domain = metroTextBox5.Text
            });

            streamWriter.Write(json);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            dynamic item = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            return (string)item.Data;
        }
    }

    public  void metroButton1_Click(object sender, EventArgs e)
    {
        metroTextBox1.Text = connect();
    }

GetVirtualMachines Class

public class GetVirtualMachines
{
    public  string gVM()
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:35113/api/vms/list/");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "GET";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = JsonConvert.SerializeObject(new
            {
                SessionToken = Form1.connect(),
            });

            streamWriter.Write(json);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            dynamic item = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            return item;
        }
    }
}
Craig W.
  • 17,838
  • 6
  • 49
  • 82
Max
  • 1
  • Ups. seems my Greetings where not added to the post. "Hello Specialists" afterwards ;) – Max Apr 04 '17 at 23:56

2 Answers2

1

You either need to make the method static, so it's part of the class definition rather than an instance method, i.e.

public static string connect()

or create an instance of Form1 and use that to call connect(). However, that ends up creating another problem because now you've got a form hanging out in memory that no one ever sees (and will prevent the application from closing), so you really should ensure it gets disposed, i.e.

using(var form = new Form1)
{
    form.connect();
}

However, my bigger question would be, why are you using a Form to perform this operation at all. It seems to me more like the connect() method belongs on the GetVirtualMachines class.

At the moment, given the code you've shown, this is really bad use of the toolset.

Craig W.
  • 17,838
  • 6
  • 49
  • 82
1

You need to rethink your approach here. The Windows Form (Form1) is the actual GUI that the user sees. Your backend GetVMs class appears to be something purely for data processing that the user doesn't really interact with.

So you can't really have the GetVMs class create a new instance of your Windows Form because, well, there is no way for the user to see the form that you new up (simplifying a lot here!).

I would solve this by following a relatively standard view/controller type pattern:

  1. Your windows form is the view -- that is what the user sees
  2. The form has an instance of your GetVMs class private GetVirtualMachines VMGetter
  3. The form calls methods of GetVirtualMachines via its instance of the class (VMGetter), passing an argument with whatever is in the text box.

This is still not the greatest idea in the simplified approach I gave because you'll hang the UI thread. But, hopefully it gives you a jumping off point.

Edit: I'd also move the connect method and its business logic to your GetVMs class. Typically we try to avoid business logic in all view/display classes.

debracey
  • 6,517
  • 1
  • 30
  • 56
  • Thx for the fast Replys. Reason for why i just started to use the connect() in the Form was, because i was able to use it inside the Buttonclick void. Once i move the connect() to the other class, i have the issue to reach the Metrotextboxes. Getting same Object Reference Error then. How i would be able then to get the Data from metroboxes once moving the connect() away to the class. Will try in morning . ;) – Max Apr 05 '17 at 01:05
  • i see thread was marked as "Duplicate". i don't have a 2nd Form. i only have 1 Form and 1 Class. i moved the connect() to the Class. so i'am trying to reach now the Class from the Form. and from the Class to reach the TextBoxes. both i'am failing. i looked the sharing between the Forms Thread > but is not really helpfully for me, as code is differently. not 100% clear to my why facing that issues. ;). any further help appriciated. once i understand the situation - i'am sure able to work further. – Max Apr 05 '17 at 10:10