Aspx and connecting to a access database on a share - asp.net

Im trying to make a aspx application that connects to a access database on a share.
the path is correct, when i copy paste it in a run screen it opens a database right away.
The weird thing is that the exception that im getting is this, however the database is not a mdb and not in that location either.(it was dutch I translated it, might not be 100% correct translation):
Cant find file C:\Program Files (x86)\IIS Express\dbo.mdb
This is my code:
The exception is fired on the ExecuteReader
namespace AssetDB
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_zoek_Click(object sender, EventArgs e)
{
if (txt_name.Text.Length < 4)
return;
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\netwerk\data\TeamFolders\ICT\Asset Database\_Backend\Assets_be.accdb; "))
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select * from dbo.Bruikleen_Laptops where Laptop_id = #id";
cmd.Parameters.AddWithValue("#id", txt_name.Text);
conn.Open();
using (OleDbDataReader r = cmd.ExecuteReader())
while(r.Read())
{
drop_gevonden.Items.Add(r["Laptop_id"].ToString());
}
conn.Close();
}
}
}
}

Related

MS Access database able to be accessed in debug mode but not accessible when published

I've written some basic code in ASP.NET that accesses a Microsoft Access database, which works when I run in debug mode on IIS Express, but when I published the application and tried to run on the actual website, I get the error.
[IndexOutOfRangeException: There is no row at position 0.]
System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex) +2430497
NIM_Tool.Default.Page_Load(Object sender, EventArgs e) +2321
System.Web.UI.Control.OnLoad(EventArgs e) +106
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3785
From modifying some of my code, I'm pretty confident that the database is unable to be found, but I can't figure out why it's able to be accessed in debug/release mode but not from the published mode. After clicking publish, all files went to the bin/Release/Publish/ folder from the root directory, which I then copied all the children of the Publish folder to the correct server path. The children files/folder also contained the correct MS Access database.
code from the DataLayer.cs file
public class DataLayer {
static OleDbConnection conn;
static OleDbCommand cmd;
static String connString;
static OleDbDataAdapter adp;
private static void CreateCommand()
{
// have also tried hardcoding this to the production server path but this failed too
connString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath("MyDatabase.mdb") + ";Persist Security Info=False;"
conn = new OleDbConnection(connString);
cmd = new OleDbCommand();
cmd.Connection = conn;
adp = new OleDbDataAdapter();
}
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
}
return dt;
}
}
And The Default.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtDeposit = DataLayer.GetDefaultDeposit();
string fixedCost = (string)dtDeposit.Rows[0]["FixedCost"];
}
}
The MyDatabase.mdb file is located in the same directory as the DataLayer.cs file. I've tried hardcoding the database path as well to where it should be accessed on the server, but got the same error message as well.
A little advice: you are being your own enemy when you catch an error and don't do anything with it. It is called "swallowing an error" and it hides root-causes.
Instead, I would recommend doing a re-throw. Put your (original) Exception as the .InnerException. You might want to have your connString in the .Description for the (outer) Exception. (Just in case MapPath didn't do what you thought it should, etc.)
Like this:
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
throw new Exception("ConnString=" + connString, ex);
}
return dt;
}

Using many sql connection in one code?

I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.CommandText += " insert...";
cm.CommandText += " delete from...";
cm.ExecuteNonQuery();
}
co.Close();
}
you can use like this.
You're using the same connection string for each connection? Why do you need three connections? Why not just open and close the same one?
As long as the connection string is the same, you only need one connection.
In general you should prefer to create and open a connection object as close to where you make use of it as possible, and dispose of it as soon as possible afterwards (preferably by making use of a using statement). Connection pooling will take care of ensuring you only actually create a limited number of real connections to the server, despite the large number of SqlConnection objects your code may seem to create.
Within a single method, however, it is reasonable to use a single connection object:
public partial class Home : System.Web.UI.Page
{
string connString = ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection co = new SqlConnection(connString))
{
co.Open();
using(SqlCommand cm = co.CreateCommand())
{
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
using(SqlCommand cmv = co.CreateCommand())
{
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
using(SqlCommand cmf = co.CreateCommand())
{
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
}
}
}
(You don't need to explicitly close the connection object, the Dispose (within the using is equivalent)
No use declaring/creating multiple connections when you would be using only one at a time. You can do with just one.
Declare variable as close as possible to its first use, and with minimum scope manageable.
Make things modular and reusable as far as possible.
No need to explicitly close the connection, since the IDisposable interface implementation (and using block) does it anyways. But there is no harm in explicitly closing it.
protected void Button1_Click(object sender, EventArgs e)
{
ExecuteNonQuery("select...", null); // why??
ExecuteNonQuery("insert...", null);
ExecuteNonQuery("delete from...", null);
}
protected void ExecuteNonQuery(string query, SqlParameter[] parameters)
{
using (SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString))
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = query;
if (parameters != null) cm.Parameters.AddRange(parameters);
cm.ExecuteNonQuery();
}
}
You can also try this.
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" Select statement.. ");
sb.AppendLine(" Insert statement ");
sb.AppendLine(" delete statement ");
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = sb.Tostring();
cm.ExecuteNonQuery();
}
co.Close();
}

Issue regarding implementing SQL Dependency in Application_Start event

i through i will call SQL Dependency related code Application_Start event and my objective will be completed. my scenario is i have a routine in my web application which i invoke manually just clicking on a button when data updated in sql server table. i was told to make this process automated.
so i go through couple of article on SQL Dependency and through i can make my manual process automated by SQL Dependency because we can monitor table change by SQL Dependency and SQL Dependency can notify us when change done.
please see my code
protected void Application_Start(Object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Stop(connectionString);
System.Data.SqlClient.SqlDependency.Start(connectionString);
RegisterNotification();
}
static SqlDependency dep;
private static void RegisterNotification()
{
string tmpdata = "";
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ActivityDate FROM [bba-reman].ContentChangeLog";
dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(OnDataChange);
SqlDataReader dr = cmd.ExecuteReader();
{
while (dr.Read())
{
if (dr[0] != DBNull.Value)
{
tmpdata = dr[0].ToString();
}
}
}
dr.Dispose();
cmd.Dispose();
}
}
finally
{
//SqlDependency.Stop(connStr);
}
}
static void OnDataChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dep = sender as SqlDependency;
dep.OnChange -= new OnChangeEventHandler(OnDataChange);
SiteSearch.CreateIndex(false);
RegisterNotification();
}
protected void Application_End(Object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Stop(connectionString);
}
the above code was running fine but i faced a good problem. suppose no visitor is visiting our web site and at the same time if some one change sql data by a win apps then i saw OnDataChange() event is not firing but if at least one visitor is with our site then OnDataChange() event is firing properly.
may be this is default nature of asp.net engine. i could use SQL Dependency in win service or in winform apps but i have some constrain because the routine which i am calling after detection of data change in db that is in our web application.
So please guide me what i can do as a result OnDataChange() event should always fire if no visitor is visiting our web site.
thanks

update query is not working in ASP.NET web application

using System.Data.SqlClient;
using System.Data.Sql;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=GAGAN-PC\SQLEXPRESS;Initial Catalog=update_test;Integrated Security=True");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void delete_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("delete from update_delete where id like'"+TextBox1.Text+"'",con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully deleted.");
}
protected void update_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("update update_delete set password ='"+TextBox3.Text+"' where id like'"+TextBox2+"'", con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully Updated.");
}
}
I am trying to implement update query but there is a little problem in it. I have used SQL Server as database and update_delete is a table in which there are 3 columns id,sname,password and I am trying to update password with respect to id.
Problem is when I click on update button control reaches cmd.ExecuteNonQuery(); no error is displayed. but updating is not taking place. what should I do. Please Please Please help me. Thanks in advance. :) :)
I'm just guessing here - if Id is a numeric datatype, then you cannot use LIKE with it.
Also: please use using()... blocks to ensure proper disposal and use parametrized queries to avoid SQL Injection attacks.
Write your UPDATE command like this:
protected void update_button_Click(object sender, EventArgs e)
{
// get the values to use
string idValue = Convert.ToInt32(TextBox3.Text.Trim());
string password = TextBox2.Text.Trim();
// define the query text with *parameters* !
string updateQuery = "update update_delete set password = #password where id = #ID";
// put things like SqlConnection and SqlCommand into "using()...." blocks
using (SqlCommand updCmd = new SqlCommand(updateQuery, con))
{
// define parameters and their values
updCmd.Parameters.Add("#password", SqlDbType.VarChar, 50).Value = password;
updCmd.Parameters.Add("#ID", SqlDbType.Int).Value = idValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Data successfully Updated.");
}
}
I suppose you get an Exception. I would kindly suggest to catch your exception and tell us the message... You can catch the exception using the debugger or a try-catch clause.
If you don't get an exception and "Control reached" message is displayed, you would have to use the formed SQL string to use it directly in SQL Server and see if there is a mistake in the SQL statement. I suppose that you somehow form an invalid SQL statement (eg using a non-existing ID).
Hope I helped!

Not able to connect to database in ASP IIS

I was able to deloy my asp project on IIS and it shows the front page, there I have a login page , after entering the credentials it does not logs in, I used try and catch , and in catch it gave me an error, stating thread has aborted, it was on
page.redirect["master.apsx",true]
so I changed it to
page.redirect["master.aspx",false]
and it didnt gave error, but it was not able to login further, I guess it is not able to connect to database. So any help would be appreciable.
Thanks
CODE:
protected void Page_Load(object sender, EventArgs e)
{
strconn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~/App_Data/Securityservice.mdf") + ";Integrated Security=True;User Instance=True";
Label1.Text = " conn string";
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void btn_popup_quick_login_Click(object sender, EventArgs e)
{
try
{
if (txt_username.Text != null)
{
if (txt_password.Text != null)
{
DataTable dt = new DataTable();
conn = new SqlConnection(strconn);
conn.Open();
cmd = new SqlCommand("Select * From UserMaster Where Username=#username and Password=#password", conn);
cmd.Parameters.AddWithValue("#username", txt_username.Text);
cmd.Parameters.AddWithValue("#password", txt_password.Text);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
{
if (dt.Rows.Count > 0)
{
userloginname = txt_username.Text;
userloginpassword = txt_password.Text;
Session["username"] = txt_username.Text;
MessageBox.Show("User Login Sucessfully", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
Response.Redirect("Marketing.aspx",false);
}
else
{
Label1.Text = "else part";
MessageBox.Show("Invalid User Name and Password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txt_username.Focus();
}
txt_username.Text = "";
txt_password.Text = "";
}
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); }
conn.Close();
Label1.Text = "login";
}
You should check the connection strings in web.config, to make sure they still point to the proper location of the database after you deployed the site.
I think the problem could be the Application_Start method.
Look if you have written some thing there.
Make a break point there and see is there any error.
Or have you written Response.End() in you code?
You need to provide more detail
You need to check weather you are able to connect to database or not.
You also need to check weather the page is called or not (which comes after login).

Resources