asp.net database connection with Access - c#

I want to make a login page with an Access database for a school project with asp.net. I dont have really experience with C# so im doing different tutorials.
protected void Login1_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://tmti-16.ict-lab.nl/database/ek2012.mdb";
string query = "Select Count(*) From users Where username = ? And userpassword = ?";
int result = 0;
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", UserName.Text);
cmd.Parameters.AddWithValue("", Password.Text);
conn.Open();
Session["User"] = UserName.Text;
result = (int)cmd.ExecuteScalar();
}
}
if (result > 0)
{
Response.Redirect("index.aspx");
}
else
{
Literal1.Text = "Invalid credentials";
}
}
In Access I have the table 'users' with the 'username' and 'userpassword' rows.

The problem you are encountering is almost certainly to do with the data source segment of your connection string:
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://tmti-16.ict-lab.nl/database/ek2012.mdb"
The Access mdb file should be on a local path. This can be anywhere on your local file system that the account your web application is running as has permission to access, but, usefully, ASP.Net actually has a better place to put these files, the App_Data folder.
If you place your mdb file in this folder, your connection string would then become:
string connect = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|ek2012.mdb"
The contents of the App_Data folder will not be served to clients so this is a secure place to put your data. It's also a good idea to use it as it keeps the data with the project; often, people will put data related files in a file system folder outside of the web root, which means you then have to remember this dependency when moving the site to another computer.
A common issue you might have with accessing files in App_Data is usually related to permissioning; the user you are running the code as will need read and write permissions in this directory in order to modify the mdb file. This is covered in the section "Configuring Permissions for an Access Database" in this MSDN Article.

Related

C# Winform SQL Server Connection String

Working on a WinForm project making use of SQL Server.
Currently my MusicPlayerDB.mdf has its Copy to Output Directory property set to Copy if newer.
After I run my InsertIntoDB, I close the Winform and proceed to check the table over in Server Explorer. But is seems as my table wasn't updated. But if I go to check Bin/Debug and check MusicPlayerDB.mdf, the data is there.
What would be the best way to fix this? I've seen other comments saying to use the absolute path of the .mdf (or something along those lines), but I would like to avoid that if possible.
Here is my connection string,
private const String CONNECTION_STRING = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MusicPlayerDB.mdf;Integrated Security=True";
And here is my insert code:
private static void InsertIntoDB(List<string> userAccout)
{
String sqlQuery = "INSERT INTO dbo.UserAccount (UserName, UserPassword, PasswordQuestion, PasswordHint, PasswordKey) "
+ "VALUES (#UserName, #UserPassword, #PasswordQuestion, #PasswordHint, #PasswordKey);";
using(SqlConnection connection = new SqlConnection(CONNECTION_STRING))
{
connection.Open(); //open connection
using(SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// set up command
using(SqlTransaction trans = connection.BeginTransaction())
{
try
{
command.Connection = connection;
command.Transaction = trans;
command.Parameters.AddWithValue("#UserName", userAccout[0]);
command.Parameters.AddWithValue("#UserPassword", userAccout[1]);
command.Parameters.AddWithValue("#PasswordQuestion", userAccout[2]);
command.Parameters.AddWithValue("#PasswordHint", userAccout[3]);
command.Parameters.AddWithValue("#PasswordKey", Convert.ToInt32(userAccout[4]));
int r = command.ExecuteNonQuery(); //execute the command
trans.Commit();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message); //couldn't execute command
}
}
}
}
} //end of InsertIntoDB
This is how it is expected to work. |DataDirectory| in a desktop app point to where your executable runs. This means bin\debug or bin\release (the working folders) when you run the app inside VS but the installation folder when you run the app outside VS.
This arrangement allows you to keep your empty MDF in the project folder while a working copy stays in your output folders. When you need to change something in the schema of your database you use Server Explorer to change the copy in your project folder. So a new copy of the file will be copied in the output folders at the start of the next VS session. When you need to distribute your app you distribute the MDF file in your project folder.
Of course, if you need to check what happens in the working copy of your db then you can create a new connection inside Server Explorer that points to the MDF file in the working folders.
If you need more control then you can change where the substitution string |DataDirectory| points. See, for example, this Question and my answer there

Why session timeouts after OledbConnection open

i am calling the OledbConnection to Microsoft Access Database. there is no issue calling the method and also retrieves necessary data.
i dont know after that method the session timeouts automatically. and goes to login page. why?
i have lost entire day debugging and finding the issue.
string strQuery = "select count(LOC1) as LOC1 from shrmwise";
DataTable dt = new DataTable();
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
using (OleDbCommand command = new OleDbCommand(strQuery, connection))
{
try
{
OleDbDataReader reader = command.ExecuteReader();
dt.Load(reader);
reader.Close();
}
catch (Exception ex)
{
throw ex;
//Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
return dt;
}
}
Edited
Does not timeout if the above method call is commented.
it does not timeout on localhost, but on live server.
my connectionString as follows
string connectionString =
#"Provider=Microsoft.Jet.OLEDB.4.0;" +
#"Data Source=E:\Data\MyDatabase.mdb;" +
#"User Id=;Password=;";
Usually in a IIS/ASP.NET environment the application runs with MEDIUM TRUST settings and not with FULL TRUST. This means that your code cannot access any part of the file system that resides outside the root of your site.
To resolve the problem in which applications need a place where they can read and write without worrying about too much security restrictions a convention has been adopted.
The convention is to have a subfolder of the site root called APP_DATA where the user (IUSR) under which the ASP.NET service runs your application has Read/Write permissions. Here you can place your database or other read/write files. Create subfolder to store different type of documents and so on.
So your problem can be solved just following the convention and moving the database in that folder. Or, after verifying the security consequences of such move, force your site to run in FULL TRUST.
Of course if you have to manually create the APP_DATA folder be sure to also set the correct permissions for the IIS user.

C# mdf local database

I googled for half a day how to set the path of my database so if I put it on an other computer it will work. I would keep googling but I really need the answer really fast... I'll have to use it to a competition in few hours.
string path = Path.Combine(Application.StartupPath, "Database1.mdf");
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + path + ";");
conn.Open();
SqlCommand command = new SqlCommand("SELECT NAME FROM DATA", conn);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string text = reader.GetString(0);
MessageBox.Show(text);
}
SqlCommand c = new SqlCommand("INSERT INTO DATA (id, name) VALUES(i, v)", conn);
c.Parameters.AddWithValue("#i", 1);
c.Parameters.AddWithValue("#v", "Jack");
c.ExecuteNonQuery();
conn.Dispose();
This code is working for selection but not for insertion. Then I hardcoded the path into:
String s = #"C:\Users\Radu\Documents\Visual Studio 2013\Projects\WindowsFormsApplication7\WindowsFormsApplication7\Database1.mdf";
and it works for both so it's not the SQL statement that is wrong.
So my question is: what is the path I should put into my SqlConnection object so that when they get my source code on my competition and test it on another pc it will work.
LocalDB is meant exclusively for development. You cannot use it in production. In your case, 'production' means the competition. Unless the competition organizer specifies that they support a SQL Server instance for you to connect to, and give out the connection parameters (ie. very unlikely), you shouldn't use use SQL Server in your project.
You can put the MDF file on any file share that your computer has access to. Just alter the path variable to point at the correct file share.
See answers to your question here Can SQL Server Express LocalDB be connected to remotely?

Can i make sql Database part of c# Project

I have made a sample c# application (First project ive done) Its quite a simple application which uses a database to store data and edit data.
The problem i am having is the program works perfectly fine on my computer but if i publish the application and put it on another computer it cannot use the database as it is not part of the project.
I used connection string
private SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\Ryan\\Documents\\Visual Studio 2015\\Projects\\youtubeLoginTut\\youtubeLoginTut\\data.mdf\"; Integrated Security = True; Connect Timeout = 30");
Which is obviously the path to the database on my computer and will not be the same on the next computer. Is there anyway i could include the database in the package so its referenced from where ever the application sits.
Ive tried shortening the path to for example ..\data.mdf but to no avail and i cant find anything on google so im all out of ideas.
Go easy im very new to c#
Cheers
Ryan
There is a way to get the location of your project in every computer : (inside the bin/debug/)
string path = AppDomain.CurrentDomain.BaseDirectory //example : C:/Users/Ryan/Documents/Visual Studio 2015/Projects/Youtubetut/bin/debug
you just need add the location of the database inside of the project's folder to this path. path will replace your "C:\Users\Ryan\Documents\Visual Studio 2015\Projects\youtubeLoginTut" and make sure to move your database inside the debug folder.
Afeter publiching your database with your project you get the Installtion Path From Deployment byuse :
string sourcePath =System.Reflection.Assembly.GetExecutingAssembly().Location
sourcePath =sourcePath +"\data.mdf";
If it's a simple application you can try to use embeded DB like SQLite. I use it in my application and it works fine.
If you want to use SQLite, let's go step by step.
download the dynamic library System.Data.SQLite.dll for your version of the .NET Framework
link System.Data.SQLite.dll to your project
write a code something like this
Create a table
SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=True;", "./db/mydatabase.sdb"));
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = #"CREATE TABLE Books (BookId int, BookName varchar(255), PRIMARY KEY (BookId));";
cmd.ExecuteNonQuery();
con.Close();
Read the data
using(SQLiteConnection con = new SQLiteConnection(String.Format(#"Data Source={0};Version=3;New=False;", "./db/mydatabase.sdb")) {
con.Open();
using (SQLiteCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT BookName FROM Books WHERE BookId=1 LIMIT 1;";
using (SQLiteDataReader reader = cmd.ExecuteReader()) {
if (reader.HasRows && reader.Read()) {
oResult = Convert.ToString(reader["BookName"]);
}
reader.Close();
}
}
con.Close();
}

Image not display in webpage

I am using VS 2010 for developing a web application. I am storing the uploaded images in physical path of the Server and also created virtual path in IIS 7.5 (the screenshot below).In Authorization,one Warning is displayed.For using the belo code I try to retrieve the image from the server but the image is not display.Where the problem, in virtual path or in the path mention in code ?
private void CallImage()
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
SqlCon.Open();
string query = "SELECT Cmp_DocPath FROM Company_Info WHERE
Vendor_ID= '" + ddlVendorID.SelectedValue + "'";
SqlCommand SqlCmd = new SqlCommand(query, SqlCon);
SqlDataAdapter da = new SqlDataAdapter(SqlCmd);
DataTable dt = new DataTable();
da.Fill(dt);
string ImageName = Convert.ToString(dt.Rows[0][0].ToString());
Image1.ImageUrl = this.ResolveUrl("D:/Upload/Commerical Certificates/"+ImageName);
// Image1.ImageUrl = this.ResolveUrl("D:\\Upload\\Commerical Certificates\\"+ImageName);
// Image1.ImageUrl = this.ResolveUrl("~\\Upload\\Commerical Certificates\\"+ImageName);
SqlCon.Close();
}
You can't reference a physical location to an image and expect it to work on a Web site. Store the paths to the images as virtual paths from the root of the site. For instance:
If your site root is at:
d:\inetpub\mysite\
And your images are at:
d:\inetpub\mysite\uploads\images\
Then your virtual paths int he database need to be:
~\uploads\images\image1.jpg
~\uploads\images\image2.jpg
Then you can set that as the ImageUrl property and no, you don't need to resolve it (the Image control does that automatically).
My guess is that the reason you're having this problem is because you are trying to reference images that are not within the Web site, which even if you get to work in your dev environment by giving access to NETWORK SERVICE, IIS_IUSRS, the second you move this application into a production environment, you are going to have problems. Not to mention that is a very poor way to do things in terms of security and modularity.
The username that you used might not have read/write permissions on server. Go to the user settings of the corresponding user and enable read and write permission. Also check whether you are giving the correct path of the image. Hope it helps.

Categories