-3

After implementing the suggested code, I am getting an error stating:

An Object reference is required for the non-static field, method, or property Program.InsertLogData()

for the try block of await insertlogdata()

Shall I remove the word static inside of main and leave it public async task?

UPDATED CODE AFTER SUGGESTIONS WERE GIVEN:

namespace ElasticSearchConsoleApp { class Program { private readonly IElasticClient _elasticClient;

    public Program()
    {
        _elasticClient = new ElasticClient();
    }
    public static async Task Main(string[] args)
    {
        Console.Write("getting connection...");


        try
        {
            await InsertLogData();
        }
        catch(Exception ex)
        {
            Console.Write("Error: " + ex.Message);
        }

        Console.ReadLine();


    }

    public async Task<int> InsertLogData()
    {
        SqlConnection connection = null;
        SqlCommand command = null;
        int numrows = 0;

        try
        {
            var response = await _elasticClient.SearchAsync<Object>(s => s
                .Size(3000)
                .Index("customer-simulation-es-app-logs*")
                .Query(q => +q
                    .DateRange(dr => dr
                        .Field("@timestamp")
                            .GreaterThanOrEquals("2021-06-07T17:13:54.414-05:00")
                            .LessThanOrEquals(DateTime.Now))));

            connection = new SqlConnection("Data Source=.\\SQLExpress;Database=ElasticSearchService;Trusted_Connection=True;");

            connection.Open();

            foreach (var item in response.Hits)
            {
                var id = item.Id;
                var sourceItem = item.Source;

                var json = _elasticClient.RequestResponseSerializer.SerializeToString(sourceItem);

                command = new SqlCommand("INSERT INTO EsLogs (ELKLogID, LogMessage, DateCreated) VALUES ('" + id + "','" + json + "', getdate())", connection);

                numrows = command.ExecuteNonQuery();
            }

            connection.Close();

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
        finally
        {
            command.Dispose();
            connection.Dispose();


        }
        return numrows;
    }

}

}

enter image description here

NoviceCoder
  • 449
  • 1
  • 9
  • 26
  • you need to create an object of IElasticClient _elasticClient, so you have have something like private static IElasticClient _elasticClient = new IElasticClient(); – ARH Jul 09 '21 at 21:51
  • I think your elastic client is null. You are using is as if you had dependency injection, but it seems that you don't. Create an instance of elastic client before you call your method. It's not a question of the methods being static or not. – SnowGroomer Jul 09 '21 at 21:51
  • Wait I am confused.. I thought I do just from the first line `private static IElasticClient _elasticClient;` then having an overwritten ctor? – NoviceCoder Jul 09 '21 at 21:53
  • So if I add the line `IElasticClient _elasticClient = new IElasticClient();` before `await InsertLogData()` it tells me "Cannot create an instance of the abstract type or interface `IElasticClient`. Am I not doing this right? @SnowGroomer – NoviceCoder Jul 09 '21 at 21:56
  • I noticed that in my previous project I have `private readonly IElasticClient _elasticClient;` and not `private STATIC IElasticClient _elasticClient` does that make a difference? – NoviceCoder Jul 09 '21 at 22:00

1 Answers1

0

you have to fix elastic client.

private static readonly IElasticClient _elasticClient = new ElasticClient();

//  public Program()
//  {
//  }

After this you will have another error. You have to fix your foreach loop by placing command.ExecuteNonQuery inside of the loop


 connection.Open();
foreach (var item in response.Hits)
 {
 var id = item.Id;
  var sourceItem = item.Source;
 var json = _elasticClient.RequestResponseSerializer.SerializeToString(sourceItem);

 command = new SqlCommand("INSERT INTO EsLogs (ELKLogID, LogMessage, DateCreated) VALUES ('" + id + "','" + json + "', getdate())", connection);

 numrows = command.ExecuteNonQuery();
}

 connection.Close();

and by the way you have to think about using parameters for your query

Serge
  • 40,935
  • 4
  • 18
  • 45
  • Manually as in call the elastic client instance before calling my method? Thanks for the catch on the other error! :) I will have to look into parameters for my query since I am really new to this, thanks for the heads up btw – NoviceCoder Jul 09 '21 at 22:05
  • Upon fixing the first line of code `private readonly IElasticClient _elasticClient`, inside of my `InsertLogData()` it doesn't accept `_elasticClient` where I have `.SearchAsync` nor where I have it in my `var json` it tells me "An Object reference is required for the non-static field, method, or property 'Program._elasticClient`. But when I placed the line `IElasticClient _elasticClient = new IElasticClient();` it does not like it when I do = new IElasticClient – NoviceCoder Jul 09 '21 at 22:09
  • @NoviceCoder You can try _elasticClient = new ElasticClient(); inside of the constructor . You can't create instance using interface. But I am afraid you will need some parameters. – Serge Jul 09 '21 at 22:12
  • I will update the post... please see the updated section. I still get the same error message when removing the instance inside of the `InsertLogData` method. – NoviceCoder Jul 09 '21 at 22:15
  • Please let me know if I did it incorrectly – NoviceCoder Jul 09 '21 at 22:16
  • @NoviceCoder Comment _elasticClient and remove static from InsertLogData – Serge Jul 09 '21 at 22:21
  • Would I have to remove the word `static` from Main? and leave it as public async task main? Because when I did what you suggested, inside of the try block it said "an object reference is required for the non-static field, method, or property.insertlogdata()" – NoviceCoder Jul 09 '21 at 22:24
  • Please see the updated section post where I updated the latest code after your most recent suggestion – NoviceCoder Jul 09 '21 at 22:27
  • I am sorry I am always confused with main. Check my answer again return static back to method and elastic client – Serge Jul 09 '21 at 22:31
  • No worries! I appreciate it, will implement your suggestions! Thank you! :) – NoviceCoder Jul 09 '21 at 22:35
  • Errors went away you are the best! :) Thanks again for your help and patience! Will run it and see what happens – NoviceCoder Jul 09 '21 at 22:41