Delete specific files in directory - c#

I'm uploading PDF files into a folder using FileUpload control in this way:
string pdfFilPath = Path.GetFileName(FileUpload1.PostedFile.FileName.ToString());
string pdfPath = Server.MapPath(#"~/PDF/" + pdfFilPath);
FileUploadFoto.PostedFile.SaveAs(pdfPath);
But at the same time I'm inserting an Id, Description and PDFUrl in the database for this file:
SqlCommand cmd = new SqlCommand("INSERT INTO Book(Description, PDFUrl)
VALUES (''' + textBoxDescription.Text + "','" + "~/PDF/" + pdfFilPath + "')", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
If I select all columns from the database and show them on a GridView, they appear as follows:
ID Description PDFUrl
1 In this book... ~/PDF/jQuery in Action.pdf
Now, if I want to delete a book review, all I do is ("DELETE FROM Book Where Id='" + textBoxId.Text + "'", conn);, but this will delete only the Id,Description and the PDFUrl from the database.
My question is: How can I delete the PDF file at the same time when I delete the review from the database?

Don't forget though, you should check to see if the file exists before you delete it or else it will throw an error. This can happen if the user refreshes the postback.
if (File.Exists(Server.MapPath(PDFUrl))
{
File.Delete(Server.MapPath(PdfUrl));
}

If all you have is the ID, then first fun a query to get the PDFUrl from the DB based on the ID.
Then:
FileInfo fi = new FileInfo(Server.MapPath(PDFUrl));
fi.Delete;
Source: MSDN
Also, you should really use parameterized queries for reasons explained on the OWASP SQL Injection Prevention Cheat Sheet.

You can just create a method which delete the file from the directory, after that you delete the file from the database.
public void DeleteFile(string id)
{
FileInfo fi = new FileInfo(Server.MapPath(PDFUrl));
fi.Delete;
SqlComand cmd = new SqlComand("DELETE FROM Book Where Id='" + textBoxId.Text + "'", conn);
cmd.ExecuteNonQuery();
}

Related

C# Logging in system only works with first value of database

I'm a beginner to C# so help would be much appreciated. I'm attempting to code a logging in system but I can only successfully log in with the first line of data (username=admin , password=admin). I can't seem to log in from other data in the database (username=bryan , password=123). This is the code.
searchOLEDB.CommandText = "SELECT * FROM LOGIN where Username='" + LoginIDTextBox.Text + "' AND Password='" + LoginPasswordTextBox.Text + "'";
searchOLEDB.Connection = cnnOLEDB;
OleDbDataReader dr = searchOLEDB.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Logged In");
}
else
{
MessageBox.Show("Invalid Password");
}
dr.Close();
First, you should never concatenate sql query like you did. This will allow SQL Injection. You should use parameters.
See this post for examples :
using parameters inserting data into access database
P.S. I would also recommend to not store password in clear into your database.

Querying OLAP Cubes via ASHX Service

I'm using the following code to execute a query in C#:
// Create Connection String
AdomdConnection testConnection = new AdomdConnection("Data Source=*****;User ID=******;Provider=MSOLAP.6;Persist Security Info=True;Impersonation Level=Impersonate;Password=******");
// Test Open
testConnection.Open();
// Make Query
AdomdCommand cmd = new AdomdCommand(#"SELECT { [Measures].[Payment Amount] } ON COLUMNS,
{ [Charging Low Orgs].[Charging Division].[Charging Division] } ON ROWS
FROM [Payments]", testConnection);
AdomdDataReader dataReader = cmd.ExecuteReader();
// Close Connection
testConnection.Close();
And I keep getting this error on the cmd.ExecuteReader() call:
{"XML for Analysis parser: The CurrentCatalog XML/A property was not specified."}
The only literature that I could find that was relavent to this was that the query isn't resolving because impersonation wasn't set, but I specified that in the connection string.
Another article which I don't think is related, said to enable BAM on Excel, but I don't have that option in Excel, and I fail to see how that would make a difference for a web service.
Please help!
The following example includes a catalog parameter in the connection string:
static void Main(string[] args)
{
AdomdConnection conn = new AdomdConnection(
"Data Source=localhost;Catalog=Adventure Works DW Standard Edition");
conn.Open( );
string commandText = "SELECT {[Measures].[Sales Amount], " +
"[Measures].[Gross Profit Margin]} ON COLUMNS, " +
"{[Product].[Product Model Categories].[Category]} ON ROWS " +
"FROM [Adventure Works] " +
"WHERE ([Sales Territory Country].[United States])";
AdomdCommand cmd = new AdomdCommand(commandText, conn);
AdomdDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

Error when using insert in access: Could not Update; currently locked

I have a WebService that updates my access table from some terminals (10).
When I try to update I get this error from the error log:
Could not Update; Currently locked
Some terminals succeed and some do not.
I update like this:
using (Conn = new OleDbConnection(Work_Connect))
{
Conn.Open();
foreach (DataRow R in ds.Tables["MyCount"].Rows)
{
U_ID = ID;
U_Bar = R["Bar"].ToString().Trim();
U_Qty = R["Qty"].ToString().Trim();
U_Des = R["Des"].ToString().Trim();
SQL = "INSERT INTO MyTbl(ID,Bar,Qty,Des)VALUES('";
SQL += Convert.ToInt32(ID) + "','" + U_Bar + "','" + Convert.ToDouble(U_Qty) + "','" + U_Des + "')";
OleDbCommand Cmd2 = new OleDbCommand(SQL, Conn);
Cmd2.CommandText = SQL;
Cmd2.ExecuteNonQuery();
}
}
GC.Collect();
return true;
MsAccess has serious drawbacks for multi-user update. The Jet engine is not a database server, and will manage concurrence based on file system locking. If your problem is with a web service, I'd move the update to the server part, and implement queuing of simultaneous requests there. Thus, only the server, one process, will have access to the Access data. The other option is to use a real database server that will do that work for you. SQL Server Express is the usual option because it's easy to integrate, it's free as in beer, and is solid.
Also, if your problem happens always from the same terminals, that is, some terminals can never update anything, check the file access rights of these terminals' users to the database file, the lock file, and the database and lock file directory. Write rights are required for all of them.
Suggestions:
Convert your query to a parameterized query to avoid any potential strangeness with quoting. (You are converting text to numbers and then enclosing them in single-quotes in the SQL statement. That makes no sense.)
Don't force garbage collection on each call. According to the MSDN article here: "It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues."
Try something like this instead:
using (Conn = new OleDbConnection(Work_Connect))
{
Conn.Open();
foreach (DataRow R in ds.Tables["MyCount"].Rows)
{
U_ID = ID;
U_Bar = R["Bar"].ToString().Trim();
U_Qty = R["Qty"].ToString().Trim();
U_Des = R["Des"].ToString().Trim();
SQL = "INSERT INTO MyTbl (ID,Bar,Qty,Des) VALUES (?,?,?,?)";
using(OleDbCommand Cmd2 = new OleDbCommand(SQL, Conn))
{
// Cmd2.CommandText = SQL; redundant, the 'new' set the .CommandText
Cmd2.Parameters.AddWithValue("?", Convert.ToInt32(ID));
Cmd2.Parameters.AddWithValue("?", U_Bar);
Cmd2.Parameters.AddWithValue("?", Convert.ToDouble(U_Qty));
Cmd2.Parameters.AddWithValue("?", U_Des);
Cmd2.ExecuteNonQuery();
}
}
Conn.Close();
}
// GC.Collect(); // disabled for test purposes
return true;

using Service Based Database in VS2010 Ultimate

I have been working on a project related to database (.mdf). I have created some windows forms in visual studio using C#. Basically these forms work together to store, update and delete data from the Service Based Database i created.
The problem is when i build the project, it builds fine, no errors. It inserts a data provided from textboxes to the datagridview too as intended. But as soon as i stop the current debugging, and then rerun it again, all the data provided previously is lost from the datagridview!!
I cant understand why this is happening. anyone please help me. Im totally new to this stuff.. a bit of guidance would be heartily appreciated.
when i had previously used MySQL for the same purpose, the updated data would be permanently stored to the database, but since i migrated from the MySQL to SQL Server's Service Based Database, i get such confusing error.
......
void loadData()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT SNo,Customer_ID, Citizenship_No, Name, Subscription_Date, Phone_No, Location,Locality,Bulbs,Deposit,Monthly_Charge FROM customerinformation;", con);
try
{
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewCustomerInformation.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
try
{
float m_chrg = Convert.ToInt64(textBoxBulbs.Text)*500;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO customerinformation(SNo,Customer_ID,Citizenship_No,Name,Subscription_Date,Location,Locality,Bulbs,Deposit,Phone_No,Monthly_Charge) values('" + textBoxSNo.Text + "','" + textBoxCustomerID.Text + "','" + textBoxCitizenshipNumber.Text + "','" + textBoxName.Text + "','" + textBoxSubscriptionDate.Text + "','" + textBoxLocation.Text + "','" + textBoxLocality.Text + "','" + textBoxBulbs.Text + "','" + textBoxDeposit.Text + "','" + textBoxPhoneNumber.Text + "','" + m_chrg + "')", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
con.Close();
dataGridViewCustomerInformation.DataSource = dt;
loadData();
MessageBox.Show("Entry Added!");
fillListbox();
textBoxSNo.Clear();
textBoxBulbs.Clear();
textBoxCitizenshipNumber.Clear();
textBoxCustomerID.Clear();
textBoxDeposit.Clear();
textBoxLocality.Clear();
textBoxLocation.Clear();
textBoxPhoneNumber.Clear();
textBoxName.Clear();
textBoxSubscriptionDate.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If you have your MDF listed in your project files then the property Copy To Output Directory handles how your MDF file is copied to the output directory (BIN\DEBUG or BIN\RELEASE).
If this property is set to Copy Always, then when you run your program a fresh copy of your database file is copied from the project folder to the output effectively destroying every data that you have inserted, modified, deleted in the previous run of your program.
The best solution to this dilemma is to add the MDF file as a permanent database inside your current install of Sql Server and adjust your connection string. And of course set the property to Copy Never
In alternative you could set to Copy if newer. This will allow to change the database schema inside the Server Explorer and let the Visual Studio IDE copy the new structure only after you have made changes.
UPDATE BUT IMPORTANT Not related to your actual question, but your insert query is a serious problem. Do not use string concatenation to build a sql command text. Particularly if the partial text comes from user input. You could face syntax errors (if someone places a single quote inside a text box) or worst, a Sql Injection problem (see here for a funny explanation)
To find good examples of Insert search for 'parametrized query'

failed to copy database as backup file

Description:
I am trying to copy my sql database as backup file, once I login, and redirect to backup.aspx and I clicked backup button, it prompt me an error output
If I open directly backup.aspx I can copy the database without any error
I knew that the problem is my database is connect after I login, so it tell me it is being used by another process
What I want to ask is that anyway can solved this problem ?
I aim to disconnect from db on page load but I cant make it, it still prompt me the same error
Error message:
The process cannot access the file 'C:\Users\Roy\Desktop\backup
fyp\10-18-2011\WebSite5\App_Data\Database.mdf' because it is being
used by another process.
Code for button click:
string time1 = DateTime.Now.ToString("dd-MM-yyyy hh-mmtt");
Directory.CreateDirectory(#"C:/SME-Online/" + time1);
string destination = #"C:/SME-Online/" + time1;
string source = Server.MapPath(#"~/App_Data");
File.Copy(Path.Combine(source, "Database.mdf"), Path.Combine(destination, "Database.mdf"), true);
File.Copy(Path.Combine(source, "Database_log.LDF"), Path.Combine(destination, "Database_log.LDF"), true);
You should backup database first and then copy *.bak file as backup, here some code to get you started, of course you can alter that query or filename generation code to suit it to your needs, be sure to check Backup T-SQL statement help.
public void BackupDatabase()
{
/// this method should get opened connection
SqlConnection conn = GetOpenedDBConnectionFromSomewhere();
string dbName = conn.Database;
string backupFName = "c:\\MSSQLData\\Backup\\" + dbName + "_" + DateTime.Now.Ticks.ToString() + ".bak";
string sql = "BACKUP DATABASE [" + conn.Database + "] TO DISK = '" + backupFName + "'" +
"WITH NOFORMAT, INIT, NAME = 'Backup of DB:" + dbName + "', SKIP, NOREWIND, NOUNLOAD, STATS = 10;";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
}

Categories