I have an error when I delete an image from folder - asp.net

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

Related

MVC UPLOAD IMAGE SAVE IN SQL using ado.net with update (i edit any text box . the image disappear)

[HttpPost]
public ActionResult Create(Showroom showroom)
{
objShowroom.InsertShowroomDetails(showroom);
return RedirectToAction("Index");
}
I had separate data access layer
how to update the upload image in database
insert query no problem with that
if I edit any textbox image will disappear in postback or roundtrip
5. I will use not entity framework so I want to connect with model using ado.net
model folder:
public int UpdateShowroomDetails(Showroom objShowroom)
{
sqlCommandText = "Update Showroom Set CARIMAGE='" + objShowroom.CARIMAGE + "', CARNAME='" + objShowroom.CARNAME + "', CARBRAND='" + objShowroom.CARBRAND + "', PRICE=" + objShowroom.PRICE + " Where ID="+objShowroom.ID ;
return objDAL.ExecuteNonQuery(sqlCommandText);
}
Here is how i save d my image to db using ado.net . Hope this will help you
string fileName = string.Empty;
string servr_path = string.Empty;
string serviceId = string.Empty;
string planId = string.Empty;
if (IdProofFile.HasFile && IdProofFile.PostedFile.FileName != "")
{
string fileType = IdProofFile.PostedFile.ContentType;
if (fileType == "image/jpg" || fileType == "image/jpeg" || fileType == "image/png" || fileType == "image/gif")
{
int fileSize = IdProofFile.PostedFile.ContentLength;
if (fileSize <= 2097152)
{
//fileName = System.IO.Path.GetFileName(IdProofFile.PostedFile.FileName);
fileName = "ID-" + txt_FirstName.Text + "_" + txt_LstName.Text + DateTime.Now.ToString("ddmmyy_hhMMss") + Path.GetExtension(IdProofFile.PostedFile.FileName);
string serverFolder = Server.MapPath("idProof//");
if (!System.IO.Directory.Exists(serverFolder))
{
System.IO.Directory.CreateDirectory(serverFolder);
}
servr_path = serverFolder + fileName;
foreach (int i in ddlservices.GetSelectedIndices())
{
serviceId += "," + ddlservices.Items[i].Value;
}
IdProofFile.SaveAs(servr_path);
}
}
else
{
}
}
else
{
}
}
else
{
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
mpepopup.Show();
lblMsg.Text = "Min File Size Must Be Greater Than 5 KB and Less Than 2 MB";
}
}
else
{
mpepopup.Show();
// ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "mask();", true);
lblMsg.Visible = true;
lblMsg.Text = "Please upload an image of *.jpg/*.jpeg/*.png/*.gif/*.bmp file type only!!!";
}
}
else
{
mpepopup.Show();
lblMsg.Text = "ID Proof File Not Selected.";
}

Application_Error not working in production server

Application_Error was not firing on production server. but its working in our local server and other amazon server. in our local server have windows7 OS and IIS (7.5)version, but the production server have Windows8 and IIS (8+) version. any one have any idea.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError().GetBaseException();
string cls = ex.TargetSite.DeclaringType.Name;
string mtd = ex.TargetSite.Name;
string ErrorMessage = ex.Message;
string page = Request.Path;
string url = Request.PhysicalPath;
string StackTrace = "";
string inputdata = "";
if (ErrorMessage != "File does not exist.")
{
StackTrace = ex.StackTrace;
foreach (string i in Session.Contents)
{
if (Session[i] != null)
{
if (inputdata != "")
{
inputdata = inputdata + " , [" + i + "] = " + Session[i].ToString();
}
else
{
inputdata = "[" + i + "] = " + Session[i].ToString();
}
}
}
string flg = objBus.insertException(page, "", ErrorMessage, StackTrace, "", url, Session["UserID"].ToString(), inputdata,"");
//string flg = "0";
//Response.Redirect("~/ErrorPage.aspx?errorId=" + flg, false);
Server.Transfer("~/ErrorPage.aspx?errorId=" + flg, false);
}
}
When you publish try to enable "Precompile during publish", this should include PrecompiledApp.config in publish folder

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

How to set the directory permission in .NET 3.5?

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.

Resources