System. InvalidOperationException - c#

I'm trying to make a program with a login system
I'm new to this but I have been working 8 hours straight trying to fix this.
This is the error code I get
+ ServerVersion 'con.ServerVersion' threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException}
Here's my code
private void LogB_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=Myip;user id=MyId;database=MyDb;password=MyPw;persistsecurityinfo=True");
SqlDataAdapter sda = new SqlDataAdapter("Select * From login where navn='"+ TULog.Text + "' and pw='" + TPLog.Text + "'",con);
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
throw ex;
}
finally
{
con.Close();
}
}
}
}
Sorry If this seems like some crap but I'm a guy who's trying to learn :p

This exception is telling you that there was an attempt to access the con.ServerVersion property while the SqlConnection was closed.
From MSDN on the SqlConnection.ServerVersion property:
InvalidOperationException - The connection is closed. ServerVersion was called while the returned Task was not completed and the connection was not opened after a call to OpenAsync.
The code you show above does not show a call to this property, you must be doing so somewhere else. Regardless, the connection needs to be open prior to doing so.

Related

Handling request errors in OracleDataAdapter.Fill()

I am writing a client application using System.Data.OracleClient. With an error in writing a select query when calling the OracleDataAdapter.Fill (DataSet) function, I understand that an error occurs inside, but the program, when executing this function, interrupts the execution of the body of the function in which this string is located. Binding OracleDataAdapter.Fill Error event or "try" construct does not fire.
How can I catch errors like this?
string select = "SELECT qwe FROM employee"; // 'employee' does not contain 'qwe'
OracleDataAdapter adapter = new OracleDataAdapter(select, connection);
adapter.FillError += Adapter_FillError;
try
{
adapter.Fill(ds, "zak");
}
catch (OracleException ex)
{
MessageBox.Show(ex.Message);
}
private void Adapter_FillError(object sender, FillErrorEventArgs e)
{
MessageBox.Show(e.Errors.Message);
}

Form not Responding when select database [duplicate]

This question already has answers here:
WinForms app seems "Not Responding" while fetching data from database?
(3 answers)
Closed 4 years ago.
Every time when i open my program, it's say "Not Responding".
though on my form event load only retrieve data from database.
private void form1_Load(object sender, EventArgs e)
{
//LoadDb_1()
//LoadDb_2()
//LoadDb_3()
}
i have tried to put the load database in the form1_shown event, but it's not working either.
how do i overcome this ?, i don't want to wait a several minutes to use the program.
PS: i have no idea how to use thread or async
UPDATE
example inside LoadDb_1()
public void LoadDb_1()
{
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
Datatable dt_main = new Datatable();
try
{
dt_main.Clear();
myConnection.Open();
command.Connection = myConnection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "General.SP_Car";
adapter.SelectCommand = command;
adapter.Fill(dt_main);
gridControl1.DataSource = dt_main;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
You have blocking action, blocking the main thread, this is why your application in not responding, to fix this depends how you are connecting to the database, EF6 or EFCore, basic, dapper....
As you say, you don't know async programming or multithreading, one way to do it, connect to the database when you need, for example on some click, you then connect to the database, get the data and then shut the connection down, the application will not be responding for a few seconds, but that's one way...
You have one big problem in your application as i say, not just not responding windows, you connection is always open, you shouldn't do that, you are making your app and your server vulnerable
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection("your connection string....");
try
{
cnn.Open();
SqlCommand myCommand = new SqlCommand("SQL query....", cnn);
SqlDataReader reader = myCommand.ExecuteReader();
while(reader.Read())
{
// Access the columns by reader["columnName"]
}
// Don't forget to close the connection
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
Useful links:
Learn more about native c# to sql connection : https://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Use sqlconnection with winForms: http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm
Connection strings: https://www.connectionstrings.com/
Check on youtube for Tim Corey (https://www.youtube.com/user/IAmTimCorey) , he has great c# tutorials for Threading, async/await, dapper, ASP.NET and much more

StackOverflowException on Singleton

My Singleton is throwing a StackOverflowException, but yesterday it worked fine and the unique change was the database in the Connection String. It is a console application and the debug is very complicated:
class OracleSingleton
{
private static OracleConnection instance;
private OracleSingleton() { }
public static OracleConnection Instance
{
get
{
if (instance == null)
{
try
{
instance = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleConnection"].ConnectionString);
}
catch (Exception ex)
{
LogHelper.WriteMessage("Error trying to create a new connection. - " + ex.Message.ToString() + " - " + ex.InnerException.ToString().Trim());
}
}
return instance;
}
}
}
My App.config:
<configuration>
<connectionStrings>
<add name="OracleConnection" connectionString="Password=somepassword;Persist Security Info=True;User ID=someuser;Data Source=DATABASE01"/>
</connectionStrings>
//Some stuff
</configuration>
Can you guys show me what is wrong and why yesterday it worked fine?
EDIT:
I use the Singleton to do a lot of things. I Know that the problem is in the singleton because my application shows the StackoverflowException without log anything, who is one of the places where I use the Singleton. Below, my LogHelper.WriteMessage method, who is called at the first line of program to say" Hi, the application is running right now ":
public static void WriteMessage(string info)
{
using (OracleConnection conn = OracleSingleton.Instance)
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO TB_LOG (DT_LOG, ID_PERMISSAO, ID_USUARIO, NM_USUARIO, DS_LOG) VALUES (TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS'), 5025, 5025, 'IMPORTADORCAIXA', '" + info + "')", conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
} catch (Exception ex)
{
Console.WriteLine(DateTime.Now + " - Erro ao conectar com o banco. por favor, verifique o erro: " + ex.Message.ToString() + ", " + cmd.CommandText.ToString());
}
}
}
new LogHelper();
eventLog.WriteEntry(info);
Console.WriteLine(DateTime.Now + " - " + info);
}
Your "singleton" is indeed recursive on some paths. What happens if this line
instance = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleConnection"].ConnectionString);
throws exception, for example if connection string is invalid? You log that exception with WriteLog which again references singleton with
using (OracleConnection conn = OracleSingleton.Instance)
So if connection string is invalid, or connection creation constantly fails for other reason - you go into recursion and eventually end with StackOverflowException when stack space is exhausted.
By the way, with
using (OracleConnection conn = OracleSingleton.Instance)
you also dispose your connection, making it unusable for subsequent invocations.
Best way to resolve it is to just get rid of singleton, there is no need for it. It's bad practice to have global connection - just create it every time you need it and dispose (close) when you are done with it. Connection pool will manage the rest for you.
If you don't want to do serious refactoring for some reason, at least change to something like this:
public static OracleConnection Create() {
// no need to catch any exceptions here
return new OracleConnection(ConfigurationManager.ConnectionStrings["OracleConnection"].ConnectionString);
}
And use as you already do:
using (OracleConnection conn = OracleSingleton.Create())

Exception handling (I want to check if the connection.Open() runs)

I'd like my code to give a warning or something whenever the database is not available.
(That's why I commented the connection string), but my website just crashes.
I created this class cause there were many parts of the program using this connection string (login page, register page, user panel page, etc), so if I want to change something in the future, this is the only string I have to change.
namespace Fatture.Data.User
{
public class DbConnection
{
public MySqlConnection ConnessioneDb()
{
MySqlConnection conn = new MySqlConnection(/*ConfigurationManager.ConnectionStrings["ConnectionStringloginDb"].ConnectionString*/);
try
{
conn.Open();
}
catch (Exception ex)
{
throw new Exception("I can't connect to the database", ex);
}
return conn;
}
}
}
Use exception handling...
var connector = new DbConnection();
try
{
var connection = connector.ConnessioneDb();
}
catch (Exception ex)
{
// show message to user: database not available
}
Though you'll have to put this in place everywhere you access the database. Instead you can also just set up error handling for your entire site.
Catch the exception...
try
{
var conn = new DbConnection().ConnessioneDb();
}
catch (Exception ex)
{
// Notify user here
}

I am not able to connect to my SQL Server database

public partial class Variables_input : System.Web.UI.Page
{
public string conStr = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
protected void Buttonsubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(conStr))
{
try
{
con.Open();
Response.Write("<script language ='javascript'>alert('Connection is open');</script>");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Response.Write("<script language ='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
Response.Write("<script language ='javascript'>alert('Connection is close');</script>");
}
}
}
I am not able to connect to connect my SQL Server database. After running this code I receive "Connection Problem". Please help.
I don't know where to begin to start.
You are using SQL server not mySQL right, you have funny wording. Just want to make sure.
You might want to try looking at the exception data, usually it gives you an error message. You caught the error now read it.
If the error message is not helpful you could put a breakpoint at con.Open() and step into an make sure all the parameters are correct or see where the problem is if the exception error doesn't help.
Might also want to look at this:
dot net pearl for sqlconnection

Categories