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

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

Related

download a SQL back up file in asp.net

I am trying to download sql back up file but getting error :
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack" near respone.end()
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
string backupDestination = backupPath;
string dbNAme = dbName;
string dateStamp = DateTime.Now.ToString("yy-MM-dd#HHmm");
string backupfile = backupDestination + '\\' + dbNAme + " of " + dateStamp + ".bak";
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + dbNAme + " of " + dateStamp + ".Bak'");
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("content-disposition", "attachment; filename= " + dbNAme + ".bak");
byte[] data = req.DownloadData(backupfile);
response.ContentType = "application/sql";
response.BinaryWrite(data);
response.End();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscipt", "swal('Error!','Database Backup Failed." + ex.ToString() + "','warning')", true);
}
}
One issue that I see is the buffer - change the response.Buffer = true; to false
response.Buffer = false;
for big files this is wrong because its put it on a buffer but you want to send it direct to the user...
also remove the catch (Exception ex) to see other problems on your code - the ScriptManager.RegisterStartupScript is not run from the moment you have change the headers. So the issue is hidden from you.
One other better and more correct way is to create a handler and download the file from there.
If the backup file is present on the server running the application, you shouldn't be using a WebClient. Something that reads the file from local disk, e.g. TransmitFile(), would then be sufficient - like this:
string backupDestination = backupPath;
string dbNAme = dbName;
string dateStamp = DateTime.Now.ToString("yy-MM-dd#HHmm");
string backupfile = backupDestination + '\\' + dbNAme + " of " + dateStamp + ".bak";
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + dbNAme + " of " + dateStamp + ".Bak'");
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("content-disposition", "attachment; filename= " + dbNAme + ".bak");
response.ContentType = "application/octet-stream";
response.TransmitFile(backupfile);
response.Flush();
ok so after 72 hours i have found the error. the download button was inside update panel so i was getting "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack"
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
string dbNAme = dbName;
string backupDestination = Server.MapPath("~/BackUp");
string dateStamp = DateTime.Now.ToString("yyyy-MM-dd#HH_mm");
string fileName = dbName + " of " + dateStamp + ".Bak";
if (!Directory.Exists(backupDestination))
{
Directory.CreateDirectory(backupDestination);
}
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + fileName + "'");
byte[] bytes = File.ReadAllBytes(Path.Combine(backupDestination, fileName));
// Delete .bak file from server folder.
if (Directory.Exists(backupDestination))
{
Directory.Delete(backupDestination, true);
}
Response.Clear();
Response.Buffer = false;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch(Exception ex)
{
string exception = ex.ToString();
}
}

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

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.

Insert SQL (Access) not working using webmethods Asp.net

I am trying to insert some fields into the local ms access database using webmethod(services) and website. I have tried looking up but cannot seem to spot where I've gone wrong. Can anyone tell me if I am doing it right. The code below does not add new data into the database nor does it direct me back to the page requested.
Services Webmethod:
[WebMethod]
public void AddNewPosts(string postUserName, string postTitle, DateTime postMessagepostDateTime, int subTopicId, string postMessage)
{
//Connection string for the datbase
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Forum.accdb;Persist Security Info=True";
OleDbConnection myConn = new OleDbConnection(database);
//Execute the query
string queryStr = "Insert into Posts (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "'," + postMessagepostDateTime + ")";
// Create a command object
OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
// Open the connection
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
Calling the above method from my website:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//string postUserName = Page.User.Identity.Name;
string postUserName = "tom123";
string postTitle = txtTitle.Text;
string postMessage = txtMessage.Text;
DateTime postDateTime = DateTime.Now;
int subTopicId = int.Parse(Request.QueryString["id"]);
Service fs = new Service();
fs.AddNewPosts(postUserName, postTitle, postDateTime, subTopicId, postMessage);
//Redirect back to the SubTopic page
Response.Redirect("SubTopic.aspx?id=" + subTopicId.ToString());
}
Can you try with quotes around the date time
string queryStr = "Insert into Posts (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "','" + postMessagepostDateTime + "')";

Resources