How to upload a DB backup to a FTP server - c#

On the tail end of database backup project and I've run into a issue where the Deflate compression I put in can't seem to find the path I saved the backup to. Being that the default backup location (used here) is on a network drive is there something else I need to do to make sure the path is found by Deflate? As of now I get System.IO.DirectoryNotFoundException: 'Could not find a part of the path. The purpose of the tool is to be able to put in any server you want to access, get a list of available DB's and then choose the one you want to backup.
I had this issue before locally, but all i had to do was give SQLserver the proper permissions to the folder.
using (SqlConnection newConn = new SqlConnection(connString))
using (SqlCommand sqlCmd = new SqlCommand(query, newConn))
{
newConn.Open();
value = sqlCmd.ExecuteScalar();
canCompress = !(value == null || Convert.ToInt32(value) == 0);
//----------------------------------
//SQL Commands to run backup process
//----------------------------------
Interface.WriteLine("Creating backup");
if (canCompress)
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, COMPRESSION, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
else
{
sqlCmd.CommandText = "BACKUP DATABASE [" + connBuilder.InitialCatalog + "] "
+ "TO DISK = '" + backupFile + "' "
+ "WITH COPY_ONLY, NOFORMAT, NOINIT, "
+ "NAME = '" + backupName + "', "
+ "SKIP, REWIND, NOUNLOAD, STATS = 10";
sqlCmd.ExecuteNonQuery();
}
//----------------------------------
//Grab Backup File
//----------------------------------
query = "SELECT physical_device_name "
+ "FROM msdb.dbo.backupset b "
+ "JOIN msdb.dbo.backupmediafamily m ON b.media_set_id = m.media_set_id "
+ "WHERE database_name = '" + connBuilder.InitialCatalog + "' "
+ "ORDER BY backup_finish_date DESC ";
using (SqlConnection connection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
value = cmd.ExecuteScalar();
if (value != null)
backupFile = (string)value;
else
throw new Exception("Unable to find backup file.");
}
//Set which files should be uploaded.
if (canCompress)
{
fileToUpload = backupFile;
}
else
{
fileToUpload = Deflate.CompressFile(backupFile); //Point of error message
File.Delete(backupFile);
}
return fileToUpload;
}
static class Deflate
{
public static string CompressFile(string sourcePath, string destPath = null)
{
if (destPath == null)
destPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".cmp");
using (FileStream originalFileStream = File.OpenRead(sourcePath))
using (FileStream compressedFileStream = File.Create(destPath))
using (DeflateStream compressionStream = new
DeflateStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
compressedFileStream.Flush();
}
FileInfo sourceInfo = new FileInfo(sourcePath); //Remove the .bak extension on compression?
FileInfo destInfo = new FileInfo(destPath); //Remove the .bak extension on compression?
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", Path.GetFileName(sourcePath), sourcePath.Length, destInfo.Length);
return destPath;
}
}

Related

Updating a Image field in SQL server

I am trying to update mu existing image field in one of my table and I am getting error saying "A generic error occurred in GDI+". Please help.
private void Add_Records()
{
int i = check_for_null();
if (i == 1)
{
DateTime Nw = DateTime.Now;
int user = Form_Common_Login.user_id;
int ref_lc = 0;
ref_lc = Convert.ToInt16(cbo_emp_cat.SelectedValue);
try
{
string query = #"INSERT INTO tbl_Labour_Employee_Reg
(Ref_IDLC,First_Name,Last_Name,Emp_Image,Designation,NIC_No,Emp_Address,Previous_WorkPlaces,Phone_Number_Mobile,Phone_Number_Residential,Account_Number,Employee_Number,Remarks,Accessed_By,Accessed_Time,Is_Deleted,Is_Active)
VALUES ('" + ref_lc + "','" + txt_Fname.Text + "','" + txt_Lname.Text + "',#image_array,'" + txt_designation.Text + "','" + txt_nic.Text + "','" + txt_address.Text + "','" + txt_previous_wp.Text + "','" + txt_Mnumber.Text + "','" + txt_Lnumber.Text + "','" + txt_account_number.Text + "','" + txt_emp_number.Text + "','" + txt_remarks.Text + "','" + user + "','" + Nw + "',0,1)";
clz_Common_SqlConnection con = new clz_Common_SqlConnection();
SqlCommand cmd = new SqlCommand(query ,con.ActiveCon ());
MemoryStream ms = new MemoryStream ();
pic_box_employee.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] image_array = ms.ToArray();
cmd.Parameters.AddWithValue("#image_array", image_array);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else { MessageBox.Show("Please enter Valid Data"); }
}
my update code here
private void Update_Records()
{
int i = check_for_null();
if (i == 1)
{
DateTime Nw = DateTime.Now;
int user = Form_Common_Login.user_id;
int ref_lc = 0;
ref_lc = Convert.ToInt16(cbo_emp_cat.SelectedValue);
try
{
string update_query = "UPDATE tbl_Labour_Employee_Reg"+
"SET Ref_IDLC ='"+ref_lc+"',First_Name = ,'" + txt_Fname.Text + "',Last_Name='" + txt_Lname.Text + "',Emp_Image = #image_array,Designation = '" + txt_designation.Text + "',NIC_No='" + txt_nic.Text + "',Emp_Address = '" + txt_address.Text + "'"+
",Previous_WorkPlaces = '" + txt_previous_wp.Text + "', Phone_Number_Mobile = '" + txt_Mnumber.Text + "',Phone_Number_Residential='" + txt_Lnumber.Text + "', Account_Number= '" + txt_account_number.Text + "',Employee_Number='" + txt_emp_number.Text + "'"+
",Remarks='" + txt_remarks.Text + "',Accessed_By='" + user + "',Accessed_Time= '" + Nw + "',Is_Deleted=0,Is_Active=1";
clz_Common_SqlConnection con = new clz_Common_SqlConnection();
SqlCommand cmd = new SqlCommand(update_query, con.ActiveCon());
MemoryStream ms = new MemoryStream();
pic_box_employee.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] image_array = ms.ToArray();
cmd.Parameters.AddWithValue("#image_array", image_array);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else { MessageBox.Show("Please enter Valid Data"); }
}
Insert function is properly working but the update is not. I am really struck in here. If you have better way to insert & update a image field please explain.
First of all move your answer to your question. Its not an answer. Its just a new question.
try using the following, I personally update images as follows;
Image img = Image.FromFile(#"C:\Users\Awais\Desktop\image.png");
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
arr = ms.ToArray();
}
int dr = 0;
SqlConnection con = new SqlConnection("data source=.; initial catalog=database; uid=sa;pwd=password;");
SqlCommand cmd = new SqlCommand("update table set I1 = #img", con);
cmd.Parameters.AddWithValue("#img", arr);
con.Open();
using (con)
{
dr = cmd.ExecuteNonQuery();
}

How i can delete database from local server without database files

If database files .mdf and .log do not exist in folder with application then i need to create new database, but if i do like this
CREATE DATABASE Mydvds.mdf
And i have exception that databese Mydvds.mdf is alredy exist. If i try to drop database like this
DROP DATABASE Mydvds.mdf
I have exception that base is not exist or i don't have premmisions.
I was checking database list by way of
SELECT * FROM sysdatabases
And C:\Mydvds.mdf in this list.
How i can remove this database from server?
Or can you tell me about another way do this?
public void create_db()
{
string base_path = Environment.CurrentDirectory + #"..\..\..\My_cool_db.mdf";
string log_path = Environment.CurrentDirectory + #"..\..\..\My_cool_db_log.ldf";
string ConnectionString = #"Data Source=(LocalDB)\v11.0";
string cmnd_create_db;
connection = new SqlConnection(ConnectionString);
cmnd_create_db = "CREATE DATABASE My_cool_db ON PRIMARY " +
"(NAME = My_cool_db, " +
"FILENAME = '" + #base_path + "', " +
"SIZE = 4MB, MAXSIZE = 20MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = My_cool_db_log, " +
"FILENAME = '" + #log_path + "', " +
"SIZE = 4MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + #base_path + ";Integrated Security=True";
connection = new SqlConnection(ConnectionString);
cmnd = connection.CreateCommand();
cmnd.CommandText = cmnd_create_db;
connection.Open();
cmnd.ExecuteNonQuery();
List<string> db_cmnd = new List<string>();
db_cmnd.Add(File.ReadAllText(Environment.CurrentDirectory + "\\res\\Main.sql"));
db_cmnd.Add(File.ReadAllText(Environment.CurrentDirectory + "\\res\\Category_table.sql"));
db_cmnd.Add(File.ReadAllText(Environment.CurrentDirectory + "\\res\\ForeignKeyConstraint1.sql"));
foreach (string command_text in db_cmnd)
{
cmnd.CommandText = command_text;
cmnd.ExecuteNonQuery();
}
connection.Close();
connection.Dispose();
cmnd.Dispose();
}

How can i get the rotated image in file

as of now i can upload my image in the database the problem is when i rotate the image.
the uploaded image is not the rotated one, its still the image that i upload that i didnt rotate.
how can i upload the rotated image ?
Stream FileStream = File.OpenRead(ServerPath + Filename);
// Stream FileStream = FileUpload1.PostedFile.InputStream;
// System.Drawing.Image.FromFile(ServerPath + Filename);
//System.Drawing.Bitmap postedimage = new System.Drawing.Bitmap(FileStream);
objImage = ScaleImage(PostedImage, 73);
if (FileType != "jpg" && FileType != "JPG")
{
objImage.Save(ServerPath + jpgFileName, ImageFormat.Jpeg);
}
else
{
//objImage.Save(ServerPath + Filename);
}
img = new byte[FileStream.Length];
contentlength = FileStream.Length;
if (contentlength > 506000)
{
ClientScript.RegisterClientScriptBlock(typeof(Page), "ClosePopup", "File is to large! Maximum size is 8kb", true);
}
else if (contentlength <= 506000)
{
//ImageConverter converter = new ImageConverter();
//byte[] bytestr = (byte[])converter.ConvertTo(objImage, typeof(byte[]));
//fs.InputStream.Read(img, 0, fs.ContentLength);
byte[] bytestr = null;
var fsm = ToStream(objImage, ImageFormat.Jpeg);
//Stream fsm = ScaleImage(objImage, 73);
BinaryReader br = new BinaryReader(fsm);
bytestr = br.ReadBytes((int)fsm.Length);
SqlCommand cmd = new SqlCommand("Select * FROM tblphotoupload where mem_cardno = '" + sParameter + "'", connection);
SqlDataReader alinan_veri3;
alinan_veri3 = cmd.ExecuteReader();
if (alinan_veri3.Read())
{
int sct = 2;
int a = Convert.ToInt32(alinan_veri3["upload_count"]);
if (sct == 2)
{
if (a >= 2) a = 2;
sql = "update tblphotoupload set mem_photo" + Convert.ToString(a + 1) + " = #img, upload_date" + Convert.ToString(a + 1) + " = '" + sDateTime + "', mem_contenttype" + Convert.ToString(a + 1) + " = '" + FileType + "', mem_photofile" + Convert.ToString(a + 1) + " = '" + Filename + "', upload_count='" + (a + 1) + "' where mem_cardno = '" + sParameter + "'";
connection.Close();
SqlConnection connection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["EKConn"].ConnectionString);
connection2.Open();
SqlCommand cmd2 = new SqlCommand(sql, connection2);
cmd2.Parameters.Add(new SqlParameter("#img", bytestr));
cmd2.ExecuteNonQuery();
connection2.Close();
}
}
else
{
//string ole;
sql = "insert into tblphotoupload (mem_cardno, mem_photo1, upload_date1, upload_count, mem_contenttype1, mem_photofile1) values ('" + sParameter + "', #img, '" + sDateTime + "','1','" + FileType + "','" + Filename + "')";
connection.Close();
SqlConnection connection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["EKConn"].ConnectionString);
connection2.Open();
SqlCommand cmd2 = new SqlCommand(sql, connection2);
cmd2.Parameters.Add(new SqlParameter("#img", bytestr));
cmd2.ExecuteNonQuery();
connection2.Close();
}
}
}
First of all make sure that your file is saved on the disk and then save the file into DB.
If this will not help you probably will have to either:
rotate it properly, rotation might be saved only by the image viewer without changing the image on the disk, i have encountered the issue with Picassa
rotate it in the code (rotate bytes)

Backup SQL Server database by C# statement

I want to create a backup for the database I worked on my application by C# statement.
This is my code:
SqlConnection con = new SqlConnection(Connection.GetConnection());
SqlCommand command = new SqlCommand();
command.CommandText = "backup database [Pharmacy Database]to disk ="+"'"+path +"'";
command.CommandType = CommandType.Text;
command.Connection = con;
con.Open();
command.ExecuteNonQuery();
con.Close();
And gives me an error:
Cannot open backup device 'C:/Users/Abo Sala7/Desktop'.Operating system error 5 (failed to retrieve text for this error. Reason:15105).
BACKUP DATABASE is terminating abnormally.
Maybe the Problem is that your ServiceUser of the SQL-Service does not have the permission to write into the defined folder - The service is perfoming the backup - so this user must have the requiered permissions on the destination folder. (error 5 == Accessdenied)
I have been using the code below for back up, try this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// <summary>
/// Backups the data base.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public bool BackupDataBase(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return false;
bool isDatabackedUp = true;
try
{
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
BackupDeviceItem deviceItem = new BackupDeviceItem(fileName, DeviceType.File);
ServerConnection connection = new ServerConnection(this.BackupConnection);
DataConnection dataConnection = new DataConnection();
Server sqlServer = new Server(dataConnection.ServerName);
Database db = sqlServer.Databases[dataConnection.DataBaseName];
sqlBackup.Database = dataConnection.DataBaseName;
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
return isDatabackedUp;
}
catch (Exception)
{
return false;
}
}
private SqlConnection BackupConnection
{
get
{
string backupConnectionString = string.Empty;
ConnectionStringSettings settings =
ConfigurationManager.ConnectionStrings["LibrarySystemBackUpConnection"];
backupConnectionString = settings.ConnectionString;
SqlConnection backupDatabaseConnection = new SqlConnection(backupConnectionString);
return backupDatabaseConnection;
}
}
Here is a procedure is use for back up in C#.Hope it helps
public void BackupDatabase
(string BackUpLocation, string BackUpFileName, string DatabaseName, string ServerName )
{
DatabaseName = "[" + DatabaseName + "]";
string fileUNQ = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() +"_"+ DateTime.Now.Hour.ToString()+ DateTime.Now .Minute .ToString () + "_" + DateTime .Now .Second .ToString () ;
BackUpFileName = BackUpFileName + fileUNQ + ".bak";
string SQLBackUp = #"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + #"\" + BackUpFileName + #"'";
string svr = "Server=" + ServerName + ";Database=master;Integrated Security=True";
SqlConnection cnBk = new SqlConnection(svr);
SqlCommand cmdBkUp = new SqlCommand(SQLBackUp, cnBk);
try
{
cnBk.Open();
cmdBkUp.ExecuteNonQuery();
Label1.Text = "Done";
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label2.Text = SQLBackUp + " ######## Server name " + ServerName + " Database " + DatabaseName + " successfully backed up to " + BackUpLocation + #"\" + BackUpFileName + "\n Back Up Date : " + DateTime.Now.ToString();
}
finally
{
if (cnBk.State == ConnectionState.Open)
{
cnBk .Close();
}
}
}
internal void CreateDbBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = string.Format(#"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath);
con.Open();
cmd.ExecuteNonQuery();
}
}
internal void RestoreDbFromBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
con.Open();
// Make sure to get exclusive access to DB to avoid any errors
cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE";
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format(#"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath);
cmd.ExecuteNonQuery();
}
}

fileupload isnt creating folder if its not there

My fileupload isnt creating the path if its not there, its only working if the folder belonging to the user id is actually already in place, I need it to upload whether the folder is there or not.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
string filenameDB = Path.GetFileName(FileUpload1.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
Label2.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES (" + theUserId + ", '" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
OdbcCommand md = new OdbcCommand("UPDATE User SET flag = 0 WHERE UserId = '" + theUserId + "'", cn);
// OdbcCommand cmd = new OdbcCommand("UPDATE Pictures SET picturepath ='" + fileuploadpaths + "' WHERE UserId = '" + theUserId + "'", cn);
md.ExecuteNonQuery();
Response.Redirect("UserProfileWall.aspx");
}
catch (Exception ex)
{
Label2.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Why don't you simply check if the folder is already created, if it's not create it. if(System.IO.Directory.Exists("YourDirectoryPath")) do your stuff;
The command you want to utilize is
string fileuploadDir = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
if(!System.IO.Directory.Exists(fileuploadDir)
{
System.IO.Directory.CreateDirectory(fileuploadDir)
}
Insert this after:
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
Corrected based on comments below.
string dirPath= Path.GetDirectoryName(fileuploadpath);
if(!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}

Categories

Resources