connection to SQL SERVER in ASP.Net - asp.net

I'm creating a register page . When I write connection string to connect to SQL Server 2014 , this error is shown: Error Pic
protected void btnsignup_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=(local);DataBase=MyDataBase;integrated security=True");
SqlCommand cmd = new SqlCommand("insert into Users (Username,UPassword,Uname,UEmail) values ('"+ tbUname.Text + ","+ tbPass.Text + ","+tbname.Text +","+ tbemail.Text +"')");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}

Like the error message shows you cannot login as that user (IIS/defaultapppool) on SQL server.
Ususally this happens if:
User does not exist
User does not have the permissions to access the database
Go to your SQL server management studio and make or edit your user. right click the security folder to make a new user, and make sure he is databaseReader, -Editor and/or databaseAdmin
You can also specify another user in your connectionstring by adding: User ID=name;Password=password

Related

How to check if a SqlConnection is possible, and do something consequently?

I have an ASP.NET solution that launch a website, with a login page.
Also, I have created many Sql server accounts that give access to the same databases.
I want that, when an user put his username & password in my login page, my app try to connect to Sql server using this username & password.
So I don't have a table with the usernames & passwords of the users in my database, but I have many SQL server accounts with theses usernames & passwords.
I hope I'm clear enough.
So, I want to know, when my app try to connect to Sql server, if the username & password that the user enters doesn't refer to any account, if we can display an error message.
So the user know that he enters his credentials incorrectly, and he can try to enter theml again.
Is it possible ?
Thanks for your help and have a nice day.
So I would think you can build the connectionstring up and then just add the username and password and then attempt to connect. You can encase it in a try catch block and if it fails you can display a message on the form or you can work out what the error from the try catch block is saying and display your own message.
Something like this
<add key="ConnectionString" value="server=serverName;database=database;User ID=username;password=password"/>
could be
SqlConnection con = new SqlConnection();
try
{
string connectionString = #"<add key="""ConnectionString""
value="""server=serverName;database=database;User ID="" + txtUsername.Text + """;password="" + txtPassword.Text +"""/>";
con = new SqlConnection(connectionString);
con.Open();
}
catch (exception ex)
{
read ex.message
}
Then you can use the following to see if connection was sucessful
if (con.State = ConnectionState.Open)
{
your code here...
}

ASP.NET Login control not redirecting

My login control isn't working as intended anymore. It pulls the username and password from a database and then redirects the user to Home.aspx. Redirecting sadly doesn't happen. It does add this to the end of the url, but nothing happens
ReturnUrl=%2fHome.aspx
This is the shortend ASP code
<asp:Login ID="Login1" runat="server" OnAuthenticate= "ValidateUser"
DestinationPageUrl="~/Home.aspx"> </asp:Login>
Plus .cs code
protected void ValidateUser(object sender, AuthenticateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_CONNE"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username =#Username and Password=#Password", con);
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Wachtwoord", Login1.Password);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Session["Uname"] = Login1.UserName;
if (dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx");
}
I have been working on functionality in which not logged in users cant acces certain pages, but I'm not sure if that's the thing that's screwing it up..
After fiddling a little I noticed deny users seems to have an effect on it, but don't know any other way to be redirecting non-login attempts.
Any help would be greatly appreciated!
Looking at your code, in sql command your query have password parameter defined as #Password while adding it to the cmd parameters collection you have #Wachtwoord instead of the #Password.
Here is the updated code:
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username =#Username and Password=#Password", con);
cmd.Parameters.AddWithValue("#Username", Login1.UserName);
cmd.Parameters.AddWithValue("#Password", Login1.Password);
Also, instead of always redirecting to Home.aspx you can get the return url using FormsAuthentication.GetRedirectUrl. So if you try to access some page Protected.aspx without logging in the user will be redirected to Login.aspx?ReturnUrl=protected.aspx and after login user will be redirected to Protected.aspx page.
if (dt.Rows.Count > 0)
{
Response.Redirect(FormsAuthentication.GetRedirectUrl( Login1.UserName, false));
}

Proper Protocol for Connecting to Azure SQL DB for ASP.NET Web Forms Site

New to ASP.NET trying to connect to an Azure SQL DB. I don't know exactly what to include in the connection string. I've viewed many posts from this site but a lot of the answers have different content in the connString.
The following is my Form_Load event handler code:
protected void Page_Load(object sender, EventArgs e)
{
//declare connection sting for Azure SQl DB
string strSQLconnection = "Data Source=someValue.database.windows.net;Initial Catalog=dbName;Integrated Security=True";
//create SqlConnection object and pass strSQLconnect variable from above as parameter
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
//create SqlCommand object and select table EMPLOYEES from Azure DB for grid view (to test) and pass sqlConnection from above as parameter
SqlCommand sqlCommand = new SqlCommand("select * from Employees", sqlConnection);
//open the SQL connection
sqlConnection.Open();
//create SqlDataReader object to be able to read from Azure DB
SqlDataReader reader = sqlCommand.ExecuteReader();
gvAzureSql.DataSource = reader;
gvAzureSql.DataBind();
}
Note: I added the gridView just for testing purposes to see if data has been binded; wont be on implemented form.
Also, Im using the address on the top left of the Azure db site; is this correct (########.database.window.net)
I've seen solutions advising to add connection string tag in web.config. Do I also have to do this. If so, may you provide the proper protocol to set this up for Azure SQL DB. I've searched for a long time and can't find a definitive question or process of exactly what to enter in the connString.
Thanks

SqlConnection localhost failed username

This is my first time trying to use a database in ASP.Net, and I have a problem here:
My database is on my computer (localhost), and it throws an exception on me when I click the "submit" button :
SQLException was unhandled by user code. Login failed for user ".
protected void Register_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server = localhost ;uid=; Password= database = Movies;");
connection.Open();
//FirstName***********
string firstName = UsernameTextBox.Text;
string sqlquery = ("INSERT INTO [Movie] (FirstName) VALUES (' " +FirstNameTextBox.Text + " ' ");
SqlCommand command = new SqlCommand(sqlquery , connection);
command.Parameters.AddWithValue("FirstName", firstName);
Since the server is on my computer, I dont have any username, right?!
You do need a username and password, or else you need to use integrated security, which means that your windows credentials are used.
You can add integrated security to your connection as follows:
SqlConnection connection = new SqlConnection("server = localhost ;integrated security=SSPI; database = Movies;");
A good resource for connection strings is http://www.connectionstrings.com
SQL server always requires a username, whether it's on your machine or a remote machine.
I'd suggest looking www.asp.net or try Google to find out how you configure your patricular version of SQL Server
Check this site for connectionstrings if you have problem with formating the connectionstring

SqlCacheDependency not working

I would like to add SqlCacheDependency to my app.
So I desided to create littel tesp project and confronted with difficulties.
I use MSSQL 2008. I create new db with table Lines and added several rows.
I executed:
ALTER DATABASE ForTest SET ENABLE_BROKER
in managmeng studio.
Aspx page:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Cache["Lines"] == null)
{
string connectionString =
WebConfigurationManager.ConnectionStrings["ForTest"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string query = "SELECT dbo.Lines.Id, dbo.Lines.Value FROM dbo.Lines";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Lines");
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);
Cache.Insert("Lines", ds, empDependency);
}
}
}
protected void btnResult_OnClick(object sender, EventArgs e)
{
var result = Cache["Lines"];
}
}
I run this page and add lines to Cache then I add row in managment studio and when I click on button I expect
that the cache will be changed but cache remains old.
I can't find what I do wrong :( Could you give me some hint how I can solve this problem?
Thanks
Update:
I forger to say that in global.aspx I run:
SqlDependency.Start(
WebConfigurationManager.ConnectionStrings["ForTest"].ConnectionString
);
I had a similar issue. This article: Troubleshooting SqlCacheDependency in SQL Server 2008 and SQL Server 2005 helped me a lot then.
In a few words: the databse was restored from a backup, and the original Windows user that created the database was no longer available. So I changed the database ownership to a valid login, something similar to:
ALTER AUTHORIZATION ON DATABASE::[my_perfect_database_name] TO [sa];
and it works like a charm now.
How did I find the source of the issue? I run the query SELECT * FROM sys.transmission_queue and found the next data in the transmission_status column:
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.
This message gave me a key to solving the problem.
There is a mistake in the code;
Definition of sqldependency should be placed before you execute the command,
otherwise it will not subscribe to your sqlcommand, then it won't get notified when your resultset of your command changes.
SqlCacheDependency empDependency = new SqlCacheDependency(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Lines");
I also thought I had an issue with the SqlCacheDependency not being cleared after a change to the table.
Turns out it was because of how I was testing. I was simply editing the rows in the SQL table thru management studio and expecting it to notify and clear the cache. That's not the case! If you are editing the table, you must also re-execute the select sql to kick off the clearing of the cache.

Resources