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