0

I've got a Class in C# that is firing on a button click. When the button is clicked it fires CreateRepo()

        protected void Button1_Click(object sender, EventArgs e)
        {
            //await MyClient.CreateRepo();
            string Repo = TextBox2.Text;
            var WebTask = MyClient.CreateRepo(Repo);

}
       

    }

This is CreateRepo()

public class MyClient
        {
            public static TextBox TextBox2;
            public static Button Button1;
            public static Label Label1;
            
                



            static async public Task<string> CreateRepo(string Repo1)
            {
                using (var httpClient = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.github.com/user/repos"))
                    {

                       

                        var UserAgent1 = new ProductInfoHeaderValue("Bot", "1.0");
                        //Get Github Personal Access Token from Azure Key Vault
                        var kvsecret = ConfigurationManager.AppSettings["secret"];

                        //Use Github Personal Access Token from Azure Key Vault
                        request.Headers.TryAddWithoutValidation("Authorization", $"token {kvsecret}");

                        request.Headers.UserAgent.Add(UserAgent1);
                        
                        request.Content = new StringContent($"{{\"name\":\"{Repo1}\"}}");

                        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                        var response = await httpClient.SendAsync(request);
                       
                        var responseBody = await response.Content.ReadAsStringAsync();
                        
                        
                        var http = response.StatusCode;
                        string stringhttp = http.ToString();
                        MyClient.Label1.Text = stringhttp;
                       
                        HttpresponseFunction(stringhttp);

                        return stringhttp;
                        

                    }
                }
            }

I'm just trying to pass the http response code inside stringhttp to populate Label1.text but it's just not working.

If I add it into the Button1 click as follows it seems to work:

        protected void Button1_Click(object sender, EventArgs e)
        {
            //await MyClient.CreateRepo();
            string Repo = TextBox2.Text;
            var WebTask = MyClient.CreateRepo(Repo);
            MyClient.label1.text = "hello world"

Inside my class I've added in the required objects to that the class can 'see' the controls as follows:

        public static TextBox TextBox2;
        public static Button Button1;
        public static Label Label1;

..And I've converted the http Status code into a string

Is there a way I can write the value of stringhttp to the label

james
  • 1
  • 1
  • why not just `Label1.Text = await WebTask` ? *Inside my class I've added in the required objects to that the class can 'see'* - but that doesn't make any sense, for various reasons, not least that whatever class hold the button click handerl probably also holds the Label, gets the string from the repo, then .. er.. looks like you intended to give the label and the string back to the repo so the repo can set the label, except the label in the repo is a static field that is never inited and will cause a null ref.. very convoluted. Make the repo do one thing only: query api, return string – Caius Jard Jan 12 '22 at 17:27
  • Then the main class uses repo, awaits the response, awaiting unpacks the Task and retrieves the resulting value when the task is done, and the string it gives out can be set to the label. Using `await` lets the UI thread stop processing the button click handler half way through, go back to what it was doing, and then return to finish off when the task completes (the api responds) – Caius Jard Jan 12 '22 at 17:32
  • If I add MyClient.Label1.Text = await WebTask; to my function as below and run the code, I get the following error async public void Button1_Click(object sender, EventArgs e) { //await MyClient.CreateRepo(); string Repo = TextBox2.Text; var WebTask = MyClient.CreateRepo(Repo); MyClient.Label1.Text = await WebTask; } – james Jan 13 '22 at 09:48
  • This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it. – james Jan 13 '22 at 09:48
  • If I remove the VOID from the function as below. The modifier async is not valid for this item I get it that void needs to be removed but not sure on the async stuff – james Jan 13 '22 at 09:51
  • See https://stackoverflow.com/questions/27282617/is-it-safe-to-use-async-await-in-asp-net-event-handlers for more extensive advice than can be passed in a comment – Caius Jard Jan 13 '22 at 10:38

1 Answers1

0

Thanks Caius, I managed to get it working. The calling function looks like this protected void Button1_ClickAsync(object sender, EventArgs e)

{
    //await MyClient.CreateRepo();
    string Repo = TextBox2.Text;
    MyClient C = new MyClient();
    var WebTask = C.CreateRepo(Repo);
    string sc = WebTask.ToString();
    Label2.Text = sc;

}

The next problem I have is that Label2 is returning this as text - 'System.Threading.Tasks.Task`1[System.Net.Http.HttpResponseMessage]'

james
  • 1
  • 1
  • That's not "working" though; it's not waiting for the task to complete and getting the string from it like await would, it's just calling to string on a task, which is returning the type name ("Task" in essence). Did you read what I linked to? – Caius Jard Jan 14 '22 at 01:58
  • I've managed to get the Async stuff working now, thanks for the link. I read it but couldn't actually get it to work but I have now. The fix was to add async="true" to the default.aspx which got over the async issues, Then I had to add 'ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;' as the .Net 4.8 version seemed to be using the OS ciphers. – james Jan 14 '22 at 11:18
  • The Task returns a lot of data so that's good news. Thanks for your help! – james Jan 14 '22 at 11:18