I am currently, designing a Revit plugin macro using Revit API, which uses .NET Framework 4.8. Hence my project is in that framework. At the moment I am trying to write certain output parameters, to a PostgreSQL database using NpgSQL. However, when I run my macro, I am getting a type initializer for NpgsqlDataSourceBuilder error prompt from Revit. I was able to test the code in a different framework (.Net 8.0) and it was working fine.
My question is: As I am using a different framework, would I have to use NpgsqlConnectionrather than NpgsqlDataSourceBuilder?
I have a DB_Reading Class that is used to initialize the connection to the database. Where I call it and pass certain parameterized queries in other classes.
using Npgsql;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Data;
namespace Revit_Plugin_V5
{
public class DB_Reading
{
public string Server_Name { get; set; }
public int Port { get; set; }
public string Database_Name { get; set; }
public string User_Name { get; set; }
public string Password {get; set;}
public NpgsqlConnection Connection { get; set; }
public NpgsqlDataSource dataSource { get; set; }
private static DB_Reading _instance = null;
public static DB_Reading Instance()
{
if (_instance == null)
{
try
{
_instance = new DB_Reading();
}
catch (System.Exception ex)
{
throw new Exception("" + ex.Message + " Instance()");
}
}
return (_instance);
}
public bool IsConnect()
{
if(Connection == null)
{
if(String.IsNullOrEmpty(Database_Name))
{
return false;
}
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.Database = Database_Name;
sb.Host = Server_Name;
sb.Password = Password;
sb.Username = User_Name;
sb.Port = Port;
try
{
// Connection = new NpgsqlConnection(sb.ToString());
// Connection.Open();
NpgsqlDataSourceBuilder dataSourceBuilder = new NpgsqlDataSourceBuilder(sb.ToString());
dataSource = dataSourceBuilder.Build();
Connection = dataSource.OpenConnection();
}
catch (System.Exception ex)
{
throw new Exception("" + ex.Message + " IsConnect() is the problem");
}
}
return (true);
}
public void Close()
{
Connection.Close();
}
}
}
For example in another class I would call the DB_Reading class via:
var dbCon = DB_Reading.Instance();
dbCon.Server_Name = "localhost";
dbCon.Database_Name = "database";
dbCon.Port = 5432;
dbCon.User_Name = "user_name";
dbCon.Password = "password";
if (dbCon.IsConnect()==true)
{
string query = "SELECT DISTINCT job_name,job_id FROM Table";
using(var cmd = dbCon.dataSource.CreateCommand(query))
{
var reader = cmd.ExecuteReader();
List<int> parameters = new List<int>();
try
{
while(reader.Read())
{
string job_name = reader.GetString(0);
int job_id = reader.GetInt32(1);
job_names.Add(job_name); // public
job_ids.Add(job_id); // public
job_list.Add(job_name + "-" + job_id.ToString()); // private
}
reader.Close();
}
catch (Exception ex)
{
throw new Exception("" + ex.Message + " reader");
}
}
}
dbCon.Close();
dbCon.Connection = null;