Error when trying to read data from InfluxDB database

Ionut Dragomir 26 Reputation points
2023-01-20T08:24:21.48+00:00

Hi,

I have a web MVC application in C# with targer framework: .NET Framework 4.5.2. I want to read some data from an InfluxDB database. After I publish and run my application, I get this error:

System.IO.FileLoadException
Message : Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
StackTrace :    at System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
   at System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
   at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, Boolean inherit)
   at DevExpress.DataAccess.ObjectBinding.ObjectMember..ctor(MemberInfo memberInfo)
   at DevExpress.DataAccess.Native.ObjectBinding.ObjectDataSourceFillHelper.<>c.<GetItemMembersCore>b__24_5(MemberInfo info)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at DevExpress.DataAccess.Native.Web.ObjectDataSourceWizardService.GetMemberInfo(Type type, IObjectDataSourceMemberFilterService filterMemberService)
   at DevExpress.DataAccess.Native.Web.ObjectDataSourceWizardService.GetAvailableObjectDescriptions(String context)
   at lambda_method(Closure , IQueryBuilderRequestController , String )
   at DevExpress.XtraReports.Web.Native.ClientControls.Services.RequestManagerBase`2.WrapWithTryCatchAction(String controllerTypeName, String methodName, String webActionName, ControllerFunc invoker, TController controller, String json)

In order to establish the connection, I had to add two references: InfluxDB.Client and InfluxDB.Client.Core. My code looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Api.Service;
using InfluxDB.Client.Core;

namespace ServerSide
{
    public class ReadInfluxDB
    {
        private readonly string Token = "TestTokenWEBICC";

        public async Task Main()
        {
            var client = new InfluxDBClient("http://localhost:8086", Token);

            var flux = "from(bucket:\"TestDB\") |> range(start: 0)";

            var queryApi = client.GetQueryApi();

            //
            // QueryData
            //
            var tables = await queryApi.QueryAsync(flux);//, "org_id"

            var id = tables[0].Records;
            var measure = tables[1].Records;
            var val = tables[3].Records;
            var time = tables[4].Records;
            var count = id.Count();

            List<Value> Values = new List<Value>();
            tables.ForEach(table =>
            {
                table.Records.ForEach(record =>
                {
                    Console.WriteLine($"{record.GetTime()}: {record.GetValueByKey("_value")}");
                });
            });

            for (int i = 0; i < count; i++)
            {
                Value _value = new Value();
                _value.DateAndTime = Convert.ToDateTime(time[i].GetTimeInDateTime());
                _value.Measure = Convert.ToString(measure[i].GetValue());
                _value.Val = Convert.ToDouble(val[i].GetValue());
                Values.Add(_value);
            }
            client.Dispose();
        }
    }

    public class Value
    {
        public DateTime DateAndTime { get; set; }
        public string Measure { get; set; }
        public double Val { get; set; }

    }
}

I found on .csproj file that I have a line: <Reference Include="netstandard" />. If I replace it with <Reference Include="netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />; I get erros on the above function.
How could I solve this issue?

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Santhi Swaroop Naik Bukke 595 Reputation points
    2023-01-20T17:02:08.2033333+00:00

    There are a few issues in the code snippet you provided:

    1. The tables variable may not have the same number of elements as the number of variables (id, measure, val, time) you are trying to extract from it. This means that when you try to access an element from one of these variables, an IndexOutOfRangeException may occur.
    2. The val variable is being accessed from index 3, however it's not clear if the data is stored at this index, so this could cause an IndexOutOfRangeException.
    3. In the for loop where you are iterating through the count, you are assuming that the number of records in the id variable is the same as the number of records in the other variables, this could cause an IndexOutOfRangeException if the number of records are different.
    4. The time[i].GetTimeInDateTime() the method is not a valid method and this will cause a runtime error.
    5. The measure[i].GetValue() the method is also not a valid method and this will cause a runtime error.
    6. The val[i].GetValue() method is also not a valid method and this will cause a runtime error.

    below is the code

    Here's an example of how you can fix the above code to correctly extract data from the InfluxDB:
    
    Copy code
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using InfluxDB.Client;
    using InfluxDB.Client.Api.Service;
    using InfluxDB.Client.Core;
    using InfluxDB.Client.Writes;
    
    namespace ServerSide
    {
        public class ReadInfluxDB
        {
            private readonly string Token = "TestTokenWEBICC";
    
            public async Task Main()
            {
                var client = new InfluxDBClient("http://localhost:8086", Token);
                var queryApi = client.GetQueryApi();
    
                //Query
                var flux = "from(bucket:\"TestDB\") |> range(start: 0)";
                var tables = await queryApi.QueryAsync(flux);
                if(tables.Count == 0)
                {
                    Console.WriteLine("No data found");
                    return;
                }
                
                //Extract data
                var records = tables[0].Records;
                var count = records.Count();
                var values = new List<Value>();
                for (int i = 0; i < count; i++)
                {
                    var record = records[i];
                    var time = record.GetTime();
                    var value = record.GetValue();
                    var measurement = record.GetMeasurement();
                    values.Add(new Value(Convert.ToDateTime(time), measurement, Convert.ToDouble(value)));
                }
                values.ForEach(val => Console.WriteLine(val.ToString()));
                client.Dispose();
            }
        }
    
        public class Value
        {
            public DateTime DateAndTime { get; set; }
            public string Measure { get; set; }
            public double Val { get; set; }
    
            public Value(DateTime dateAndTime, string measure, double val)
            {
                DateAndTime = dateAndTime;
                Measure = measure;
                Val = val;
            }
            public override string ToString()
    
    
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.