How to connect a database to website using LINQ and dbml file - c#

I am new to SQL server and trying to make a very simple website which will record usernames and passwords from clients into a database. I have created a database project with a table of users: user name and password. I built a website with a page containing user name text field, password text field and a login button. All I want is to record the usernames and passwords the users are entering (as simple as that). I want to do it via sql connection using LINQ-to-SQL. I know that I have to create SQLConnection class, create a dbml file and attach my database to it. I am having trouble creating a dbml file of my database and attaching my database to it in Visual Studio 2013. Can anyone please give direction to do so?
So far I have this class for the login page:
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = "data source=.; database = AuroraDB; integrated security=SSPI";
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TODO"].ConnectionString);
try
{
string insertQuery = "insert into Users (Username, Password,) values(#uname , #password)";
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("#uname", UserNameTextBox.Text);
command.Parameters.AddWithValue("#password", PasswordTextBox.Text);
connection.Open();
command.ExecuteNonQuery();
Response.Write("Loggin was successful!");
}
catch(Exception exception)
{
Response.Write("Error occurred: " + exception.Message);
}
finally
{
connection.Close();
}
}
}

Related

Connection String Not Working- Not Allowing Connection to Database made in VS (C# Visual Studio)

I am currently working on building an attendance tracker that will take the user's input data and add it to a database table. I'm running into an issue where my connection string will not connect to the database? I've copied it directly as is, and even tried a few different tutorials with alternative ways with no success. This is for an assignment however, our SQL portion was quite small and I'm not sure where to go from here. Please let me know if something in my code needs revisited.
When I run the code I get the "unable to connect" exception I created below. I need it to run and add the user input to the table.
I have also noticed that my database connection often disconnects unless I refresh, is this common?
namespace AttendanceTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void signInButton_Click(object sender, EventArgs e)
{
string connectionString = null;
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\soupy\Desktop\AttendanceTracker\AttendanceTrackerDatabase.mdf; Integrated Security = SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#Student_Name", nameTextBox.Text);
cmd.Parameters.AddWithValue("#Student_ID", studentIDTextBox.Text);
cmd.Parameters.AddWithValue("#Class", classDropDown.Text);
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Your sign in has been recorded successfully!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unable to open attendance tracker for updating.");
}
}
When using Parameter objects, you should ensure that the variable names are consistent.
Please modify your code as follows
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#studentName", nameTextBox.Text); // Modified to "studentName"
cmd.Parameters.AddWithValue("#studentID", studentIDTextBox.Text); // Modified to "studentID"
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
cmd.Parameters.AddWithValue("#class", classDropDown.Text); // Modified to "class"

connectionString, i need to use password, but i'm using windows connection

I have created a database with visual studio, i'm using windows authentication to connect to it.
I've tried many things but it's not working
namespace Stock
{
public partial class Fm_principal : Form
{
public SqlConnection connexion_BDD()
{
//Connection base de donnée
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Trusted_Connection=false";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
return connection;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return connection;
}
}
public Fm_principal()
{
InitializeComponent();
}
private void cb_test_Click(object sender, EventArgs e)
{
connexion_BDD();
string request = "SELECT ref_pdt FROM produits";
SqlCommand command = new SqlCommand(request, connexion_BDD());
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
cb_test.Items.Add(dataReader["ref_pdt"]);
}
}
}
}
I have an error on dataReader because the connection is currently closed
I literally just banged this out, but you will want something like this: (Hint: Take a look at something like Dapper as you may like that better)
public partial class Fm_principal : Form
{
public SqlConnection connexion_BDD()
{
//Connection base de donnée
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;Trusted_Connection=true";
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
return connection;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return connection;
}
}
public Fm_principal()
{
InitializeComponent();
}
private void cb_test_Click(object sender, EventArgs e)
{
using (var connection = connection_BDD())
{
string request = "SELECT ref_pdt FROM produits";
using (var command = new SqlCommand(request, connection))
{
using (var dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
cb_test.Items.Add(dataReader["ref_pdt"]);
}
}
}
}
}
}
Edit: Just in case I am misreading your question to mean that you really want to be connecting using a username and password, then make the connection string this:
string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Database;User Id=YOURUSERNAME;Password=YOURPASSWORD;Trusted_Connection=false";
Edit: To setup SQL credentials (I do not really recommend this as I think integrated security is better as it avoids username/password credentials leaking into source control):
Make sure SQL Server Authentication is enabled (SSMS -> Server
(Right-Click) -> Properties -> Security (Make sure the second radio
button is selected "SQL Server and Windows Authentication Mode"
You will need a server login and mapped DB user. Under the server
(in SSMS), expand Security -> Logins. Add a login (Right-click login
choose Add Login).
Enter the login name you want (this is the
User Id in the connection string) and select SQL Server
Authentication, then pick a (hopefully good) password. If this is a
local box and you don't care turn off the password policy
checkboxes.
In the dialog under Database Roles leave public or
make it more privileged if you want it to manage DBs. If this is a
local devbox making the account sysadmin can be OK.
In the dialog under User Mapping, select your DB and select appropriate
roles. If the user just needs to access (read/write) data, pick
db_datareader/db_datawriter. Often on a dev box just picking
db_owner is best (if you are managing schema, etc.)

how to connect sql database server to usercontrol in windowsform by using c#?

I tried to connect the database to the user control that has in my desktop application. the catch block is running. can anyone see any error in here?
can someone help to find the correct code to connect SQL server management studio 2014 to windows form Application?
I have tried the code as we use to windows form. but it isn't working .is there any different code that uses to user control database connection?
SqlCommand cmd;
SqlConnection con;
private void btnsave_Click(object sender, EventArgs e) {
try {
con = new SqlConnection(# "Data Source=LAPTOP-EN6B5ABV;Initial Catalog=nature;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT INTO crop" + " (cropid, cropname, scnname, noofplant, culdate, ferttimeperiod, harvetimeperiod, addeddate,lifetime,lifetimeperiod) VALUES (#cropid, #cropname, #scnname, #noofplant, #culdate, #ferttimeperiod, #harvetimeperiod, #addeddate,#lifetime,#lifetimeperiod)", con);
cmd.Parameters.AddWithValue("#cropid", txtcropid.Text);
cmd.Parameters.AddWithValue("#cropname", txtcropname.Text);
cmd.Parameters.AddWithValue("#scnname", txtscnname.Text);
cmd.Parameters.AddWithValue("#noofplant", textBox1.Text);
cmd.Parameters.AddWithValue("#culdate", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#ferttimeperiod", comfert.SelectedItem);
cmd.Parameters.AddWithValue("#harvetimeperiod", comboBox1.SelectedItem);
cmd.Parameters.AddWithValue("#lifetime", textBox2.Text);
cmd.Parameters.AddWithValue("#lifetimeperiod", combolifetime.SelectedItem);
cmd.Parameters.AddWithValue("#addeddate", addeddate.Text);
cmd.ExecuteNonQuery();
con.Close();
} catch (Exception) {
MessageBox.Show("something went wrong in database server");
}
I expect the insertion of the data.
Here is my code that I got the correct output. There was an error related to the datetimepicker value. When Get the selected value of datetimepicker it was given an error.
I used this statement to insert date to the database.
cmd.Parameters.AddWithValue("#culdate", Convert.ToDateTime(dateTimePicker1.Value));
string date =DateTime.Now.ToShortDateString();
cmd.Parameters.AddWithValue("#cropid", txtcropid.Text);
cmd.Parameters.AddWithValue("#cropname", txtcropname.Text);
cmd.Parameters.AddWithValue("#scnname", txtscnname.Text);
cmd.Parameters.AddWithValue("#noofplant", txtnoofplant.Text);
cmd.Parameters.AddWithValue("#culdate", Convert.ToDateTime(dateTimePicker1.Value));
cmd.Parameters.AddWithValue("#ferttimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("#fert", comfert.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#harvtimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("#harv", comboBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#addeddate", date);
cmd.Parameters.AddWithValue("#lifetimeperiod", txtlifetime.Text);
cmd.Parameters.AddWithValue("#life", combolifetime.SelectedItem.ToString());
cmd.ExecuteNonQuery();
con.Close();
string msg = "Crop Details are successfully saved...";
string title = "Saved";
System.Media.SystemSounds.Asterisk.Play();
MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.None);

How to insert data from ASP.Net to MS SQL Server?

This question has been asked for several times here. I read posted questions but I still have problem. I'm trying to insert values from ASP.Net form to SQL Server. I created a sample website to work on inserting data into Sql table. SQL Database's name is "TestDatabaseDB" which has one table called "Person". Person table has 4 columns. They are ID, FirstName, LastName, NationalID. The type of ID is "int". I set "Is Identity:Yes". So SQL will assign an ID to each inserted record. It just doesn't work. When I click the button nothing happens. It must insert data into database table or clears the textboxes at least but it doesn't.
I tried
SqlConnection conn= new SqlConnection(#"Data source=.\SQLEXPRESS; AttachDBFilename=""|DataDirectory|\TestWebSiteDB.mdf""; integrated user=true; User Instance=true")
It didn't work. So I changed that into:
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
Didn't make any difference. Here is my code:
using System;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
SqlCommand insert = new SqlCommand("insert into Person(FirstName, LastName, NationalID) values(#Name, #Surname, #ID)" ,conn);
insert.Parameters.AddWithValue("#Name", txtboxName.Text);
insert.Parameters.AddWithValue("#Surname", txtboxFamilyName.Text);
insert.Parameters.AddWithValue("#ID", txtboxNationalCode.Text);
try
{
conn.Open();
insert.ExecuteNonQuery();
}
catch
{
LMsg.Text="Error when saving on database";
conn.Close();
}
txtboxName.Text="";
txtboxFamilyName.Text = "";
txtboxNationalCode.Text = "";
}
}
Any help would be appreciated.
Try this:
protected void Register_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DB_Users.mdf;Integrated Security=True");
SqlCommand insert = new SqlCommand("insert into tbl_users(name, username, password,email) values(#name, #username, #password,#email)", conn);
insert.Parameters.AddWithValue("#name", txtname.Text);
insert.Parameters.AddWithValue("#username", txtusername.Text);
insert.Parameters.AddWithValue("#password", txtpassword.Text);
insert.Parameters.AddWithValue("#email", txtemail.Text);
try
{
conn.Open();
insert.ExecuteNonQuery();
lbl_msg.Text = "Register done !";
//lbl_msg.Text = "ثبت نام با موفقیت انجام شد";
}
catch (Exception ex)
{
lbl_msg.Text = "Error: "+ex.Message;
//lbl_msg.Text = "خطا در ارتباط با پایگاه داده";
conn.Close();
}
}
It works for me.
You need to track what error you are getting as follows. Because it is not possible to help you without the actual error.
catch(Exception ex)
{
LMsg.Text=ex.Message;
}
Also you need to use finally in your code for closing connection rather than closing it into the catch block.
finaly
{
conn.Close();
}
check your connection string. in conn.open() you get exception ?
To create a data connection to a SQL Server database
In Server Explorer/Database Explorer click Connect to Database.
In the Choose Data Source dialog box, select Microsoft SQL Server, and then click OK.
If the Add Connection dialog box opens, and the Data source is not Microsoft SQL Server, click Change to open the Choose/Change Data Source dialog box
. For more information, see Choose/Change Data Source Dialog Box.
Select a server name from the drop-down list, or type the name of the server where the database you want to access is located.
Based on the requirements of your database or application, select either Windows Authentication or use a specific user name and password to log on to the SQL Server (SQL Server Authentication).
For more information, see Add/Modify Connection (Microsoft SQL Server).
Select the database you want to connect to from the drop-down list.
Click OK.
then copy generated connection string to your program.
when you install sql server the server name and the setting you choose for installing .affect your connection string.
for more inforamtion on installing sql server see the
installing sql server express edition
and also check this for connecting asp.net application to sql server
Asp.net connection to SQL Server
Actually the list view has a default method call onsorting. It will automatically sort the list view. onsorting will call the function as below.The function no need put any statement.
protected void Sorting(object sender,ListViewSortEventArgs e)
{
}
For the link button in list view u just simply put the tag like that:
<asp:ListView ID="DisplayContent" runat="server" onSorting="Sorting">
<asp:LinkButton ID="Name" runat="server" CommandName="Sorting" CommandArgument="Name" Text="Name" />
Try following steps:
Step1: Instead of putting you query in your C# file, declare a stored procedure for it like bellow:
CREATE PROCEDURE [dbo].[ADD_PERSON_SP]
/*Type of this variables should be their column types*/
#firstName varchar(MAX),
#lastName varchar(MAX),
#nationalID varchar(MAX)
AS
BEGIN
INSERT INTO [dbo].[Person] (FirstName, LastName, NationalID)
VALUES (#firstName,#lastName,#nationalID)
END
Step2: Using Stored Procedure where you need:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand("ADD_PERSON_SP", con);
com.Parameters.AddWithValue("#firstName", txtboxName.Text);
com.Parameters.AddWithValue("#lastName", txtboxFamilyName.Text);
com.Parameters.AddWithValue("#nationalID", txtboxNationalCode.Text);
com.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
Keep in mind to:
Do not put db related stuffs in your C# files
Try to choose better names for your variables(specially for controls)
This may help you with connectionString
I hope that help
protected void btnRegister_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=. ; Database=TestWebSiteDB; Integrated Security=true");
SqlDataAdapter dap = new SqlDataAdapter("insert into Person(FirstName, LastName, NationalID) values(#Name, #Surname, #ID)", con);
dap.InsertCommand(txtboxName.Text, txtboxFamilyName.Text,txtboxNationalCode.Text);
txtboxName.Text="";
txtboxFamilyName.Text = "";
txtboxNationalCode.Text = "";
}

Insert into Access Database on button click (No errors but not working)

I'm trying to insert data a user inputs from a web form into an Access Database. I made the Access Database with the following fields (FName, LName, State, Address, Zip, Telephone) and put it in a folder called App_Data\Registrationinfo.mbd within my code files.
When a user comes to the website and goes to register for a conference coming this summer they are given the mentioned fields in textboxes, once they click continue there's a cross page posting with labels which verifies with the user that the information is correct. Then upon clicking the "Submit" button on the web form, the information they entered will be put into the Access Database. Any help would be appreciated.
I'm getting any errors at all and the proper page redirect is working when they click submit but the information is not being put into the database.
Note: This is being written in C# with a masterpage.
The table in Access is called UserInfo with only the fields FName and LName just to keep it simple.
protected void submitButton_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=U:\App_Data\Registrationinfo.mbd";
string cmdstr = "insert into UserInfo(FName, LName)values(?, ?)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("?", labelFirstName.Text);
com.Parameters.AddWithValue("?", labelLastName.Text);
com.ExecuteNonQuery();
con.Close();
}
I think you want
protected void submitButton_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=U:\App_Data\Registrationinfo.mbd";
string cmdstr = "insert into UserInfo(FName, LName) values(#First, #Last)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("#First", labelFirstName.Text);
com.Parameters.AddWithValue("#Last", labelLastName.Text);
com.ExecuteNonQuery();
con.Close();
}
Name your parameters on this line:
string cmdstr = "insert into UserInfo(FName, LName) values(#First, #Last)";
And use Parameters.AddWithValues using the names:
com.Parameters.AddWithValue("#First", labelFirstName.Text);
com.Parameters.AddWithValue("#Last", labelLastName.Text);

Categories

Resources