The following error is occurring when i run my code below. I am running a user registration page with details such as first name, last name, user name, password ect. "ID" is my primary key. Error: "An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 0."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication_Assignment
{
public partial class User_Registration_WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_SubmitUserReg_Click(object sender, EventArgs e)
{
//Response.Write("Your registration is successful");
string sql = "SELECT * from User_Table where User_Name = #username";
using (SqlConnection connection = new SqlConnection("ConnectionString"))
using (SqlCommand command = new SqlCommand(sql, connection))
{
var userParam = new SqlParameter("username", SqlDbType.VarChar);
userParam.Value = TextBox_UserName.Text;
command.Parameters.Add(userParam);
var results = command.ExecuteReader();
}
Because you are not using parameters, you have a surname (lastname) that is almost certainly "O'Sullivan" See that single quote; it is causing the TSQL statement to be improperly formed.
If you concatenate strings you run into problems like this and open yourself up to SQL Injection attacks. Always use parameters.
Here's a simple example:
string sql = "SELECT * from employee where username = #username";
using (SqlConnection connection = new SqlConnection("connection string")
using (SqlCommand command = new SqlCommand(sql, connection))
{
var userParam = new SqlParameter("username", SqlDbType.VarChar);
userParam.Value = txtUsername.Text;
command.Parameters.Add(userParam);
var results = command.ExecuteReader();
}
There are numerous references to SQL Injections attacks on SO. Here's one example:
Why do we always prefer using parameters in SQL statements?
Related
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
static void Main()
{
string conn = #"Data Source=(local)\SQLEXPRESS; Integrated Security=true;";
using (SqlConnection sqlConn = new SqlConnection(conn))
{
sqlConn.Open();
Console.WriteLine("State: {0}", sqlConn.State);
}
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();
System.Data.DataRow[] rows = table.Select();
foreach (System.Data.DataRow row in rows)
{
Console.WriteLine(row["ServerName"]);
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
I have a single SQL Server Express instance running.
When I launch this program, it says "Status: Open" but fails to show the name of the server. Why might that be? I know for sure that there is one server up and running.
I picked (and adapted a little) the second half of the code from the MSDN page "SqlDataSourceEnumerator.Instance Property"
When I use a breakpoint to peek into the contents of rows[], I see that they are empty.
The program does not throw any errors, it just does not show the name of the server.
I'm using sql application roles from a .net application. I have an issue which occurs when the connection is lost. So as an example I have this block of code which opens a connection, sets the app role, does a select from the database and the disposes my connection. If I run this code a 2nd time it fails when trying to set the app role again (the ExecuteNonQuery() line for the sys.sp_setapprole).
The exception is an SqlException: A severe error occurred on the current command. The results, if any, should be discarded.
I've tried using the #fCreateCookie parameter and calling sys.sp_unsetapprole to reset the role but this makes no difference.
Help please?
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("sys.sp_setapprole", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#rolename", "MyRole");
command.Parameters.AddWithValue("#password", "MyPassword");
command.ExecuteNonQuery();
}
try
{
DataSet ds = new DataSet();
using (SqlCommand command = new SqlCommand("dbo.MyProcedure", connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.CommandType = CommandType.StoredProcedure;
adapter.Fill(ds);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm still new to MVC and dapper ORM.
Suppose I use dapper for MVC and and when I try to build solution, it showing message:
'SqlConnection does not contain a definition for'Query' and no extension method 'Query' accepting a first argument of type 'SqlConnection'.
here is the code:
using System.Collections.Generic;
using System.Data.SqlClient;
public string Connectionstring = #"Data Source = KL - PT - 049\sqlexpress;Initial Catalog = Record; Integrated Security = True";
public IEnumerable<Customer> GetCustomers()
{
using (SqlConnection conn = new SqlConnection(Connectionstring))
{
conn.Open();
var customer = conn.**Query**<Customer>("Select * from Customer");
return customer;
}
my question is: does the Query above should be fine if I use that way? since I already use data.sqlClient reference?
Add
using Dapper;
at the top of the file.
Note: in recent versions of Visual Studio you can also just press ctrl+. on the unresolved extension method and it will offer to fix it for you:
This question has been addressed all over the web and I tried a lot of things without success. The SQL EXPRESS service is setup to accept local system account but the problem still exists.
This is my connection string:
<add name="PhoneTemplateChange" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Database=PhoneTemplateChange;Integrated Security=SSPI" />
I created a class to do database operations in the constructor I have
_connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["PhoneTemplateChange"].ConnectionString;
and a method in this class to insert data
public void AddNewChangeOrder(int operation, int targetExt)
{
using (SqlConnection con = new SqlConnection(_connectionString))
{
string sql = "INSERT into [dbo].ChangeOrder (operation, targetExt, dtrequested) VALUES (#operation, #targetExt, #dtrequested)";
using (SqlCommand cmd = new SqlCommand(sql))
{
try
{
cmd.Parameters.AddWithValue("#operation", operation);
cmd.Parameters.AddWithValue("#targetExt", targetExt);
cmd.Parameters.AddWithValue("dtrequested", DateTime.Now);
//con.CreateCommand();
con.Open();
//cmd.InitializeLifetimeService();
int rows = cmd.ExecuteNonQuery();
con.Close();
}
catch (SqlException e)
{
throw new Exception(e.Message);
}
}
}
I have played around with the connection string trying all different suggestions, also the commented code in the method above is what I tried to solve the problem. Still no luck!
I also changed the connection string I get two different exceptions this way
Database=PhoneTemplateChange
The above gives the exception in the title.
And the following gives the Exception "Cannot open Database PhoneTemplatechange.mdf requested by the login. Login failed for user 'mydomain\myusername'"
Database=PhoneTemplateChange.mdf
Any ideas?
You are missing the line of code where you specify that cmd uses con as it's connection. As a result the Command (cmd) has no connection, and con isn't associated with any command at all.
Add this line before executing:
cmd.Connection - con;
Alternatively (and better IMO) change your using statement as follows:
using (SqlCommand cmd = new SqlCommand(sql, con))
The code below serves to change connection string in App.config at runtime, I found it here but this code did not work for me on Visual Studio 2010 and SQL Server 2008, I could not open the connection to the Northwind database.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace MyNameSpace
{
public partial class FrmConnectionTest : Form
{
public FrmConnectionTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(TxtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(TxtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
DataTable dt = new DataTable();
da.Fill(dt);
CmbTestValue.DataSource = dt;
CmbTestValue.DisplayMember = "EmployeeID";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}
}
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
}
Using Visual Studio 2010 and SQL Server2008, I got 2 errors for the next line:
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
Error 1 The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(System.Data.SqlClient.SqlCommand)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
Is there any solution to this issue? Thank you.
The error is telling you that you are passing incorrect parameters to your SqlDataAdapter. I think the proper call would be:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
Edit
It looks like you're creating your connection string from within your program, saving it to your config file, then reading it out of our config file right before you create your SqlDataAdapter. So, when you debug this line:
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
Double check that Db.ConnectionString actually contains a connection string.
The other thing to do is open up your SQL Server Management Studio and confirm you can connect to the Northwind database from there. Including/alternatively, in Visual Studio, open your "Server Explorer" window and confirm you can create a Data Connection to Northwind by clicking Add Connection and then setting the connection property window to your server and dropping down the combobox to see if it populates with your databases:
Take a look at the available constructors of the SqlDataAdapter class.
There is no constructor overload that accepts just an SQL String.
You need to use one of the other overloads.
For example, there is one that needs an SQL String and a SqlConnection object.
To use it, change your code like this:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
EDIT:
As BradRem already mentioned in his comment, try a different connection string.
If his example doesn't work for you, you can find more possible examples at http://connectionstrings.com/sql-server-2008.
Do you really have a database called Northwind on your server?
Does the Windows user on your current machine have permissions on the server to access the database? (that's what Integrated Security=SSPI means - your current Windows user is used to access the database!)