Not able to connect to database in ASP IIS - asp.net

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).

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;
}

SQL simple registration - all time exception

i have problem with registration in ASP.NET.
When i try to add new user to table in sql i catch exception. No idea what is wrong, in my opinion code is correct.
Look at this:
public partial class Registeration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RejConnectionString"].ConnectionString);
con.Open();
string cmdStr="Select count(*) from Registration where UserName='" + TextBoxUN.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
Response.Write("Already exist.<br /> Change another nickname.");
}
}
}
protected void Wyślij_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RejConnectionString"].ConnectionString);//połączenie z bazą
con.Open();
string insCmd = "Insert into Registration (UserName, Password, EmailAddress, FullName, Country) values (#UserName, #Password, #EmailAddress, #FullName, #Country)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#UserName,", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Password", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#Country", DropDownListCountry.SelectedItem.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("/Account/Login.aspx");
}
catch (Exception er)
{
Response.Write("<b>STH bad happened :( Try again</b>");
}
finally
{
}
}
}
well
1. DO NOT DO REDIRECTs inside of TRY!!!! Response.Redirect("/Account/Login.aspx"); NO NO!!
2. if you do with finally DO THE CLOSE connection there
I will redo this try Open connection to be inside as well

How to connect to SQL Server using ADO.Net

This is the first time I'm designing a web site. I'm having problem on connecting to my database. None of buttons work on pages. The most important one is Register button. I fill the form correctly but when I press Register button it doesn't register the new user into database. It even doesn't show any error message which I've considered. For example, it doesn't show that You've registered before or Your registration wasn't successful. No error message and no new record in my database. I've removed the captcha code because I thought that may cause problem.Here's my code:
using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strname = Cache["TF"] as string;
if (strname != null)
{
(Master.FindControl("Lozv") as Label).Text = strname;
(Master.FindControl("LinkButton1") as LinkButton).Visible = true;
}
else
{
(Master.FindControl("Lozv") as Label).Text = "Guest";
(Master.FindControl("LinkButton1") as LinkButton).Visible = false;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
string username = txtboxUser.Text;
SqlConnection sqlc = new SqlConnection("Data Source=.; Database=LDatabase; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT dbo.CheckUserName(#UN)");
cmd.Parameters.AddWithValue("#UN", txtboxUser.Text);
sqlc.Open();
Boolean User = Convert.ToBoolean(cmd.ExecuteScalar());
sqlc.Close();
if (User == false) ////////////// if user name is not in DB//////////////
{
SqlConnection sqlca = new SqlConnection();
sqlca.ConnectionString = "data source=. ; database=LDatabase ; integrated security=true";
SqlCommand cmda = new SqlCommand();
cmda.Connection = sqlca;
cmda.CommandText = "INSERT INTO User_Pass values(#UserName,#Pass,#Name,#LastName,#Email,#Date,#Sex,'0')";
cmda.Parameters.AddWithValue("#UserName", txtboxUser.Text);
cmda.Parameters.AddWithValue("#Pass", txtboxPass.Text);
cmda.Parameters.AddWithValue("#Name", txtboxName.Text);
cmda.Parameters.AddWithValue("#LastName", txtboxSurname.Text);
cmda.Parameters.AddWithValue("#Email", txtboxEmail.Text);
cmda.Parameters.AddWithValue("#Date", DateTime.Now);
cmda.Parameters.AddWithValue("#Sex", rbtnGender.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#manager", "No");
sqlca.Open();
int n= cmda.ExecuteNonQuery();
if (n <= 0)
LMsg.Text = "Your registration wasn't successful";
else
{
txtboxName.Text = "";
txtboxSurname.Text = "";
txtboxUser.Text = "";
txtboxPass.Text = "";
txtboxRePass.Text = "";
txtboxEmail.Text = "";
rbtnGender.SelectedIndex = -1;
LMsg.Text = "You registered successfully.";
}
sqlca.Close();
}
else //////////////if user name is in db//////////////
{
LMsg.Text = "This username has already registered.";
}
}
}
Does Captcha have anything to do with this type of problem? Any help would be appreciated.
Put your button like this in the aspx-markup:
<asp:Button ID="btnRegister" runat="server" Click="Button1_Click1" Height="26px" Text="register" Width="88px"/>
It should trigger the method.
Edit: Or bind the event in the Page_Load method (remove the Click-attribute from the button first - from my previous example above).
protected void Page_Load(object sender, EventArgs e)
{
btnRegister.Click += new EventHandler(Button1_Click1);
string strname = Cache["TF"] as string;
[...]

How to check if email is already in use in asp.net and making sure email is available before allowing the user to register?

I need to check an SQL Server database (not asp.net membership) to see if an email is already in use before allowing the user to register.
I have tried using the information in this website but it does not seem to work.
Your help will be much appreciated
You can try
protected void txtUsername_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUsername.Text))
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like " + txtUsername.Text.Trim(), con);//I changed
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
}
con.Close();//I added
}
else
{
checkusername.Visible = false;
}
}

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Resources