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
Related
I am try to connect SQL Server using multi-threading the execute SQL query on tables.
When I try to connect SQL server it's working fine without any issue, but when try to connect using thread mechanism it displaying exception.
Here is my code can exception message please let me know how to resolve this issue.
using System;
using System.Data.SqlClient;
using NUnit.Framework;
using System.Threading;
namespace ThreadSQLConnect
{
[TestFixture]
public class SQLConnect
{
private static object threadLock = new object();
[Test]
public void temp()
{CreateThread(1); }
public static void CreateThread(int ThreadCount)
{
Thread[] workerThread = new Thread[ThreadCount];
for (int i = 0; i < ThreadCount; i++)
{
workerThread[i] = new Thread(new ThreadStart(ConnectDBAndExecuteQueryWithLock));
workerThread[i].Name = i.ToString();
workerThread[i].Start();
}
}
public static void ConnectDBAndExecuteQueryWithLock()
{
lock (threadLock)
{
try
{
string sqlQuery = "insert into tblMasterLookup Values (" + Thread.CurrentThread.Name + ",'Test','2.0','Myapplication',GetDate())";
string connectionString = string.Format("Server={0}; Database = {1}; User Id = {2}; Password = {3};",
"serverNname",
"Databasename",
"ReadOnlyUser",
"ReadOnly12");
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch(Exception e)
{ Console.WriteLine(e.StackTrace); }
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
command.CommandTimeout = 80;
command.ExecuteNonQuery();
Console.WriteLine("Executed Thread.. " + Thread.CurrentThread.Name);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
}
Here is exception message
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'"
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");
}
}
I am trying to import excel file into SQL Server 2005 in C#, but I', getting an error.
Here's my code:
namespace excel
{
public partial class Csharp_Excel : Form
{
public Csharp_Excel()
{
InitializeComponent();
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
private void button1_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path = Path.Combine(path, "csharp-Excel.xls");
string connStr = #"Server=.\\SQLEXPRESS;Data Source= C:\\Users\\adil pc\\Documents\\Visual Studio 2008\\Projects\\excel\\excel\\bin\\Debug\\csharp-Excel.xls;Initial Catalog=RMS;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(connStr);
string strCmd = "select * from [sheet1$A1:E7]";
SqlCommand cmd = new SqlCommand(strCmd, con);
try
{
con.Open();
ds.Clear();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
}
}
private void btnsend_Click(object sender, EventArgs e)
{
}
}
The error that I am getting is:
System.Data.SqlClient.SqlException: A network-related or instance-specified error occurred while establishing a connection to SQL Server
I think I got it working I made some changes in connection string :
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\csharp-Excel.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";
it is working on demo havent implement in actual project once I do will update.
I'm very new to programing and am trying to link a database to a website. I want the website to allow a user to make a username (OrgID) and password (OrgPassword) and have them apear in my database table (Organizer). This is the code I have so far, but I cannot get it to update the information in the database. Does anyone have any suggestions?
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
if (txtUserName.Text != "" && OrgPassword.Text !="")
{
string cnnString = "Provider= Microsoft.ACE.OLEDB.12.0; Data Source =C:/Users/codym/Desktop/Fall 2011/Information Systems/Project/CampuSpaceDatabase2.accdb";
OleDbConnection cnx = new OleDbConnection(cnnString);
OleDbDataAdapter adapter = new OleDbDataAdapter();
string cmdText= "SELECT * FROM Organizer";
OleDbCommand cmd = new OleDbCommand(cmdText, cnx);
adapter.SelectCommand= cmd;
adapter.Fill(Organizer);
Session["Organizer"]= Organizer;
Organizer= ((DataTable)Session["Organizer"]);
string orgname = OrgID.Text;
string orgpass = OrgPassword.Text;
foreach (DataRow in Organizer.Rows)
{
if(row["OrgID"].ToString() == orgname & row["OrgPassword"].ToString() == orgpass)
{
errLabel.Text = "Welcome "+ row["OrgID"].ToString();
return;
}
else
{
errLabel.Text = "OrgID/Password Invalid";
return;
}
}
}
}
It looks like you are missing opening the connection:
OleDbConnection cnx = new OleDbConnection(cnnString);
cnx.Open();