Inserting elements into a database table through using ASP.NET - sql-server-2012

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();

Related

Using SQL Dependency with Azure

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.

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

SqlDependency not firing

I am trying SqlDepenedency for the first time. I am not getting any notifications on Database Update.
I am placing breakpoints inside :
OnChange(object sender, SqlNotificationEventArgs e),
but it never gets hit.
Here is my code :
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Cache Refresh: " + DateTime.Now.ToLongTimeString();
DateTime.Now.ToLongTimeString();
// Create a dependency connection to the database.
SqlDependency.Start(GetConnectionString());
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand command = new SqlCommand(GetSQL(), connection))
{
SqlDependency dependency =
new SqlDependency(command);
// Refresh the cache after the number of minutes
// listed below if a change does not occur.
// This value could be stored in a configuration file.
connection.Open();
dgHomeRequests.DataSource = command.ExecuteReader();
dgHomeRequests.DataBind();
}
}
}
private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
//return "Data Source=(local);Integrated Security=true;" +"Initial Catalog=AdventureWorks;";
return ConfigurationManager.ConnectionStrings["TestData"].ConnectionString;
}
private string GetSQL()
{
return "Select [Address] From [UserAccount1]";
}
void OnChange(object sender, SqlNotificationEventArgs e)
{
// have breakpoint here:
SqlDependency dependency = sender as SqlDependency;
// Notices are only a one shot deal
// so remove the existing one so a new
// one can be added
dependency.OnChange -= OnChange;
// Fire the event
/* if (OnNewMessage != null)
{
OnNewMessage();
}*/
}
I have also placed some code in Global.asax file :
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
SqlDependency.Start(ConfigurationManager.ConnectionStrings["TestData"].ConnectionString);
}
protected void Application_End()
{
// Shut down SignalR Dependencies
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["TestData"].ConnectionString);
}
}
The SQL server is on local machine. I am running the code through Visual Studio(IIS Express).
To enable service broker on database:
ALTER DATABASE SET ENABLE_BROKER
GO
To subscribe query notification, we need to give permission to IIS service account
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO “<serviceAccount>”
I guessed the 2nd point is not needed as it is local. But I tried giving it some permissions. Don't know if they are right as I don't think it is using app pool.And don't need the permission on local env. if I am the user myself and created the schema myself.
One of the questions that I saw was granting :
alter authorization on database::<dbName> to [sa];
I gave that permission too.
I was missing :
dependency.OnChange += new OnChangeEventHandler(OnChange);
The new code would look like :
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(OnChange);
now I can fire
void OnChange(object sender, SqlNotificationEventArgs e)

Sql Notification Supported Isolation Levels for Transactions

I am running multiple inserts using transactions. I am using the SqlDependency class to let the client machine know when the server has been updated.
The problem I am having is that whenever I insert using a transaction, no matter what isolation level I set for the transaction, the SqlNotificationEventArgs returns e.Info as Isolation which indicates that I have the wrong isolation level set for that transactions (I think). When I insert without using a transaction, everything runs smoothly.
My questions is, what are the supported Isolation levels, if any, for transactions when using Sql Notification?
Below is some of the code I am using for the notification:
void DataChanged(object sender, SqlNotificationEventArgs e) {
var i = (ISynchronizeInvoke)_form;
if (i.InvokeRequired) {
var tempDelegate = new OnChangeEventHandler(DataChanged);
object[] args = { sender, e };
i.BeginInvoke(tempDelegate, args);
} else {
var dependency = (SqlDependency)sender;
if (e.Type == SqlNotificationType.Change) {
dependency.OnChange -= DataChanged;
GetData(dependency);
}
}
}
And for the transaction:
public void ExecuteNonQueryData(List<string> commandTexts) {
SqlConnection connection = null;
var command = new SqlCommand();
SqlTransaction transaction = null;
try {
connection = new SqlConnection(GetConnectionString());
connection.Open();
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
foreach (var commandText in commandTexts) {
try {
command.Connection = connection;
command.CommandText = commandText;
command.Transaction = transaction;
command.ExecuteNonQuery();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
transaction.Commit();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
command.Dispose();
if (transaction != null) transaction.Dispose();
if (connection != null) {
connection.Close();
connection.Dispose();
}
}
commandTexts.Clear();
}
Edit: I was committing the transaction in the wrong place.
Apparently Query Notification does not support transactions. Removing the transaction code fixed this problem.
According to Microsoft:
Transact-SQL does not provide a way to subscribe to notifications. The CLR data access classes hosted within SQL Server do not support query notifications.
This quote was found at http://msdn.microsoft.com/en-us/library/ms188669.aspx, which describes how Query Notifications work and their requirements.

Liquibase does not commit my changes

I'm running Liquibase from a Java application to MSSQL with the JTDS driver. When I run the updates I see them displayed but nothing actually get's committed to the Database. Any ideas? The code below runs in a Servlet.
Connection con = null;
try {
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/datasource.properties"));
String driver = props.getProperty("database.driver");
String url = props.getProperty("database.url");
String username = props.getProperty("database.username");
String password = props.getProperty("database.password");
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(con));
Liquibase liquibase = new Liquibase("db.xml", new ClassLoaderResourceAccessor(), database);
response.getWriter().print("<PRE>");
liquibase.update("", response.getWriter());
con.commit();
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.warn(e.getMessage(), e);
}
}
}
response.flushBuffer();
The update() method that takes a writer will not execute changes, but rather output what would be ran.
If you call liquibase.update("") or liquibase.update(null) instead, it will execute the changes.