Stored procedure couldn't be reached - sql-server

The stored procedure cannot be executed. Can anyone please advise me and point out my stupid mistake?
The error message that I got is
Invalid operation. The connection is closed
Code:
public void Update(RepliesBAL RPBAL)
{
using (SqlConnection connection = new SqlConnection(#"Data Source=19NNZP;Initial Catalog=ivr;Persist Security Info=True;User ID=sa;Password=sa"))
{
SqlCommand command = new SqlCommand ();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.fax_UpdateFaxReply";
command.Parameters.Add("#uid", SqlDbType.VarChar, 50).Value = RPBAL.UlyssesID ;
SqlTransaction transaction;
transaction = connection.BeginTransaction("SampleTransaction");
command.Connection = connection;
command.Transaction = transaction;
try
{
connection.Open();
command.ExecuteNonQuery();
Console.WriteLine("OK");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
throw new Exception(ex.Message);
}
}
}
}

In order to call .BeginTransaction(), your connection needs to be opened already - so change your code to:
using (SqlConnection connection = new SqlConnection(#"Data Source=19NNZP;Initial Catalog=ivr;Persist Security Info=True;User ID=sa;Password=sa"))
{
// set up the SqlCommand
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.fax_UpdateFaxReply";
// SqlDbType should be *NVarChar* to exactly match the stored procedure parameter's type!
// Otherwise you'll have an implicit conversion happening....
command.Parameters.Add("#uid", SqlDbType.NVarChar, 50).Value = RPBAL.UlyssesID ;
SqlTransaction transaction;
try
{
// open connection, start transaction
connection.Open();
transaction = connection.BeginTransaction("SampleTransaction");
// assign transaction to SqlCommand and execute it
command.Transaction = transaction;
command.ExecuteNonQuery();
// if successful - commit the transaction!
transaction.Commit();
connection.Close();
Console.WriteLine("OK");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
throw new Exception(ex.Message);
}
}
}
After that change, hopefully, this code should work just fine.

Related

SqlDependency Works with local DB but not with servers

using this code:
private async Task<object> ChatNotification()
{
try
{
string cs =dbConnectionStr;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string cmdText = #"SELECT
[dbo].[ChatMessage].[Id],
[dbo].[ChatMessage].[fkUserId],
[dbo].[ChatMessage].[fkGroupId],
[dbo].[ChatMessage].[Message],
[dbo].[ChatMessage].[DateTime],
[dbo].[ChatMessage].[IPAddress]
FROM [dbo].[ChatMessage] ";
SqlClientPermission permission =
new SqlClientPermission(
PermissionState.Unrestricted);
try
{
permission.Demand();
}
catch (System.Exception ex)
{
}
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
cmd.Notification = null;
SqlDependency tradeInfoDependency = new SqlDependency(cmd);
tradeInfoDependency.OnChange += DependencyNotify_OnChange;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader reader = cmd.ExecuteReader();
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return Ok( );
}
//dependency******
private async void DependencyNotify_OnChange(object sender, SqlNotificationEventArgs e)
{
ChatNotification().Wait();
var dependency = sender as SqlDependency;
if (dependency == null) return;
if (e.Info == SqlNotificationInfo.Insert || e.Info == SqlNotificationInfo.Merge)
{
var chats = _dbContext.ChatMessage.FromSql(#"SELECT * FROM [dbo].[ChatMessage] " +
"WHERE IsSeenByAdmin=0").OrderBy(c => c.DateTime).ToList();
dependency.OnChange -= DependencyNotify_OnChange;
await _chatAdminHubContext.Clients.All.SendAsync("AdminListen",
chats);
}
}
public Startup(IConfiguration configuration)
{
SqlDependency.Start(dbConnectionStr);
Configuration = configuration;
}
the whole thing works with this connection string which is connected to my localdb:
private readonly string dbConnectionStr=
"Data Source=.;Initial Catalog=signalr;Integrated Security=True;user id=sa;password=******";
but it does not work if i change the connection string to this:
private readonly string dbConnectionStr=
"Data Source=server.*****.com\\MAININSTANCE;Initial Catalog=signalr;Persist Security Info=True;User ID=sa;Password=********";
i can connect to the server and local db with no problem, and can use fetching data with entityframework from both, the connection is made successfully yet the only problem is that when i insert row in localdb [dbo].[ChatMessage], dependency works but when i insert row in servers [dbo].[ChatMessage], it does not.
the only thing i did was to set broker enabled. Could it be related to any permissions on server's db?
UPDATE:
select * from sys.transmission_queue
gives this transmission_status:
An exception occurred while enqueueing a message in the target queue. Error: 15517, State: 1. Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission. 5

sqlite attach password protected database

How can I attach a password protected sqlite database to a non password protected database?
I have a user sqlite database that is not password protected.
I'm trying to attach a read-only resource database that is password protected.
I could reverse their roles and open the password protected first and attach the user database, but I think it should work this way?
I haven't tried too many things so there is no code to share. but I have googled and can't seem to find any mention of this in the documentation or any examples.
It's all about opening a password protected database directly.
Edit: - heres what i've tried...
using both https://www.sqlite.org/lang_attach.html https://www.sqlite.org/c3ref/open.html
private void btnPasswordAttach_Click(object sender, EventArgs e)
{
string pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Users #1.astc";
string connectionstring = string.Format("Data Source={0};Version=3;BinaryGUID=false", pathToUnProtected);
SQLiteConnection connection = new SQLiteConnection(connectionstring);
connection.Open();
TestQueryMain(connection); **//WORKS**
pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Mods #1.aste";
string commandTextUnProtected = string.Format("ATTACH DATABASE '{0}' AS mods", pathToUnProtected);
SQLiteCommand attachCommandUnProtected = new SQLiteCommand(commandTextUnProtected, connection);
attachCommandUnProtected.ExecuteNonQuery();
TestQueryUnProtected(connection); **//WORKS**
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite";
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
//string pathToProtected = #"file:C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite;password=VanillaIceCream;";
string password = "VanillaIceCream";
string commandText = string.Format("ATTACH DATABASE '{0}' AS vanilla", pathToProtected);
SQLiteCommand attachCommandProtected = new SQLiteCommand(commandText, connection);
attachCommandProtected.ExecuteNonQuery();
TestQueryProtected(connection); **//NO SUCH TABLE...**
}
private void TestQueryMain(SQLiteConnection connection)
{
string sql = "Select * FROM Notes";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteReader();
}
private void TestQueryProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from vanilla.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
private void TestQueryUnProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from mods.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
found the answer in another post:
https://stackoverflow.com/a/1385690/10099912
to attach a password protected sqlite database you need to use the 'key'word:
"ATTACH DATABASE 'C:\test.sqlite' AS attachedDb KEY 'password'"

Having trouble with SQL Delete on SQL Server using C#

I am running this code but it throws an exception and I am not sure why. Any help would be appreciated. I checked the ID and it was the right ID for the record.
protected void DeleteSQLDB(int id)
{
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=" + id;
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
m_dbConnection.Open();
cmd.ExecuteNonQuery();
m_dbConnection.Close();
}
}
}
catch (Exception ex)
{
Response.Redirect("somwhere");
}
finally
{
}
}
I solved the problem. The reason was that the record was referenced in other tables so I had to remove the references before I could remove the record. Thanks user7396598 for advice about running query manually. This is the code which removes the conversations first and then the student record:
//This deletes the archived student, First any conversations need to be deleted before the record can be removed.
protected void DeleteSQLDB(object id,String studentID)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblConversations WHERE StudentID=#studentID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#studentID", studentID);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
DeleteSQLDB2(id);
}
}
protected void DeleteSQLDB2(object id)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=#ID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#ID", id);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
Response.Redirect("studentgrid.aspx");
}
}

Database entry not done

try
{
// Data Source=FAHAD-PC\SQLEXPRESS;Initial Catalog="Student management";Integrated Security=True
// server=FAHAD-PC\\SQLEXPRESS;database=Student management;
String str = "Data Source=FAHAD-PC\\SQLEXPRESS;Initial Catalog=Student management;Integrated Security=True;";
String query = "Insert into Users (Username, Password) values('usern' , 'userpassword');";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
DataSet ds = new DataSet();
MessageBox.Show("connect with sql server");
con.Close();
MessageBox.Show("Inserted sucessfully");
usern = " ";
userpassword = " ";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
here is the code my connection is successfull and the query insterted msg is also show but cant get the entry in my db.
Try code below
try
{
// Data Source=FAHAD-PC\SQLEXPRESS;Initial Catalog="Student management";Integrated Security=True
// server=FAHAD-PC\\SQLEXPRESS;database=Student management;
String str = "Data Source=FAHAD-PC\\SQLEXPRESS;Initial Catalog=Student management;Integrated Security=True;";
String query = "Insert into Users (Username, Password) values('usern' , 'userpassword');";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("connect with sql server");
con.Close();
MessageBox.Show("Inserted sucessfully");
usern = " ";
userpassword = " ";
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

Issue with database connect

In this section I get the error
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
try
{
SqlCommand cmd = new SqlCommand("delete from sug where IDbro='" + ime + "'and AtributValue='+atr+' and [+/-]='+rat+' ", conn);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
finally
{
conn.Close();
}
GridView2.DataBind();
promenaP();
}
I have issue with database deleting error exception
Try this
SqlCommand cmd = new SqlCommand("delete from sug where IDbro='" + ime + "'and AtributValue='"+atr+"' and [+/-]='"+rat+"' ", conn);
add ""
I had similar issue programming android sqlite...

Resources