The current program I am working on is for a Registration page for a shopping cart, I have setup a SQL Server with tables to allow data to be recorded as
UserName,
Email,
Password all are set a Nvarchar(max).
The version of the .NET Framework is 4.5 and I am using VS 2012 and am coding in C#, and the server is an SQL Server instance KENSULLIVAN-PC\KSSQL using integrated Windows Authentication.
So far, I have been able to run the registration page to the point where it will save a cookie of the information but, not send any information to the tables in SQL Server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Account_Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
}
//Submit button for user registration information
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
int TheUserID = 5000;
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC/KSSQL;Database=GroupProject; Integrated Security=True");
//INSERT command for values to be updated or added to the Database
SqlCommand comm = new SqlCommand("INSERT INTO RegUser (UserName, Email, Password) VALUES (#UserName, #Email, #Password)", conn);
comm.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#UserName"].Value = RegisterUser.UserName;
comm.Parameters.Add("#Email", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#Email"].Value = RegisterUser.Email;
comm.Parameters.Add("#Password", System.Data.SqlDbType.NVarChar, 100);
comm.Parameters["#Password"].Value = RegisterUser.Password;
try
{
conn.Open();
comm.ExecuteNonQuery();
Response.Redirect("~/LoggedIn.aspx");
}
catch
{
//ErrorDB.Text = "Error Submitting, Try Again";
}
finally
{
conn.Close();
}
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/LoggedIn.aspx";
}
Response.Redirect(continueUrl);
}
}
What should I be doing differently, what do you notice that is not really recommended?
Thank you,
Kenneth
I see a couple of possible issues.
First, the instance name for SQL databases should be using a backslash. Of course you'll need to escape that backslash, so try this:
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC\\KSSQL;Database=GroupProject; Integrated Security=True");
Second, integrated security can be a little tricky from ASP.NET since often times it's running from a service or system account. You may want to enable MIXED authentication mode in MS-SQL, create a SQL account, and pass in a username and password. I would recommend storing your connection string in the web.config and encrypting it.
Is there a specific error/exception you're receiving? That would be very helpful to us.
First of all #Adam already pointed out, your connection string has issue, for named instance of SQl server, if you are using .Net, it should be backslash
SqlConnection conn = new SqlConnection("Server=KENSULLIVAN-PC\\KSSQL;Database=GroupProject; Integrated Security=True");
OR using #
SqlConnection conn = new SqlConnection(#"Server=KENSULLIVAN-PC\KSSQL;Database=GroupProject; Integrated Security=True");
Second, because you are using Window Authentication, you need to set you ThreadPool which host you web application to run under a windows domain account, which has enough permission to backend database.
If each user using your web site login with windows domain account, and you want to use user's window domain credential to access to backend database, then you need more set up, you need the impersonation, you probably also need constrained delegation.
Related
I am new at this but I have a simple table in my SQL Server with one column name and 2 rows in it. I am trying to show up the names when pressing a button, I need to know how to connect the SQL Server database to the C# code and how to read from a specific table.
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=DESKTOP-REB699D\SQLEXPRESS;Initial Catalog=DBdemo";
cnn = new SqlConnection(connetionString);
cnn.Open();
MessageBox.Show("Connection Open !");
cnn.Close();
}
}
}
But that didn't work, it crashes at the cnn.open(); line of code.
If you are not using any credentials, its windows authentication.
Does adding Integrated Security=True to the connection string help?
Can you login to the DB without credentials on SSMS using Windows authentication option? If so, you don't need user credentials for connecting to DB. If you require a Username and password there,
you either need to include that in the connection string or
you need to enable SQL Server and Windows Authentication option under security tab to access the database without credentials
Recently we have had an issue with our ERP retrieving some information from our database tables. While this is being fixed I have come up with some work arounds to temporarily, however, they only work because my user has access to the SQL database and can run queries on the database. I would like to distribute an executable program throughout the company (we are relatively small, so I am not worried about bottle-necking my computer) that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. This way we don't need to make any changes to users SQL permissions.
How could I possibly do this?
Edit - Additional Info
User A - has permission to query the database on our servers from
their workstation
User B - does not have permission to query the db
User B needs to gather information from a specific db query, yet they don't have access to the db. All that User B needs, is to be returned a string with information from that query.
So not necessarily looking for the remote execution of a program per se, because then how would they get that return value?
I would do it with an application that does something like this.
using MySql.Data.MySqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection conn = null;
try
{
conn = new MySqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
MySqlCommand selCmd = new MySqlCommand("SELECT ...", conn);
MySqlDataAdapter da = new MySqlDataAdapter(selCmd);
....
This uses MySql, but the exact equivalent can be done with any DB provider. The part of the connection string that says Integrated Security=False tells the system not to use the current user's window credentials but rather what is being provided in the connection string.
The same thing but using Sql Server, I think, would be like this (it's been a while since I use sql server...
using System.Data.SqlClient;
namespace WinformFiddle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection();
conn.ConnectionString = "server=myserver.mydomain.edu;user id=MyUserWithAccessUsername;password=MyUserWithAccessPassword;persistsecurityinfo=True;database=roomscheduling;Integrated Security=False";
conn.Open();
SqlCommand selCmd = new SqlCommand("SELECT ...", conn);
SqlDataAdapter da = new SqlDataAdapter(selCmd);
....
I assume based on the quote below - you are creating a program that you will send to user B to use to run the query and return a string.
"that would allow a different user on another computer to run a query through my computer and retrieve the information to then be output on their computer. "
If this is the case - User B doesnt need any data base permissions. You will put your [user A]'s username and password in the connection string of the program you create. So when User B runs this program you gave him, it will use User As permissions to run and return data.
like this:
<add name="myconnection" connectionString="data source=yoursqlserver;initial catalog=yourdataabase;persist security info=True;user id=UserA;password=userAspassword" providerName="System.Data.SqlClient" />
How can I connect to a remote or local database using simple SqlConnection object? I learned to do it this way, but my connection is failing. I read about creation of connection string from this page:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
My code:
using System.Data.SqlClient;
namespace SyncApp_BuiltInProviders
{
public partial class Form1 : Form
{
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection source_conn = new SqlConnection();
source_conn.ConnectionString ="Server=localhost;Database = ptls; UID = root;Password = ODYSSEY99GRANITE;";
source_conn.Open();
}
}
}
As from your comment in another answer it is clear that you are using the wrong classes. The SqlConnection is a class specialized in connecting to Sql Server/Sql Server Express/LocalDb. It cannot work against a MySql
If you use MySql then you need to download and install the MySql Connector for NET from here.
After that, you need to reference the MySql.Data.dll and add a
using MySql.Data.MySqlClient;
to all the source files that interact with the database.
Finally, all the classes used to work with the database, should be the ones provided by the MySql NET Connector.
They are prefixed with MySql..... (MySqlConnection, MySqlCommand, MySqlDataReader etc.)
If you are used SQL Database, it seems to me that, you have not set username and password. If you have not set username and password then try this.
private void btnSynchronize_Click(object sender, EventArgs e)
{
SqlConnection db_connect= new SqlConnection();
db_connect.ConnectionString ="Server=[your local pc connection name, it is not local host.];Database=[database_name];Trusted_Connection=true";
db_connect.Open();
}
If you use MySql then
private void btnSynchronize_Click(object sender, EventArgs e)
{
//Create a MySQL connection string.
string connectionString="Server=localhost;Database[database_name];Uid=root;Password =your password; ";
MySqlConnection db_connect= new MySqlConnection(connectionString);
db_connect.Open();
}
Finally use following name space
using MySql.Data.MySqlClient;
I have a local project where I am trying to input data from an ASP:textbox to a database.
On building I get the following...
"Failed to generate a user instance of SQL Server. Only an integrated connection can generate a user instance. The connection will be closed."
I'm a little puzzled here, I have checked the database and it is active with the credentials i am trying to connect with.
Here is the code behind
C#
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection sqlcon = new SqlConnection(#"user id=*myuserid*;"+"password=*mypassword*;"+"Data Source=mssql.dev-works.co.uk;User Instance=True;"+"Database=devworks_osqar"+"Trusted_Connection=true;");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Create_Click(object sender, EventArgs e)
{
DataBinder ds = new DataBinder();
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
}
}
}
Any help would be much appreciated.
Edited code behind (read commment below)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace OSQARv0._1
{
public partial class new_questionnaire : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string myConnectionString;
private SqlConnection myConn;
public new_questionnaire()
{
myConn = new SqlConnection();
myConnectionString += "Data Source=mssql.database.co.uk; Initial Catalog=devworks_osqar;User ID=myusername;Password=mypassword";
}
protected void Create_Click(object sender, EventArgs e)
{
//DataBinder ds = new DataBinder();
SqlCommand sqlcmd = new SqlCommand("INSERT INTO QUESTIONNAIRES (QuestionnaireName) VALUES ('"+qnrName.Text+"')");
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("#Name", qnrName.Text);
insert(sqlcmd);
}
private void insert(SqlCommand myCommand)
{
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
}
}
}
Fix error "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."
Content from link pasted and altered below in case reference site is removed in the future:
Step 1.
Enabling User Instances on your SQL Server installation
First we are gonna make sure we have enabled User Instances for SQL Server installation.
Go to Query Window in SQL Server Management Studio and type this:
exec sp_configure 'user instances enabled', 1.
Go
Reconfigure
Run this query and then restart the SQL Server.
Step 2.
Deleting old files
Now we need to delete any old User Instances.
Go to your C drive and find and completely DELETE this path (and all files inside):
C:\Documents and Settings\ YOUR_USERNAME \Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
(Dont forget to replace the bold text in the path with your current username (if you are not sure just go to C:\Documents and Settings\ path to figure it out).
After deleting this dir you can go to Visual Studio, create ASP.NET WebSite and click on your App_Data folder and choose Add New Item and then choose SQL Server Database and it should work!!!
I'm currently making a custom login in ASP.NET. I've modified the code of the Login Control to use my database instead of the Aspnet table. Here's a sample of my code;
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
// Custom login control
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
try
{
string uname = Login1.UserName.Trim();
string password = Login1.Password.Trim();
bool flag = AuthenticateUser(uname, password);
if (flag == true)
{
e.Authenticated = true;
Login1.DestinationPageUrl = "Default.aspx";
}
else
e.Authenticated = false;
}
catch (Exception)
{
e.Authenticated = false;
}
}
private bool AuthenticateUser(string uname, string password)
{
bool bflag = false;
string connString = "Server=DEVSERVER;User ID=sa;Password=whatpassword;Database=CommonUser";
string connstring2 = "Server=DEVSERVER;User ID=sa;Password=whatpassword;Database=Admins";
string strSQL = "Select * from dbo.Users where Username ='" + uname + "' and Password ='" + password + "'";
DataSet userDS = new DataSet();
SqlConnection m_conn;
SqlDataAdapter m_dataAdapter;
SqlCommand m_Command;
try
{
m_conn = new SqlConnection(connString);
m_conn.Open();
m_dataAdapter = new SqlDataAdapter(strSQL, m_conn);
m_dataAdapter.Fill(userDS);
m_conn.Close();
}
catch (Exception)
{
userDS = null;
}
if (userDS != null)
{
if (userDS.Tables[0].Rows.Count > 0)
bflag = true;
}
return bflag;
}
}
I have another database for the Admin users. So my question is how can I make it check the database for the admin users. Also how can I restrict common users from certain pages like ~Admin/AdminPages.aspx? I'm currently trying to figure This.
Any help would be much appreciated ;)
Thanks in advance
Ok, so I am going to say this, but know that I mean it in the nicest possible way...
You are doing it wrong!
I'm not arguing against the use of a custom database although Asp.Net already has this built in. I'm not even arguing against hand coding this in a method when you could be using the very nice pluggable provider model that Asp.Net has built in. What I am arguing against is how wide open this code is to a Sql Injection attack.
Consider for a second what would happen if I typed in x'; DROP TABLE Users; -- as the username? BAD THINGS MAN!!!!
Ok, so seriously follow the links I put in there and please please please at the very least use parameterized queries!
There are quite a few things wrong with the code you posted.
string strSQL = "Select * from dbo.Users where Username ='" + uname + "' and Password ='" + password + "'";
Never EVER EVER do string concatenation to build a query. This leaves your application open to SQL Injection. Use a parametrized query instead.
Why do you have a separate database for Admins and Common Users? Wouldn't you store all the logins in a single table in a single database. Then either use a single field "IsAdmin" or use a separate Roles table and UsersInRoles table to determine which users are Admin or not.
What is your reason for not using the builtin Membership Provider? You configure the builtin provider to use any database, not just the AppData\aspnet.mdf.
You typically restrict different pages to different users using Roles, this can be set in the web.config file inside the authorization element.
If you REALLY want to create a custom simple authentication system, use something like http://csharpdotnetfreak.blogspot.com/2009/02/formsauthentication-ticket-roles-aspnet.html
to manually assign the user roles to the user identity.
To add my voice to the mix. Those who do not learn from history are doomed to repeat it. The ASP.NET membership system is the result of years of people trying to implement their own user authentication systems. Microsoft learned from that. So should you.
Use the membership provider model. If you don't want to use the default provider, then implement your own custom one. But honestly, it's very easy to use the built-in provider and adapt it to whatever you want.
I really think you shouldn't hardcode database connection parameters at all. Is a bad practice because if the DB changes, you'll have to recompile. So, what you must do is implement a custom membership and role provider. See this article. Basically you need to create a custom class that inherits from System.Web.Security.RoleProvider and System.Web.Security.MembershipProvider. Membership manages users and roles, well.. user permissions.
After it is all set, you can check user permissions via Page.User property on your aspx page code-behind file.