In my Local DB Sql Dependency works fine, but when i migrate to an Azure Database is not work.
I check if service broker is enabled, and it is activated.
This is the error:
Statement 'RECEIVE MSG' is not supported in this version of SQL Server
This is my code:
public class Program
{
static void Main(string[] args)
{
SqlClientPermission permission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
if (SolicitarNotifications())
{
string con = "Server=tcp:xxxxx.database.windows.net,0000;Initial Catalog=TestSQLDependendcy;Persist Security Info=False;User ID=xxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
SqlConnection conn = new SqlConnection(con);
SqlDependency.Start(con);
Console.WriteLine("Empezando a escuchar");
GetAlerts();
Console.WriteLine("Presiona enter para salir");
Console.ReadLine();
Console.WriteLine("Deteniendo la escucha...");
SqlDependency.Stop(con);
}
else {
Console.WriteLine("No tienes permitido solicitar notificaciones");
}
}
public static void GetAlerts()
{
try
{
using (SqlConnection con = new SqlConnection("Server=tcp:xxxxx.database.windows.net,0000;Initial Catalog=TestSQLDependendcy;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
{
SqlCommand cmd = new SqlCommand("Select Correo, Nombre From TestNombre", con);
cmd.CommandType = CommandType.Text;
cmd.Notification = null;
cmd.Dispose();
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(OnDataChange);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
{
while (dr.Read())
{
if (dr.HasRows)
{
using (MailMessage mm = new MailMessage())
{
//Send Mails
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
private static void OnDataChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= new OnChangeEventHandler(OnDataChange);
GetAlerts();
}
}
How to run this service in Azure SQL Database?
Currently, Azure SQL does not support Service Broker.
Find RECEIVE statement supported versions at https://learn.microsoft.com/en-us/sql/t-sql/statements/receive-transact-sql?view=sql-server-2017, which states Azure SQL does not support it.
In addition, this documentation https://learn.microsoft.com/en-us/azure/sql-database/sql-database-features provides a great feature comparison documentation between SQL Server, Azure SQL and Managed Instances. Note that Manage Instance supports Service Broker with some differences. I'd recommend signing up for the preview and trying it out.
Related
I have a Windows Forms application. I want to create a setup file for this application. I used Visual Studio 2012 and SQL Server 12.
I want this setup to work in every new environment.
So, how do I make this connection string dynamic? Can I create a connection string after installation and make it available for every form to access, like in my local machine?
Any kind of source code, video links, explanations or examples will be a great help for me.
I propose to search on the machine for instances of the SQL server, and then in every instance search for the databases. You could setup some logic for example if only one instance is found, and on this instance only database with specific name exists then use this database, but if two or more instances are found, or different database name then preferred is found, show window to user where he can choose the right one.
To find Database instance you could use following method:
private static DataRowCollection SQLDataServers()
{
System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
DataTable dt = instance.GetDataSources();
if (dt.Rows.Count>0)
{
return dt.Rows;
}
throw new Exception("No SQL Instance Found");
}
To find tables in the database you can use following method:
private static List<string> GetDatabases(string conString)
{
List<string> list = new List<string>();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
To generate connection string you can use nuget package or following methods:
public static string GetSqlDataSourceConnectionString(string dataSource)
{
return GetSQLDataSource(dataSource).ToString();
}
private static SqlConnectionStringBuilder GetSQLDataSource(string dataSource)
{
var r = GetDataSource(dataSource).AddIntegratedSecurity();
return r;
}
private static SqlConnectionStringBuilder GetDataSource(string dataSource)
{
SqlConnectionStringBuilder sqlBuilder = new
SqlConnectionStringBuilder();
sqlBuilder.DataSource = dataSource;
return sqlBuilder;
}
private static SqlConnectionStringBuilder AddIntegratedSecurity(this SqlConnectionStringBuilder connectionStringBuilder)
{
connectionStringBuilder.IntegratedSecurity = true;
return connectionStringBuilder;
}
The method which connects all this elements can be as following:
static void Main(string[] args)
{
var servers=SQLDataServers();
foreach (DataRow item in servers)
{
string serverName = string.Format($"{item.ItemArray[0].ToString()}\\{item.ItemArray[1].ToString()}");
var connectionString = GetSqlDataSourceConnectionString(serverName);
var listOfDB=GetDatabases(connectionString);
}
}
I have been dealing with connecting to a database from an ASP.NET page. After I had filled the associated the registration form I have prepared, when I click the complete registration I am encountering an error:
And here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection baglanti = new SqlConnection("server=BerkPC-IV; Initial Catalog=Okul; Integrated Security=true;"))
{
using (SqlCommand komut = new SqlCommand())
{
komut.Parameters.AddWithValue("#name", TextBox1.Text);
komut.Parameters.AddWithValue("#midname", TextBox2.Text);
komut.Parameters.AddWithValue("#surname", TextBox3.Text);
komut.Parameters.AddWithValue("#phone", TextBox4.Text);
komut.Parameters.AddWithValue("#country", TextBox5.Text);
komut.Parameters.AddWithValue("#city", TextBox6.Text);
komut.Parameters.AddWithValue("#adress", TextBox7.Text);
komut.Parameters.AddWithValue("#passwod", TextBox8.Text);
komut.Parameters.AddWithValue("#email", TextBox9.Text);
try
{
baglanti.Open();
komut.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw;
}
}
}
}
This seems like a db connectivity issue. In your connection string you have not specified the db username and password.
new SqlConnection("server=BerkPC-IV; Initial Catalog=Okul; Integrated Security=true;"))
which mean the exception must be thrown on execution of this line baglanti.Open();
I want to run a SQL Query like
SELECT a,b,c,d FROM table1 WHERE userID.table1 = userID.table2
I want the output to go to the a DataGrid.
I am using SQL Server 2012.
This is a Silverlight 5 application using the "Business Application" template.
Here is my code from my C# WinForm App. I am trying to port to Silverlight
public SqlConnection ConnectionStateToSQLServer()
{
//string source = "Data Source=.;Initial Catalog=catalog_skull_primary;Integrated Security=SSPI;";
//databaseConnectionstring = source;
try
{
SqlConnection conn = new SqlConnection(databaseConnectionstring);
conn.Open();
//MessageBox.Show("Connection Test Successful");
connection = conn;
conn.Close();
return conn;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
//MessageBox.Show(e.ToString());
}
return null;
}
I have a database in which a table has name Registration which is used to register the user.
It has only two column one is Username and one is password.
A page named Register.aspx is used for registering the member which have two textbox one is for taking Username(textbox1) and one is for taking password(textbox2) and one button for insert these value in database.
The Main problem is that we cannot write statement like this :
Insert into Registration (Username, password)
values ('TextBox1.text','TextBox2.text')
I am using ADO.net Connection oriented mode, I googled but I didn't find any way to insert row in SQL database in connected mode. Please provide me a idea for inserting this row?
ADO.NET has DataReader which supports Connected mode. All else are disconnected.
DataReader is connected architecture since it keeps conneection open untill all records are fetched
If you want to insert in ADO.NET then you should perform the following steps:
private void btnadd_Click(object sender, EventArgs e)
{
try
{
//create object of Connection Class..................
SqlConnection con = new SqlConnection();
// Set Connection String property of Connection object..................
con.ConnectionString = "Data Source=KUSH-PC;Initial Catalog=test;Integrated Security=True";
// Open Connection..................
con.Open();
//Create object of Command Class................
SqlCommand cmd = new SqlCommand();
//set Connection Property of Command object.............
cmd.Connection = con;
//Set Command type of command object
//1.StoredProcedure
//2.TableDirect
//3.Text (By Default)
cmd.CommandType = CommandType.Text;
//Set Command text Property of command object.........
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
//Assign values as `parameter`. It avoids `SQL Injection`
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
Execute command by calling following method................
1.ExecuteNonQuery()
This is used for insert,delete,update command...........
2.ExecuteScalar()
This returns a single value .........(used only for select command)
3.ExecuteReader()
Return one or more than one record.
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
try
{
using (var connection = new SqlConnection(yourConnectionString))
{
string queryString = "Select id, name, age from Table where name = #name";
using (var command = new SqlCommand(queryString, Connection))
{
command.Parameters.AddWithValue("#name", name);
Connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
item = new Item(long.Parse(dataReader[0].ToString()),
dataReader[1].ToString(),
int.Parse(dataReader[2].ToString()));
}
dataReader.Close();
}
}
}
catch (Exception ex)
{
// if exception will happen in constructor of SqlConnection or Command, the // resource can leak but Dispose method will never be called, couse the object was not created yet.
// Trace and handle here
throw;
}
finally
{
}
But ADO.net is useless for enterprice development. You have to have and abstraction from Data Acess Layer and go to entities, not table records
Use the ORM, Luke!
using System.Data.SqlClient;
string cnstr = "server=.;database=dbname;user=username;password=password;";
SqlConnection con = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand { Connection = con };
cmd.CommandText = "Insert into Registration (Username, password) values ('#user','#pass')";
cmd.Parameters.AddWithValue("user", TextBox1.text);
cmd.Parameters.AddWithValue("pass", TextBox2.text);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
//something;
}
finally
{
if (con != null)
con.Close();
}
I keep on getting the following error every time i try to create a new transaction after i have backed up my database using SMO (Sql Server Management Objects):
New transaction is not allowed because there are other threads running in the session.
I have created a little console app that demonstrates the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;
using System.Data;
namespace TestSMO
{
class Program
{
string username = "radandba";
string password = "belmont";
string servername = "e2idev\\e2isqlexpress";
string databaseName = "e2i";
string backupfilename = "c:\\e2i.bak";
Server server;
static void Main(string[] args)
{
Program prog = new Program();
prog.server = new Server(prog.servername);
prog.server.ConnectionContext.LoginSecure = false;
prog.server.ConnectionContext.Password = prog.password;
prog.server.ConnectionContext.Login = prog.username;
try
{
prog.server.ConnectionContext.Connect();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
return;
}
Console.WriteLine("Connected");
//prog.SelectData();
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = prog.databaseName;
backup.Devices.Clear();
backup.Incremental = false;
backup.Devices.AddDevice(prog.backupfilename, DeviceType.File);
backup.BackupSetName = prog.databaseName + " database backup";
backup.BackupSetDescription = prog.databaseName + " database - Full backup";
backup.Initialize = true;
backup.CopyOnly = true;
backup.LogTruncation = BackupTruncateLogType.NoTruncate;
backup.CompressionOption = BackupCompressionOptions.Default;
backup.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Complete);
backup.Information += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Information);
backup.PercentComplete += new PercentCompleteEventHandler(prog.backup_PercentComplete);
backup.SqlBackupAsync(prog.server);
}
void backup_PercentComplete(object sender, PercentCompleteEventArgs e)
{
Console.WriteLine("Backup progress: " + e.Percent);
}
void backup_Information(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
}
void backup_Complete(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
SelectData();
}
public void SelectData()
{
SqlConnection sqlCon = server.ConnectionContext.SqlConnectionObject;
try
{
if (sqlCon.State != System.Data.ConnectionState.Open)
sqlCon.Open();
SqlTransaction trans = sqlCon.BeginTransaction();
SqlDataAdapter adapter = new SqlDataAdapter("select * from version", sqlCon);
adapter.SelectCommand.Transaction = trans;
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row[0]);
}
trans.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
sqlCon.Close();
}
Console.ReadLine();
}
}
}
You could try to enable MARS on connection (msdn about MARS)
In connection string should be: "MultipleActiveResultSets=true;"
As stated by Anders UP turned out it was the NoLogTruncation was affecting it.