I am a newcomer in .net , my problem is related to email. This code is well performed on my localhost. This is code of my enquiry.aspx.cs:-
protected void Button1_Click(object sender, EventArgs e)
{
Mail mm = new Mail();
if (DropDownList3.SelectedItem.Text == "--Select--")
{
Label5.Text = "Please Select Course";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
}
else if (TextBox1.Text == "")
{
Label5.Text = "Please Enter Name";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Name');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Name'); </script>");
TextBox1.Focus();
}
else if (mm.checkValidemail(TextBox2.Text) == false)
{
Label5.Text = "Please Enter E-Mail ID";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter E-Mail ID');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter E-Mail ID'); </script>");
TextBox2.Focus();
}
else if (mm.checkValidmobile(TextBox3.Text) == false)
{
Label5.Text = "Please Enter Mobile Number";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Error", "alert('Please Enter Mobile Number');", true);
//Response.Write("<script language=JavaScript> alert('Please Enter Mobile Number'); </script>");
TextBox3.Focus();
}
else
{
myenquiry ee = new myenquiry();
//myenquiry ee=new myenquiry();
int i = ee.add_enquiry(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, "-", "-", "NORMAL ENQUIRY FROM SITE", TextBox11.Text, DropDownList3.SelectedItem.Text, TextBox12.Text,locationlst.SelectedItem.Text);
if (i == 1)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(" Enquiry " + "<shila#gmail.com> ");
message.To.Add(new MailAddress("shu#gmail.com"));
message.CC.Add(new MailAddress("va_aone#yahoo.com"));
message.Subject = "Enquiry from CMC site";
string p = "<b>Name: </b>" + TextBox1.Text;
p += "<br><b>Mobile:</b> " + TextBox3.Text;
p += "<br><b>Mail ID:</b> " + TextBox2.Text;
p += "<br><b>Address:</b> " + TextBox4.Text;
p += "<br><b>City:</b> " + TextBox5.Text;
p += "<br><b>Location:</b>" + locationlst.SelectedItem.Text;
p += "<br><b>College:</b> " + TextBox11.Text;
p += "<br><b>Course:</b> " + DropDownList3.SelectedItem.Text;
p += "<br><b>Query:</b> " + TextBox12.Text;
message.Body = p;
message.IsBodyHtml = true;
SmtpClient SMTPServer = new SmtpClient("localhost");
try
{
SMTPServer.Send(message);
//result = "Your Enquiry has been Submitted !!";
Label5.Text = "Your Enquiry has been Submitted !!";
//Response.Write("<script language=JavaScript> alert('Your Enquiry has been Submitted !!'); </script>");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox11.Text = "";
TextBox12.Text = "";
DropDownList3.SelectedIndex = 0;
}
catch
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
//Response.Write("<script language=JavaScript> alert('Server Problem !!Your Enquiry Not Submitted'); </script>");
}
}
else
{
Label5.Text = "Server Problem !!Your Enquiry Not Submitted";
}
}
and this is my appcode folder enquiry.cs:-
public class myenquiry
{
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=group;Integrated Security=True");
SqlCommand comm = new SqlCommand();
int result = 0;
public int add_enquiry(string nam,string email,string mob,string adr,string cit,string state,string country,string zip,string college,string tech,string query,string loc)
{
try
{
comm.Connection = conn;
comm.CommandText = "insert into enquiry(name,email,mobile,address,city,state,country,zip,college,technology,query,edate,location) values('" + nam + "','" + email + "','" + mob + "','" + adr + "','" + cit + "','" + state + "','" + country + "','" + zip + "','" + college + "','" + tech + "','" + query + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','"+loc+"')";
conn.Open();
comm.ExecuteNonQuery();
result = 1;
}
catch(Exception ee)
{
result = 0;
}
finally
{
conn.Close();
}
return result;
}
}
this is well perform on local. But at the server the appcode enquiry.cs is not called on enquiry.aspx.cs and the value of int i is becoming 0, so the else part is executing. Why?
You seem to have a hard coded connection string in the myenquiry class. If you are not dynamically setting the connection string from a configuration file or otherwise, the insert method will try to use that string which points to your local. Assuming your server is a different domain/machine with no access to your local DB, the connection will definitely fail, giving you the result 0.
As Shree.pat18 says Don't make hardcodded connection string in class file.instead of this make your connection string in web.config file something like this in your configuration tag
<connectionStrings>
<add name="cn" connectionString="Data Source=USER-PC;Initial Catalog=group;Integrated Security=True"/>
</connectionStrings>
Related
The table is not updated, it only does "insert" to the text I put in the textbox. Can someone tell me what's wrong? Here is my code:
protected void update_b_Click(object sender, EventArgs e)
{
//Update employee details
try
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update employees set Emp_number='" + emp_num.Text + "',First_name='" + emp_fname.Text + "', Last_name='" + emp_lname.Text + "',Phone_num='" + emp_phone.Text + "',Email='" + emp_email.Text + "'where Emp_number='" + emp_num.Text + "'";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("employee details updated successfuly");
emp_num.Text = "";
emp_fname.Text = "";
emp_lname.Text = "";
emp_phone.Text = "";
emp_email.Text = "";
Bind1();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i have problem durin verifying user by email...here is my code for registtration page..
protected void btnsignup_Click(object sender, EventArgs e)
{
MailMessage msg;
//SqlCommand cmd = new SqlCommand();
string ActivationUrl = string.Empty;
string emailId = string.Empty;
try
{
//Sending activation link in the email
msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
emailId = txtemail.Text.Trim();
//sender email address
msg.From = new MailAddress("xyz#gmail.com");
//Receiver email address
msg.To.Add(emailId);
msg.Subject = "Confirmation email for account activation";
//For testing replace the local host path with your lost host path and while making online replace with your website domain name
ActivationUrl = Server.HtmlEncode("http://localhost:51049/ActivateAccount.aspx?CustomerId=" + FetchUserId(emailId) + "&EmailId=" + emailId);
msg.Body = "Hi " + txtName.Text.Trim() + "!\n" +
"Thanks for showing interest and registring in <a href='Home.aspx'> e2e website <a> " +
" Please <a href='" + ActivationUrl + "'>click here to activate</a> your account and enjoy our services. \nThanks!";
msg.IsBodyHtml = true;
smtp.Credentials = new NetworkCredential("xyz#gmail.com", "xxxxxx");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.Send(msg);
if (result > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Confirmation Link to activate your account has been sent to your email address');window.location='LoginPage.aspx'", true);
ClearControl(this);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Account has not been created.');'", true);
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
return;
}
finally
{
con.Close();
}
}
protected string FetchUserId(string emailId)
{
SqlCommand cmd = new SqlCommand("select CustomerId from tbl_CustomerRegistration WHERE CustomerEmail=#CustomerEmail", con);
cmd.Parameters.AddWithValue("#CustomerEmail", emailId);
string CustomerId = cmd.ExecuteScalar().ToString();
return CustomerId;
}
and code for ActivateMyAccount.aspx...
SqlCommand cmd = new SqlCommand();
try
{
if ((!string.IsNullOrEmpty(Request.QueryString["CustomerId"])) & (!string.IsNullOrEmpty(Request.QueryString["CustomerEmail"])))
{
//approve account by setting Is_Approved to 1 i.e. True in the sql server table
cmd = new SqlCommand("UPDATE tbl_CustomerRegistration SET Is_Approved=1 WHERE CustomerId=#CustomerId AND CustomerEmail=#CustomerEmail", con);
cmd.Parameters.AddWithValue("#CustomerId", Request.QueryString["CustomerId"]);
cmd.Parameters.AddWithValue("#CustomerEmail", Request.QueryString["CustomerEmail"]);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int result= cmd.ExecuteNonQuery();
if(result>0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Your account has been activated. You can login now');window.location='LoginPage.aspx'", true);
}
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
return;
}
finally
{
con.Close();
cmd.Dispose();
}
}
user is getting email after registration but the problem is when user click on verify link then a field in database name as Is_Aprroved is not gettting updated ...thank u ..please help me
I have a small ASP.NET registration page linked to a database. If the user enters the username that already exists in the database, then it should display "user already exists", but it is not doing that:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists!!");
}
conn.Close();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Country and age!");
}
else if(this.DropDownListCountry.SelectedValue == "-Select-" && this.DropDownListAge.SelectedValue != "-Select-")
{
Response.Write("Select Country!");
}
else if (this.DropDownListCountry.SelectedValue != "-Select-" && this.DropDownListAge.SelectedValue == "-Select-")
{
Response.Write("Select Age!");
}
else
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
}
}
}
I think you should try first
If ( temp > 0)
{
}
also debug to see what is returned by the sql query
Few Things.
You need to check this before inserting the data.
You are not preventing entering the same data if the username still exists
You can check top 1 instead of count.
private bool IsUserExists()
{
bool UserExists = false;
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string check = "Select Count(*) from Registration where UserName = '"+TextBoxUN.Text+"';";
SqlCommand comm = new SqlCommand(check, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp >= 1)
{
UserExists = true;
Response.Write("User already exists!!");
}
conn.Close();
}
return UserExists ;
}
Check this before inserting the data.
try
{
if(UserExists())
return; //Skips further code when user exists.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQ = "insert into Registration(UserName,Email,Password,Country,Age) values ('" + TextBoxUN.Text + "','" + TextBoxEmail.Text + "','" + TextBoxPass.Text + "','" + DropDownListCountry.SelectedItem.ToString() + "','" + DropDownListAge.SelectedItem.ToString() + "');";
SqlCommand comm = new SqlCommand(insertQ, conn);
comm.ExecuteNonQuery();
Response.Redirect("Display.aspx");
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error : " + ex.ToString());
}
My update button is not functioning. Whenever I want to update any record, it will not works.
Radio button must be checked in order to update any records in a gridview. After the button is checked, the user will click an update button (located above the gridview). then a page will be displayed. the page will display all the information (in a form view) of the user. he/ she will just change any information they want. after that the user should click update button located below. It is like submitting the form again. But the form is not updated. What should i change?
Below is the code for update button:
protected void update_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string datestart_s = (string)(Session["datestart"]);
datestart_s = Convert.ToDateTime(datestart_s).ToString("yyyy-MM-dd");
string leavetype_c = (string)(Session["leavetype"]);
string X = TextBox3.Text;
string substring1 = X;
string substring2 = "";
foreach (string value in X.Split('-'))
if (X.Length > 40)
{
substring1 = X.Substring(0, 40);
if (X.Length == 80)
{
substring2 = X.Substring(39, 40);
}
else
{
int Xlength = X.Length - 40;
substring2 = X.Substring(40, Xlength);
}
}
OdbcConnection connection = null;
OdbcCommand com = null;
string queryString = "UPDATE QMBSTEST.SCEMLV SET LVTYPE='" + leave.SelectedItem.Value + "', LVDTST='" + start.Text + "', LVDTED='" + end.Text + "', LVDAYS='" + TextBox2.Text + "', LVAMPM='" + time.SelectedItem.Value + "', LVTEXT1='" + substring1 + "', LVTEXT2='" + substring2 + "', LVFLAG='" + apply.SelectedItem.Value + "' WHERE LVEMID='" + TB_EMPID.Text.Trim().ToUpper() + "' AND LVDTST='" + datestart_s.Trim() + "' AND LVTYPE='" + leavetype_c.Trim() + "'";
connection = new OdbcConnection(#"Dsn=as400;Uid=FATIN;Pwd=FATIN;");
com = new OdbcCommand(queryString, connection);
connection.Open();
com.ExecuteNonQuery();
connection.Close();
lblMessage.Text = "Form updated!";
lblMessage.ForeColor = System.Drawing.Color.GreenYellow;
}
}
Are you validating that event with any customvalidator?
If yes then replace :
if (Page.IsValid)
With
IF(!IsValild)
return:
and then ur code.....
Because you not doing anything when any of your validation through validation control got failed.
I am a newcomer in .NET. When I am uploading an image, I get an error of
System.UnauthorizedAccessException:
Access to the path 'C:\Inetpub\vhosts\cmcnoida.com\httpdocs\i_image\123' is denied.
This code works on local very well, but at the live server above error is generating. What can I do?
My code:
protected void Button1_Click(object sender, EventArgs e)
{
string t_sname, t_cname, t_pack, t_college, t_djoin;
if (TextBox2.Text == "")
{ t_sname = "-"; }
else
{ t_sname = TextBox2.Text; }
if (TextBox3.Text == "")
{ t_cname = "-"; }
else
{ t_cname = TextBox3.Text; }
if (TextBox4.Text == "")
{ t_pack = "-"; }
else
{ t_pack = TextBox4.Text + " lacs pa"; }
if (TextBox5.Text == "")
{ t_college = "-"; }
else
{ t_college = TextBox5.Text; }
if (TextBox6.Text == "")
{ t_djoin = "-"; }
else
{ t_djoin = TextBox6.Text; }
// conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=cmcnoida;Integrated Security=True");
conn = new SqlConnection("Data Source=127.0.0.1;Integrated Security=False;User ID=kvch_db;Connect Timeout=200;Encrypt=False;Packet Size=4096;Database=cmcnoida;password=kv_12_2014");
//conn = new SqlConnection("server=singhal;database=abc;Trusted_Connection=yes");
comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "select max(id) from placement";
conn.Open();
int i = (int)comm.ExecuteScalar();
conn.Close();
string a = (i + 1).ToString();
DirectoryInfo dd2 = new DirectoryInfo(Server.MapPath("~\\i_image\\" + a));
dd2.Create();
dd2.Refresh();
string fup;
if (FileUpload1.HasFile == true)
{
fup = "~\\i_image\\" + a + "\\" + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(fup));
}
else
{
fup = "~\\i_image\\" + a + "\\dummy-man.jpg";
File.Copy(Server.MapPath("~\\admin\\dummy-man.jpg"), Server.MapPath("~\\i_image\\" + a + "\\dummy-man.jpg"));
}
comm.Connection = conn;
comm.CommandText = "insert into placement values('" + t_sname + "','" + t_cname + "','" + t_pack + "','" + t_college + "','" + t_djoin + "','" + fup + "')";
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
// binddatagrid();
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
TextBox2.Focus();
Response.Write("<script language=JavaScript> alert('Placement Record Inserted !!'); </script>");
}
What should I do to solve this issue?
If you are hosting this on your server you need to set permissions on the folder. Here is a good read on What are all the user accounts for IIS/ASP.NET and how do they differ?
But I doubt it not the case here. I think you are hosting it on a shared environment here.
If that's the case, you cannot set server folder security permissions using code. So you have to contact your hosting providers and ask them to give permissions to the i_image folder.
I mentioned i_image folder because the child folder 123 looks dynamic from your code. Setting permission to the root folder is enough.
In many cases where access security is concerned you need to use ASP.NET Impersonation (run as Windows User Account). You then need to make some changes i web.config.
<configuration>
<system.web>
<identity impersonate="true"/>
</system.web>
</configuration>
<identity impersonate="true" userName="DOMAIN\UserName" password="***" />
You need to supply the user credentials that have write access to the folder you want to write to.
These settings can also be done in IIS on the Application pool.