C# Error: “Fill: SelectCommand.Connection property has not been initialized.” - c#

I have problem with this error:
C# Error: “Fill: SelectCommand.Connection property has not been
initialized.”
I lloked ower others threads, but people have it built their clients little different and it didnt help.
I dont know, why this error showed. And I suppose its wrong somewhere at SelectOsoba.
I need to show data in DataGridView.
my code is :
class Vrstva
{
public static SqlConnection myConnection;
public static string connstr;
static DataTable t;
public static void createConnect1()
{
connstr = ConfigurationSettings.AppSettings["local1"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void createConnect2()
{
connstr = ConfigurationSettings.AppSettings["local2"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void createConnect3()
{
connstr = ConfigurationSettings.AppSettings["local3"];
Vrstva.myConnection = new SqlConnection(connstr);
}
public static void openConn()
{
Vrstva.myConnection.Open();
}
public static void closeConn()
{
Vrstva.myConnection.Close();
}
public static SqlDataAdapter Query(string command)
{
return new SqlDataAdapter(command, Vrstva.myConnection);
}
public static void NonQuery(string command)
{
SqlCommand Command = new SqlCommand(command, Vrstva.myConnection);
Command.ExecuteNonQuery();
}
public static bool login1(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login1"];
string password1 = ConfigurationSettings.AppSettings["password1"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
public static bool login2(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login2"];
string password1 = ConfigurationSettings.AppSettings["password2"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
public static bool login3(string login, string password)
{
string login1 = ConfigurationSettings.AppSettings["login3"];
string password1 = ConfigurationSettings.AppSettings["password3"];
if (login == login1 && password == password1)
{
return true;
}
return false;
}
////vypis tabulku prislusniku
public static DataTable SelectOsoba()
{
t = new DataTable();
Query("Select * from Osoba;").Fill(t);
return t;
}
//Insert
public static void PridejOsoba(string Jmeno, string Prijmeni, string Povolani, int Poc_Det)
{
NonQuery("Insert into Osoba(Jmeno,Prijmeni,Povolani,Poc_Det) values('" + Jmeno + "','" + Prijmeni + "','" + Povolani + "','" + Poc_Det + "');");
}
}

This error is most likely being thrown because your connection in this line:
return new SqlDataAdapter(command, Vrstva.myConnection);
has not been initialized.
You have to call one of your createConnectX() methods before trying to query.

Related

Cannot implicitly convert type 'System.Collections.Generic.List<ValueObjectLayer.booksVAL>' to 'int'

I'm trying to make a 3 layered C# Library Management project.
I'm trying to select a book from bookDAL (dataacceslayer) through booksBLL(businesslogiclayer and show it on winforms.
i get this error message on BLL
error
DAL:
public static List<booksVAL> BookSelect(string x)
{
List<booksVAL> sonuc = new List<booksVAL>();
OleDbCommand cmdkitaplistele = new OleDbCommand("select * from books where id = " + Int32.Parse(x) + " ", dbConnection.conn); //
if (cmdkitaplistele.Connection.State != ConnectionState.Open) // bağlantı açık değise
{
cmdkitaplistele.Connection.Open(); // bağlantıyı aç
}
OleDbDataReader dr = cmdkitaplistele.ExecuteReader(); // sorgu sonuçlarını data reader ile oku
while (dr.Read())
{
booksVAL book = new booksVAL();
book.bookId = int.Parse(dr["id"].ToString());
book.bookName = dr["bookname"].ToString();
book.bookAuthor = dr["authorname"].ToString();
book.bookPagecount = dr["pagecount"].ToString();
book.bookDatepublished = dr["datepublished"].ToString();
book.bookIsavailable = dr["isavailable"].ToString();
book.bookCategory = dr["category"].ToString();
sonuc.Add(book);
}
dr.Close();
return sonuc;
}
BLL:
public static int BookSelect(string x)
{
return booksDAL.BookSelect(x);
Form:
public partial class bookupdateForm : Form
{
booksForm f1;
public bookupdateForm(booksForm frm1)
{
InitializeComponent();
this.f1 = frm1;
booksBLL.BookSelect(f1.selectedlabel.Text); // selectedlabel comes from another form, it works
}
}
Problem is here:
public static int BookSelect(string x)
{
return booksDAL.BookSelect(x);
}
Change return type int to List<booksVAL>:
public static List<booksVAL> BookSelect(string x)
{
return booksDAL.BookSelect(x);
}

Unable to cast object of type 'System.DBNull' to type 'System.DateTime'

Hi im trying to make a notification system. Basically when i add a new row, a notification will be shown on my notificationspage realtime (i use signalR with razor pages asp.net). But for some reason when i get on that page, i get these errors: Unable to cast object of type 'System.DBNull' to type 'System.DateTime'.
at myWebApp.Controllers.SpeedListener.GetAlarmList() in \myWebApp\Controllers\SpeedListener.cs:line 83
at myWebApp.Controllers.SpeedListener.ListenForAlarmNotifications() in \myWebApp\Controllers\SpeedListener.cs:line 43
So apparently theres a problem at the controller.
Here is the code of the controller
namespace myWebApp.Controllers
{
public class SpeedListener :Controller
{
private IHubContext<speedalarmhub> _hubContext;
private IMemoryCache _cache;
public SpeedListener(IHubContext<speedalarmhub> hubContext,IMemoryCache cache)
{
_hubContext = hubContext;
_cache = cache;
}
public static string cs = Database.Database.Connector();
public void ListenForAlarmNotifications()
{
NpgsqlConnection conn = new NpgsqlConnection(cs);
conn.StateChange += conn_StateChange;
conn.Open();
var listenCommand = conn.CreateCommand();
listenCommand.CommandText = $"listen notifytickets;";
listenCommand.ExecuteNonQuery();
conn.Notification += PostgresNotificationReceived;
_hubContext.Clients.All.SendAsync(this.GetAlarmList());
while (true)
{
conn.Wait();
}
}
private void PostgresNotificationReceived(object sender, NpgsqlNotificationEventArgs e)
{
string actionName = e.Payload.ToString();
string actionType = "";
if (actionName.Contains("DELETE"))
{
actionType = "Delete";
}
if (actionName.Contains("UPDATE"))
{
actionType = "Update";
}
if (actionName.Contains("INSERT"))
{
actionType = "Insert";
}
_hubContext.Clients.All.SendAsync("ReceiveMessage", this.GetAlarmList());
}
public string GetAlarmList()
{
List<NotificationModel> not = new List<NotificationModel>();
using var con = new NpgsqlConnection(cs);
{
string query = "Select datumnu, bericht FROM notification";
using NpgsqlCommand cmd = new NpgsqlCommand(query, con);
{
cmd.Connection = con;
con.Open();
using (NpgsqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
not.Add(new NotificationModel { Datenow = ((DateTime) dr["datumnu"]).ToString("yyyy/MM/dd"), Bericht = dr["bericht"].ToString() });
}
}
con.Close();
}
}
_cache.Set("notification", SerializeObjectToJson(not));
return _cache.Get("notification").ToString();
}
public String SerializeObjectToJson(Object notification)
{
try
{
return Newtonsoft.Json.JsonConvert.SerializeObject(notification);
}
catch (Exception) { return null; }
}
private void conn_StateChange(object sender, System.Data.StateChangeEventArgs e)
{
_hubContext.Clients.All.SendAsync("Current State: " + e.CurrentState.ToString() + " Original State: " + e.OriginalState.ToString(), "connection state changed");
}
}
}
If needed here is my hub
namespace myWebApp.Hubs
{
public class speedalarmhub : Hub
{
private IMemoryCache _cache;
private IHubContext<speedalarmhub> _hubContext;
public speedalarmhub(IMemoryCache cache, IHubContext<speedalarmhub> hubContext)
{
_cache = cache;
_hubContext = hubContext;
}
public async Task SendMessage()
{
if (!_cache.TryGetValue("notification", out string response))
{
SpeedListener speedlist = new SpeedListener(_hubContext,_cache);
speedlist.ListenForAlarmNotifications();
string jsonspeedalarm = speedlist.GetAlarmList();
_cache.Set("notification", jsonspeedalarm);
await Clients.All.SendAsync("ReceiveMessage", _cache.Get("notification").ToString());
}
else
{
await Clients.All.SendAsync("ReceiveMessage", _cache.Get("notification").ToString());
}
}
}
}
the table name in postgresql is called 'notification', i have two column called 'bericht' with type varchar and 'datumnu' with type date.
Edit suggested by mjwills
DateTime don't accept null value. Check if the value is null and assigne a default value
while (dr.Read())
{
not.Add(new NotificationModel { Datenow = ((DateTime) dr["datumnu"]).ToString("yyyy/MM/dd"), Bericht = dr["bericht"].ToString() });
}
Become
while (dr.Read())
{
DateTime defaultDateTime = DateTime.Now;
if(dr.IsNull("datumnu")){
defaultDateTime = (DateTime)dr["datumnu"];
}
not.Add(new NotificationModel { Datenow = defaultDateTime, Bericht = dr["bericht"].ToString() });
}
in single line
while (dr.Read())
{
not.Add(new NotificationModel { Datenow = (dr.IsNull("datumnu") ? DateTime.Now : (DateTime)dr["datumnu"]), Bericht = dr["bericht"].ToString() });
}

Truncated incorrect DOUBLE value: 'hello.world'

In my DAO, I have:
public void UpdateProfile(string newName, string newBio, long profileId)
{
using var dbConnection = _databaseProvider.GetConnection();
dbConnection.SetQuery($"UPDATE `profile_data` SET `name` = #newName AND `bio` = #newBio AND `fixed_unicode` = 1 WHERE `profile_id` = #profileId");
dbConnection.AddParameter("newName", newName);
dbConnection.AddParameter("newBio", newBio);
dbConnection.AddParameter("profileId", profileId);
dbConnection.ExecuteQuery();
}
It results in:
Unhandled exception. MySql.Data.MySqlClient.MySqlException (0x80004005): Truncated incorrect DOUBLE value: 'hello.world'
I don't understand why, because the name column is a varchar(255), verified via:
>> SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'profile_data' AND COLUMN_NAME = 'name'
>> varchar
Below I will place code references in my main example, for anyone to check out if it helps debug the issue.
_databaseProvider:
public class DatabaseProvider : IDatabaseProvider
{
private readonly string _connectionString;
public DatabaseProvider(string connectionString)
{
_connectionString = connectionString;
}
public DatabaseConnection GetConnection()
{
var connection = new MySqlConnection(_connectionString);
var command = connection.CreateCommand();
return new DatabaseConnection(connection, command);
}
}
DatabaseConnection:
public class DatabaseConnection : IDisposable
{
private readonly MySqlConnection _connection;
private readonly MySqlCommand _command;
public DatabaseConnection(MySqlConnection connection, MySqlCommand command)
{
_connection = connection;
_command = command;
_connection.Open();
}
public void SetQuery(string commandText)
{
_command.Parameters.Clear();
_command.CommandText = commandText;
}
public int ExecuteQuery()
{
return _command.ExecuteNonQuery();
}
public Task ExecuteQueryAsync()
{
return _command.ExecuteNonQueryAsync();
}
public MySqlDataReader ExecuteReader()
{
return _command.ExecuteReader();
}
public object ExecuteScalar()
{
return _command.ExecuteScalar();
}
public int GetLastId()
{
SetQuery("SELECT LAST_INSERT_ID();");
return int.Parse(ExecuteScalar().ToString());
}
public void AddParameter(string name, object value)
{
_command.Parameters.AddWithValue(name, value);
}
public void Dispose()
{
_connection.Close();
_command.Dispose();
}
}
You UPDATE query is incorrect. Replace AND keyword with a comma.
The query should look like this:
$"UPDATE `profile_data` SET `name` = #newName,
`bio` = #newBio,
`fixed_unicode` = 1
WHERE `profile_id` = #profileId"
Without executing your code, I can notice that your UPDATE command is not correct.
Try this
UPDATE `profile_data` SET `name` = #newName ,`bio` = #newBio ,`fixed_unicode` = 1 WHERE `profile_id` = #profileId");

I want to call a method from a different form

I want my TextBox to take information and run the code from a business object from a different form. I want it to run whenever the button is clicked.
I am having problems initializing the code. In theStudent.cs form it works fine I just want to pull the SelectDB() method into the StudentForm.
namespace SchoolReg{
public partial class StudentForm : Form
{
public StudentForm()
{
InitializeComponent();
}
private void StudentForm_Load(object sender, EventArgs e)
{
//ignore
}
private void StudentButton_Click(object sender, EventArgs e)
{
Student s1;
s1 = new Student();
txtboxIDStu.Text = s1.SelectDB(int);
}
private void txtboxIDStu_TextChanged(object sender, EventArgs e)
{
//ignore
}
}
namespace SchoolReg{
class Student : person
{
private double gpa;
//constructors
public Student():base()
{
gpa = 0;
}
public Student(int id, string fn, string ln, Address a1, string em, double gp) : base(id,fn,ln,a1,em)
{
gpa = gp;
}
//behaviors
public void setgpa(double gp) { gpa = gp; }
public double getgpa() { return gpa; }
//display
public void Display()
{
base.display();
Console.WriteLine("===================================");
Console.WriteLine("Gpa = " + gpa);
Console.WriteLine("===================================");
}
public System.Data.OleDb.OleDbDataAdapter OleDbDataAdapter2;
public System.Data.OleDb.OleDbCommand OleDbSelectCommand2;
public System.Data.OleDb.OleDbCommand OleDbInsertCommand2;
public System.Data.OleDb.OleDbCommand OleDbUpdateCommand2;
public System.Data.OleDb.OleDbCommand OleDbDeleteCommand2;
public System.Data.OleDb.OleDbConnection OleDbConnection2;
public string cmd;
public Student(int id)
{
SelectDB(id);
}
public void DBSetup()
{
OleDbDataAdapter2 = new System.Data.OleDb.OleDbDataAdapter();
OleDbSelectCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbInsertCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbUpdateCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbDeleteCommand2 = new System.Data.OleDb.OleDbCommand();
OleDbConnection2 = new System.Data.OleDb.OleDbConnection();
OleDbDataAdapter2.DeleteCommand = OleDbDeleteCommand2;
OleDbDataAdapter2.InsertCommand = OleDbInsertCommand2;
OleDbDataAdapter2.SelectCommand = OleDbSelectCommand2;
OleDbDataAdapter2.UpdateCommand = OleDbUpdateCommand2;
OleDbConnection2.ConnectionString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database L" +
"ocking Mode=1;Data Source=C:\\Users\\nicho\\OneDrive\\Desktop\\Database c#\\RegistrationMDB.mdb;J" +
"et OLEDB:Engine Type=5;Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:System datab" +
"ase=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Mode=S" +
"hare Deny None;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet " +
"OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repai" +
"r=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1";
}
public void SelectDB(int id)
{
DBSetup();
cmd = "Select * from Students where ID =" + id;
OleDbDataAdapter2.SelectCommand.CommandText = cmd;
OleDbDataAdapter2.SelectCommand.Connection = OleDbConnection2;
Console.WriteLine(cmd);
try
{
OleDbConnection2.Open();
System.Data.OleDb.OleDbDataReader dr;
dr = OleDbDataAdapter2.SelectCommand.ExecuteReader();
dr.Read();
Id = id;
setfname(dr.GetValue(1) + "");
setlname(dr.GetValue(2) + "");
Address a1 = new Address(dr.GetValue(3) + "", dr.GetValue(4) + "", dr.GetValue(5) + "", long.Parse(dr.GetValue(6)+""));
setAddr(a1);
setemail(dr.GetValue(7) + "");
setgpa(Double.Parse(dr.GetValue(8) + ""));
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
finally
{
OleDbConnection2.Close();
}
Console.WriteLine("===================================");
getSchedule();
Console.WriteLine("===================================");
}
/I think I am messing up in the StudentForm form. I'm sorry in advance because I feel like the answer is simple. Also for the messy layout, I don't usually post./
Okay, you're pretty close here, but you're missing a few steps
private void StudentButton_Click(object sender, EventArgs e)
{
Student s1;
s1 = new Student();
txtboxIDStu.Text = s1.SelectDB(int);
}
should be something like this
private void StudentButton_Click(object sender, EventArgs e)
{
string studentIdString = this.TEXTBOXNAME.Text; // This fetches the string from the input box and stores it. Replace TEXTBOXNAME with the name of your textbox that holds the ID.
bool inputIsNumber = Int32.TryParse(studentIdString , out studentIdInt); //Int32 TryParse tries to convert a given string into an integer. If it works inputIsNumber will be true, and the studentIdInt will be available as a variable.
if(inputIsNumber == false){
txtboxIDStu.Text = "Please enter a valid number";
return; //Bail out if we can't turn the string into a number
}
Student s1 = new Student(studentIdInt); //We're going to use the ID we created to build the student using the constructor
txtboxIDStu.Text = s1.fname + " " + s1.lastname; // By the time we've gotten here the constructor has fired, which also fired SelectDB() on that student. This just prints the name of the student, but if you want to improve this look up "Overrides" and create a ToString() override on your Student class.
}
You already have a constructor for student that takes an Id, which is exactly what we need.
public Student(int id)
{
SelectDB(id);
}

How can I pass my getters and setters parameters to connection class?

I assigned the textbox inputs to getters and setters also created one connection class. How can I pass my getters and setters parameters to connection class so I can use it inside my mainform.
MemberClass
private string srDatabase = "";
private string srID = "";
private string srPass = "";
public string SDB
{
get
{
return srDatabase;
}
set
{
srDatabase= value;
}
}
public string SID
{
get
{
return srID ;
}
set
{
srID = value;
}
}
public string SPassword
{
get
{
return srPass ;
}
set
{
srPass = value;
}
}
ConnectionClass
class Connection
{
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(dataSource) && !string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
con = new OracleConnection("Data Source=" + dataSource + ";User Id=" + userName.ToUpper() + ";Password=" + password + ";");
return con;
}
return con;
}
}
MainForm
UserMembers = new UserMembers();
txtSrcUserDatabase.Text = src.srDatabase ;
txtSrcUserID.Text=src.srID.ToUpper();
txtSrcUserPassword.Text = src.srPass;
OracleConnection conn1 = Connection.GetConnection() // **here error**
conn1.Open();
using (OracleCommand Names = new OracleCommand("SELECT TABLE_NAME FROM USER_TABLES ORDER BY TABLE_NAME", conn1))
{
using (OracleDataReader reader = Names.ExecuteReader())
{
while (reader.Read())
{
//Do something
}
}
}
Your method GetConnection requires three parameters. You need to pass them to the method.
UserMembers src = new UserMembers();
src.srDatabase =txtSrcUserDatabase.Text;
src.srID = txtSrcUserID.Text.ToUpper();
src.srPass = txtSrcUserPassword.Text;
OracleConnection conn1 = Connection.GetConnection(src.srDatabase, src.srID, src.srPass)
conn1.Open();
......
Or you could pass the instance of UserMembers to the GetConnection method creating an overload of GetConnection like this
class Connection
{
// the first overload that takes 3 string parameters
public static OracleConnection GetConnection(string dataSource, string userName, string password)
{
....
}
// The second overload that takes an instance of UserMembers
public static OracleConnection GetConnection(UserMembers src )
{
OracleConnection con = null;
if(!string.IsNullOrWhiteSpace(sr.srDatabase) && !string.IsNullOrWhiteSpace(sr.srID) && !string.IsNullOrWhiteSpace(sr.srPass))
{
con = new OracleConnection("Data Source=" + sr.srDatabase + ";User Id=" + sr.srID.ToUpper() + ";Password=" + sr.Pass + ";");
}
return con;
}
}
As a side note. If you need the srID member to be always in upper case then move this logic in the setter property, and you could stop to worry about the proper formatting of this member when you try to read it back
public string SID
{
get { return srID ; }
set { srID = value.ToUpper(); }
}

Categories