Unable to Connect SQL Server when using MultiThreading - sql-server

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

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");
}
}

Is there a utility to dump an existing log4j log file into a relational database?

Seems, like a very basic thing, but I could not find it.
I have a bunch of log4j/log4net log files. I would like to dump them into a database in order to be able to analyze them with ease.
I thought I would find a tool to do it in no time, apparently I am wrong.
Does anyone know of such a tool?
OK, so I found no utility. Had to write my own. Of course, it is strictly tailored to my immediate needs (time is money), however, it can save you a bit of time to start your own, in case of a need. Here is the complete code in C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
public class LogEntry
{
private const string PATTERN = #"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{4}) (\S+) \[(\d+)\] (\w+) (\S+) - (.*)$";
private static readonly Regex s_regex = new Regex(PATTERN, RegexOptions.Compiled);
public DateTime TS;
public string Machine;
public int Thread;
public string Level;
public string Logger;
public string Message;
public static LogEntry TryCreate(string line)
{
var match = s_regex.Match(line);
return match.Success ? new LogEntry
{
TS = DateTime.ParseExact(match.Groups[1].Value, "yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture),
Machine = match.Groups[2].Value,
Thread = int.Parse(match.Groups[3].Value),
Level = match.Groups[4].Value,
Logger = match.Groups[5].Value,
Message = match.Groups[6].Value,
} : null;
}
public void AppendToMessage(string line)
{
Message += Environment.NewLine + line;
}
}
static void Main()
{
const string SQL = #"
INSERT INTO log ( ts, machine, thread, level, logger, message, journalId)
VALUES (#ts, #machine, #thread, #level, #logger, #message, #journalId)
";
using (var connection = new SqlConnection("server=localhost;database=misc;uid=SantaClaus;pwd=MerryChristmas"))
{
connection.Open();
using (var command = new SqlCommand(SQL, connection))
{
var tsParam = new SqlParameter("#ts", SqlDbType.DateTime);
var machineParam = new SqlParameter("#machine", SqlDbType.NVarChar, 32);
var threadParam = new SqlParameter("#thread", SqlDbType.Int);
var levelParam = new SqlParameter("#level", SqlDbType.NVarChar, 10);
var loggerParam = new SqlParameter("#logger", SqlDbType.NVarChar, 128);
var messageParam = new SqlParameter("#message", SqlDbType.NVarChar, -1);
var journalIdParam = new SqlParameter("#journalId", SqlDbType.Int);
command.Parameters.Add(tsParam);
command.Parameters.Add(machineParam);
command.Parameters.Add(threadParam);
command.Parameters.Add(levelParam);
command.Parameters.Add(loggerParam);
command.Parameters.Add(messageParam);
command.Parameters.Add(journalIdParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
int i = 0;
foreach (var file in Directory.GetFiles(#"c:\tmp\dfbje01"))
{
journalIdParam.Value = OpenJournal(connection, file);
command.Transaction = connection.BeginTransaction();
foreach (var e in GetLogEntries(file))
{
tsParam.Value = e.TS;
machineParam.Value = e.Machine;
threadParam.Value = e.Thread;
levelParam.Value = e.Level;
loggerParam.Value = e.Logger;
messageParam.Value = e.Message;
command.ExecuteNonQuery();
++i;
if (i == 1000)
{
i = 0;
command.Transaction.Commit();
command.Transaction = connection.BeginTransaction();
}
}
command.Transaction.Commit();
CloseJournal(connection, journalIdParam.Value);
}
}
}
}
private static void CloseJournal(SqlConnection connection, object id)
{
const string SQL = "UPDATE journal SET done = 1 WHERE id = #id";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#id", id));
command.ExecuteNonQuery();
}
}
private static object OpenJournal(SqlConnection connection, string filePath)
{
const string SQL = "INSERT INTO journal (filePath) OUTPUT inserted.id VALUES (#filePath)";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#filePath", filePath));
return command.ExecuteScalar();
}
}
private static IEnumerable<LogEntry> GetLogEntries(string filePath)
{
LogEntry prev = null;
foreach (var line in File.ReadLines(filePath))
{
var logEntry = LogEntry.TryCreate(line);
if (logEntry != null)
{
if (prev != null)
{
yield return prev;
}
prev = logEntry;
}
else if (prev != null)
{
prev.AppendToMessage(line);
}
else
{
// Oops
Console.WriteLine(line);
}
}
if (prev != null)
{
yield return prev;
}
}
}
}
Mind trying out the filtering, search, colorizing features of the latest developer snapshot of Chainsaw? It has a good number of features which may avoid the need to use a DB. If you use a VFSLogFilePatternReceiver, it can parse and tail any regular text file, including those created by log4net.
Latest developer snapshot of Chainsaw is available here:
http://people.apache.org/~sdeboy

Async call of WCF using Duplex Communication to get Database change

I am implementing and WCF Async service using WsDualHttpBinding binding for duplex communication to get database changes.
I have implemented the Service but I dont know how to call it from Client application.
Here is the code.
The below code is WCF Service
[ServiceContract()]
public interface ICustomerService
{
[OperationContract(IsOneWay = true)]
void GetAllCustomer();
}
public interface ICustomerServiceCallback
{
[OperationContract(IsOneWay = true)]
void Callback(Customer[] customers);
}
[ServiceContract(Name = "ICustomerService",
CallbackContract = typeof(CustomerServiceLibrary.ICustomerServiceCallback),
SessionMode = SessionMode.Required)]
public interface ICustomerServiceAsync
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetAllCustomer(AsyncCallback callback, object asyncState);
void EndGetAllCustomer(IAsyncResult result);
}
[DataContract]
public class Customer
{
[DataMember]
public string Name
{
get;
set;
}
}
}
public class CustomerService :ICustomerService,IDisposable
{
List<Customer> Customers = null;
ICustomerServiceCallback callback;
Customer customer = null;
string constr = "Data Source=.;Initial Catalog=WPFCache;Persist Security Info=True;User ID=sa;Password=Password$2";
public CustomerService()
{
callback = OperationContext.Current.GetCallbackChannel<ICustomerServiceCallback>();
SqlDependency.Start(constr);
}
public void GetAllCustomer()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "GetHero";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Notification = null;
// Create the associated SqlDependency
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(dep_OnChange);
SqlDataReader dr = cmd.ExecuteReader();
Customers = new List<Customer>();
while (dr.Read())
{
customer = new Customer();
customer.Name = dr.GetString(0);
Customers.Add(customer);
}
}
callback.Callback(Customers.ToArray());
}
}
void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
try
{
if (e.Type == SqlNotificationType.Change)
{
GetAllCustomer();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Dispose()
{
SqlDependency.Stop(constr);
}
}
I have hosted this WCF Async Service as self hosting in a Console Application.
Here the hosting code
class Program
{
static void Main(string[] args)
{
StartService();
}
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
Uri httpbaseAddress = new Uri("http://localhost:8087/CustomerService/");
Uri[] baseAdresses = { httpbaseAddress };
myServiceHost = new ServiceHost(typeof(CustomerServiceLibrary.CustomerService));
myServiceHost.AddServiceEndpoint(typeof(CustomerServiceLibrary.ICustomerService), new WSDualHttpBinding(), httpbaseAddress);
ServiceDescription serviceDesciption = myServiceHost.Description;
foreach (ServiceEndpoint endpoint in serviceDesciption.Endpoints)
{
Console.WriteLine("Endpoint - address: {0}", endpoint.Address);
Console.WriteLine(" - binding name:\t\t{0}", endpoint.Binding.Name);
Console.WriteLine(" - contract name:\t\t{0}", endpoint.Contract.Name);
Console.WriteLine();
}
myServiceHost.Open();
Console.WriteLine("Press enter to stop.");
Console.ReadKey();
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
In client Application have crated a DuplexChannel factory instance
Here is the Code.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
EndpointAddress address = new EndpointAddress(new Uri("http://localhost:8087/CustomerService"));
WSDualHttpBinding wsDualBinding = new WSDualHttpBinding();
DuplexChannelFactory<ICustomerServiceAsync> client = new DuplexChannelFactory<ICustomerServiceAsync>(new InstanceContext(this), wsDualBinding, address);
App.channel = client.CreateChannel();
}
Now My question is How I can call the
BeginGetAllCustomer
EndGetAllCustomer
Method of My service.
Help me.... A big thanks in Advance ...
You need:
InstanceContext instanceContext = new InstanceContext(YOUR_OBJECT_IMPLMENTS_CALLBACK);
and
using (App.channel as IDisposable)
{
App.channel.YOUR_METHOD_HERE();
}
from this example:
endPointAddr = "net.tcp://" + textBox2.Text + ":8000/FIXMarketDataHub";
NetTcpBinding tcpBinding = new NetTcpBinding();
tcpBinding.TransactionFlow = false;
tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
tcpBinding.Security.Mode = SecurityMode.None;
EndpointAddress endpointAddress = new EndpointAddress(endPointAddr);
Append("Attempt to connect to: " + endPointAddr);
InstanceContext instanceContext = new InstanceContext(??);
IMarketDataPub proxy = DuplexChannelFactory<IMarketDataPub>.CreateChannel(instanceContext,tcpBinding, endpointAddress);
using (proxy as IDisposable)
{
proxy.Subscribe();
Append("Subscribing to market data");
}
See also microsoft example

Resources