How to set the directory permission in .NET 3.5? - asp.net

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.

Related

I have an error when I delete an image from folder

`protected void LinkButtondelete_Command(object sender, CommandEventArgs e)
{
int macv = 0;
if (Page.Request.Params["id"] != null)
macv = int.Parse(Page.Request.Params["id"]);
if (macv != 0)
{
string sqldelete = "delete from T_CongViec_Attach where MaAttachFile=" + e.CommandArgument.ToString() + " and MaCV=" + macv;
ulti.ExecSqlDataSet(sqldelete);
}
else
{
string sqldelete = "delete from T_Attachfile_CV where id=" + e.CommandArgument.ToString();
ulti.ExecSqlDataSet(sqldelete);
}
foreach(DataListItem item in DataListAttachfile.Items)
{
string vitualpath = System.Configuration.ConfigurationManager.AppSettings["UploadPath"].ToString() + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/" + att.Duongdanfile;
string savepath = HttpContext.Current.Server.MapPath("/" + vitualpath);
File.Delete(MapPath(vitualpath));
}
show_data(macv);
lblMessage.Text = "Delete successffully!";
}`
and this is the error:Access to the path 'D:\cms_vietnamnews_final\ToasoanTTXVN\Upload\Images\2018\9\19\' is denied.
It might be the App pool, and to fix it you need to login to Plesk and navigate to file [file manager] then select the folder you need and change the permissions by giving the [Application pool group ] the required permission.

Why isn't my database logic throwing an exception when I enter data that already exists?

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

Update button not functioning

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.

why my server.mappath() is not working in another pc?

i have project in my pc..but when i am saving my uploaded files in a folder inside my project.now when i am transferring my project in another pc the server.mappath() is not working..why??
my problem upload function
protected void addproblem_Click(object sender, EventArgs e)
{
string filepath;
if (problemupload.HasFile)
try
{
if(problemupload.PostedFile.ContentType=="application/pdf")
{
// problemupload.SaveAs("F:\\0\\My project website\\sgipc\\problems\\" + problemupload.FileName);
// filepath = "F:\\0\\My project website\\sgipc\\problems\\" + problemupload.PostedFile.FileName;
problemupload.SaveAs(Server.MapPath("\\sgipc\\problems\\" + problemupload.FileName));
filepath = Server.MapPath(problemupload.PostedFile.FileName);
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string userid = Convert.ToString(Session["userid"]);
SqlCommand cmd = new SqlCommand("INSERT INTO problemtable(problemname,problempath,userid,status) Values('" + probbox.Text + "','" + filepath + "','" + userid + "','" + "pending" + "')", objsqlconn);
cmd.ExecuteNonQuery();
objsqlconn.Close();
}
else
{
Response.Write("<script>alert('" + "Only pdf format is allowed..." + "')</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.ToString() + "')</script>");
}
else
{
Response.Write("<script>alert('" + "you have not specified a file..." + "')</script>");
}
}
i am getting this error
"System.InvalidOperationException: Failed to map the path '/sgipc/tutorials/v6-1446-1449.pdf'."
while uploading a file from another pc..but from my pc it works fine..
I think there is problem in Server.MapPath try with this syntax FileUploadControl.SaveAs(Server.MapPath("~/sgipc/problems/" + problemupload.FileName));
~ sign will automatic configure path from server and it is better then \\ sign for map path..

Regarding to not calling of enquiry.cs in app code

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>

Resources