C# console application Invalid Operation Exception - c#

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
namespace BissUpdater
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=H....;
Initial Catalog=LANDesk; Persist Security Info=True;
User ID=Mainstc; Password=xxxxxxxx";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
}
}
}
The SQL Connection threw a invalid operation exception.
"Invalid Operation. The connection is closed".
This is my complete Code. In a other program, it works perfect.
That is the second time, that doesnt work. Im working with VS2005...maybe my program is damaged?
Stacktrace:
at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at
System.Data.SqlClient.SqlConnection.get_ServerVersion()

The correct way doing that should be something like:
static void Main(string[] args) {
string connectionString = "Data Source=H....;
Initial Catalog=LANDesk;User ID=Mainstc; Password=xxxxxxxx";
// removed Persist Security Info=True;
using(SqlConnection con = new SqlConnection(connectionString))
{
if (con.State==ConnectionState.Closed)
{
con.Open();
}
}
}
Using Using Statement it will automatically dispose your SQL connection.
Check this also: Best Practices for Using ADO.NET on MSDN
Other things to do: Use SQL Management Studio and try to use your sql authentication login credential from your connection string and if you have successfully connected to your database using that account the above code should work for you.
Best Regards

The code should read
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
...
}

Try add this code. You probably has open connection and while rerun program you try to again open connection or you have problem with server or your connection string
con.Close();
See there for more info http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx

you can check connection state before opening ittry this :
SqlConnection con = new SqlConnection(connectionString);
if (con.State==ConnectionState.Closed)
{
con.Open();
}
// here your code goes for sql operations
con.Close();

Try to use using statements. Direct manually opening and closing data bases in case of large databases is bad idea.
using(SqlConnection con = new SqlConnection(connectionString))
Try to do like this for open and close connections>>
public DB(string conStr):base()
{
con = new OracleConnection(conStr);
con.Open();
}
public void Close()
{
con.Close();
//con.Dispose();
}
Hope Helpful.

I was having same problem, my solution in VB is:
Dim db As New Database
' ... Some Work with EF without procedures (90 seconds)
db.SaveChanges()
For Each p In list
If db.Database.Connection.State <> ConnectionState.Open Then
' This is only executed 1 time
db.Database.Connection.Open()
End If
' ... Some Work with EF but calling a mapped procedure (1 or 2 seconds each call)
db.MyProcedure(p.FieldId)
Next
db.Dispose()
But the total time was 200 seconds, so I had to change this in my WebConfig of my WebService:
<system.web>
<httpRuntime executionTimeout="600" /> <!--10 min-->
...

Related

CLR Stored Procedure Unable to connect with SqlConnection Regular Connection

I tried to create a CLR stored procedure in VS2017 but encountering error "NOT Connected." while executing that stored procedure.
I need to connect to other database server to grab some data. Therefore I cannot use context=true in SqlConnection.
Stored procedure will be created in serverA
This stored procedure will query data from serverB
Data will be stored back to serverA.
Is there anything I need to do in order to have regular connection in CLR stored procedure?
Please advise. Thanks!
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void udp_CLR_GetData()
{
string ConnStr = "server=MyServer; database=MyDB; user id=accabc; password=abc123";
string sql = " select top 1 ID from [dbo].Table1 ";
SqlDataReader dr = null;
DataTable dt = new DataTable();
try
{
using (SqlConnection fcon = new SqlConnection(ConnStr))
{
if (fcon.State == ConnectionState.Open)
{
SqlContext.Pipe.Send("Connected.");
using (SqlCommand fcmd = new SqlCommand(sql, fcon))
{
SqlContext.Pipe.Send("Before executing reader...");
dr = fcmd.ExecuteReader();
SqlContext.Pipe.Send("After executing reader...");
SqlContext.Pipe.Send("Before send...");
SqlContext.Pipe.Send(dr);
SqlContext.Pipe.Send("After send...");
}
}
else
{
SqlContext.Pipe.Send("NOT Connected.");
}
}
}
catch(Exception ex)
{
SqlContext.Pipe.Send("Exception error (udp_CLR_GetData): " + ex.Message);
}
finally
{
if(dr != null && !dr.IsClosed)
{
dr.Close();
}
}
}
}
Creating a new instance of a SqlConnection in:
using (SqlConnection fcon = new SqlConnection(ConnStr))
does not create it in an "open" state. You need to actually open it for it to be "open". So, I would remove the if (fcon.State == ConnectionState.Open) and the associated else part of it. I would also remove the SqlContext.Pipe.Send("Connected."); line.
Then, just before the dr = fcmd.ExecuteReader(); line, add a line for:
fcon.Open();
This way you open the connection and immediately execute the command. No need to open the connection only to do other work getting the command ready.
For more info on working with SQLCLR in general, please visit: SQLCLR Info
Try defining the data source in the connection string instead of server
string ConnStr = "DataSource=MyServer;Initial Catalog=MyDB;User Id=accabc;Password=abc123";
other than that, make sure clr is enabled on the server:
https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration/clr-integration-enabling?view=sql-server-ver15

how to solve exception for the connection string(local database c#)

ok so the first problem is the connection string itself it has this exception that i do not understand so i tried to put it in a try catch syntax but as i inserted it in the public partial class Form1 : Form the parenthesis are acting up so i inserted it in a function and now the fuction has this error:
Severity Code Description Project File Line Suppression State
Error CS0161 'Form1.connection()': not all code paths return a value Restaurant Management System C:\Users\admin\source\repos\Restaurant Management System\Restaurant Management System\Form1.cs 36 Active
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Restaurant_Management_System
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.BackColor = Color.FromArgb(50, Color.Black);
label1.BackColor = Color.FromArgb(30, Color.Beige);
label2.BackColor = Color.FromArgb(0, Color.Black);
Password.BackColor = Color.FromArgb(0, Color.Black);
}
SqlCommand cmd;
SqlDataReader dr;
public SqlConnection connection()
{
try
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename= \"|Data Directory|\\Coffee(LoginEmployee).mdf\";Integrated Security=True;");
}
catch (Exception ex)
{
MessageBox.Show("Error message: COULD NOT CONNECT STRING: " + ex);
}
}
private string getUsername()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Username", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
private string getPassword()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Password", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
What do i need to replace? why does it not all return a value? if i use the void case it will also have this error that i cannot explicitly convert it to sqlconnection. this is made in the latest visual studio 2017
If you catch the exception, no SqlConnection will be returned. So you could return null after showing the message box.
Then of course, you will need to do a null check after calling connection() so you don't get a null reference exception trying to use it.
You also need to return the connection you are creating:
return new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|Data Directory|Coffee(LoginEmployee).mdf;Integrated Security=True;");
Note: I don't recommend hard-coding your connection string either! You would normally add the connection string to your app.config/web.config and read it using ConfigurationManager.ConnectionStrings... - this is because you might have different instance names on different machines, or you might want to point to a database on a server rather than local. You will not need to change the code and recompile just to make it work on more than one machine.
There is information on microsoft's class library site (https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.attachdbfilename(v=vs.110).aspx) saying: An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.

Check online connection with SQL server, switch to offline C# Windows Application

I have a C# Windows app that I am creating with connection to a MS SQL server. I need the ability to switch to a local instance of SQL Server express if connectivity is down. This app is in a remote area where online is hit and miss. When connectivity goes down, I need the connection strings to reflect to the local server. I have logic to resync items from the local db to the live one once connection is restored. However, I am having issues trying to test connectivity automatically. The connection string in my app.config has both live and offline connections with the following code:
SqlConnection con = new SqlConnection(Properties.Settings.Default.MyLiveConnectionString);
If connection goes down, I want the local connection to use:
SqlConnection con = new SqlConnection(Properties.Settings.Default.MyLocalConnectionString);
Does anyone have a suggestion on how to make this happen seamlessly and quick?
I can test connections using try/catch, but it takes several seconds to time out before continuing.
public void Connect()
{
string connectionStr = string.Empty;
try
{
if(CheckConnection(Properties.Settings.Default.MyLiveConnectionString))
connectionStr = Properties.Settings.Default.MyLiveConnectionString;
}
catch (Exception ex)
{
//Log this, etc...
}
if (string.IsNullOrWhiteSpace(connectionStr))
connectionStr = Properties.Settings.Default.MyLocalConnectionString;
using (SqlConnection conn = new SqlConnection(connectionStr))
{
}
}
private static bool CheckConnection(string connectionString)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT 1", conn);
conn.Open();
if ((int)cmd.ExecuteScalar() == 1)
return true;
}
return false;
}

asp.net ExecuteReader requires an open and available Connection. The connection's current state is open [duplicate]

This question already has answers here:
ExecuteReader requires an open and available Connection. The connection's current state is Connecting
(2 answers)
Closed 7 years ago.
My ERP web application written in c#.net throwing this error frequently
I have Globals.cs file under App_Code folder like:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Data.Sql;
public static class Globals
{
public static string mycon = ConfigurationManager.ConnectionStrings["WebConnStr"].ConnectionString;
public static SqlConnection con = new SqlConnection(mycon);
public static SqlCommand cmd = new SqlCommand();
public static SqlDataReader dr;
public static void Initialize(string CmdType, string CmdText)
{
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
cmd.Connection = con;
if (CmdType == "StoredProcedure")
{
cmd.CommandType = CommandType.StoredProcedure;
}
else
{
cmd.CommandType = CommandType.Text;
}
cmd.CommandText = CmdText;
cmd.Parameters.Clear();
}
catch (Exception ex)
{
}
}
}
my connection string in web.config looks like:
<connectionStrings>
<add name=WebConnStr connectionString="Data Source=servername;Initial Catalog=dbname;User ID=username; Password=12345" providerName="System.Data.SqlClient"/>
</connectionStrings>
my sample aspx.cs codes like:
Gridview Bind:
DataTable dt = new DataTable();
Globals.Initialize("StoredProcedure", "[sp_getemp]");
Globals.dr = Globals.cmd.ExecuteReader();
dt.Load(Globals.dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Insert Query:
Globals.Initialize("StoredProcedure", "[sp_insertemp]");
Globals.cmd.Parameters.AddWithValue("#EmpID", txtempid.Text);
Globals.cmd.ExecuteNonQuery();
Data Reading:
private string GetEmpName(string empcode)
{
Globals.Initialize("Text", "SELECT EmpName from tbl_emp where EmpID=#EmpID");
Globals.cmd.Parameters.AddWithValue("#EmpID", empcode);
Globals.dr = Globals.cmd.ExecuteReader();
if (Globals.dr.Read() == true)
{
return Globals.dr["EmpName"].ToString();
}
else
{
return "";
}
}
May I know what might have gone wrong in Globals.cs file and how do I fix it?
That is why you should be using the using statement to get rid of this type of error. Something like
using (SqlConnection connection = new SqlConnection(connectionString))
{
//some code
}
You can refer this MSDN and read about connection pooling:
In practice, most applications use only one or a few different
configurations for connections. This means that during application
execution, many identical connections will be repeatedly opened and
closed. To minimize the cost of opening connections, ADO.NET uses an
optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections
must be opened. The pooler maintains ownership of the physical
connection. It manages connections by keeping alive a set of active
connections for each given connection configuration. Whenever a user
calls Open on a connection, the pooler looks for an available
connection in the pool. If a pooled connection is available, it
returns it to the caller instead of opening a new connection. When the
application calls Close on the connection, the pooler returns it to
the pooled set of active connections instead of closing it. Once the
connection is returned to the pool, it is ready to be reused on the
next Open call.
Looks like you need to open a connection before executing code, and example being conn.Open();

OleDB connection string for SQL Server in a C# program

I have seen lots of answers to connect to MS Access via OleDB but there is not good answer for SQL Server. I try to connect to a SQL Server database via OleDB provider in my C# program.
This is the connection string I am providing.
Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI
But it gives me error
‘Keyword not support ‘Provider’’
What I want to do here is connect database via OleDB in C# program.
This works as expected on my side. From the error message I strongly suspect that you are using the SqlConnection class instead of the OleDbConnection (Of course you need to use all the other classes provided by OleDb like OleDbCommand, OleDbDataReader etc...)
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(OleDbConnection cnn = new OleDbConnection(connStr))
{
....
}
When in doubt, use the string builder in visual studio. That way unsupported keywords can't creep into your connection strings, the following is a wonderful example on how to use it.
http://www.c-sharpcorner.com/uploadfile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/
The same Connection string is working fine at my end.
I am posting my sample code which is executes successfully at my end
public string connStr = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=<dbName>;Integrated Security=SSPI";
public OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
public void Test()
{
con = new OleDbConnection(connStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from tblApartments", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
Please place breakpoint and check line to line and when your breakpoint comes to con.close(); then check ds, you can see the output.
The connection string you're using, considering the OLE DB provider, is correct. I didn't find any error in the connection string used, if you want to connect to a SQL Server data source.
Most probably, the reason of that error should be that you're not using correctly all the classes and objects required by the OLE DB provider, like OleDbCommand (that is similar to a SqlCommand but it's different), OleDbConnection, OleDbDataAdapter and so on. In a nutshell, the reason of that error should be this:
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(SqlConnection scn = new SqlConnection(connStr))
{
....
}
Indeed, using a SqlConnection object, the ConnectionString property doesn't support the keyword Provider and, executing your application, you got an error about a keyword not supported.
Have a look at this simple tutorial about the use of OLE DB provider.

Categories