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;
}
}
}