My application successfully creates a new database utilising the following string:
SqlString = $"CREATE DATABASE {_databaseName} ON PRIMARY " +
$"(NAME = {_databaseName}_Data, " +
$"FILENAME = '{_filePath}', " +
"SIZE = 8192KB, MAXSIZE = UNLIMITED, FILEGROWTH = 10%) " +
$"LOG ON (NAME = {_databaseName}_Log, " +
$"FILENAME = '{_databasePathLdf}', " +
"SIZE = 8192KB, " +
"MAXSIZE = UNLIMITED, " +
"FILEGROWTH = 10%)";
ExecuteSqlQuery(#"server=.\SQLEXPRESS; Trusted_Connection = Yes", SqlString);
When I then try to reconnect to the database use the following connection string
internal string ConnectionString(String databaseName)
{
return $"Server =.\\SQLEXPRESS;Database={databaseName};Trusted_Connection=Yes;";
}
I get the following error
For clarity the connection strings both use Trusted_Connection = Yes and the owner and login are the same when creating and connecting to the database.
For further clarity I am utilising OpenFileDialog to navigate to the database to connect utilising the following:
internal string OpenFileDialog(String initialDirectory)
{
string filePath = "";
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = initialDirectory;
openFileDialog.Filter = "mdf Database file (*.mdf)|*.mdf";
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
}
}
return filePath;
}
The error occurs on the DialogResult.OK.
How can you utilise OpenFileDialog in this instance to return the file path of the database to connect to?
I am using SQL Server Express 2019 (v15.0.2070).
Thanks in advance for any assistance.
Related
I have an error with database file path, the project has many databases with 10 tables, for each file should have 1 database, I create a database but it can't be saved as file ... and the error is:
The File Path Is Not Supported ...
public class filewrite
{
public string datadress, dataname, databaseadress, tablexist, dsname, databak, dataldf, databakldf, filepath, filename;
public filewrite()
{
databaseadress = "baseadress";
dataname = "name";
datadress = "adress";
dsname = "databasename1";
databak = "backUp";
tablexist = "yesorno";
dataldf = "dl";
databakldf = "dbl";
filepath = "path";
filename = "name";
}
public byte writing()
{
if (File.Exists(filepath + #"\" + filename + #"\Data" + datadress))
File.Delete(filepath + #"\" + filename + #"\Data" + datadress);
if (File.Exists(#"C:\tempFile.SMP"))
File.Delete(#"C:\tempFile.SMP");
string path = filepath + #"\" + filename + #"\Data" + datadress;
FileStream fpath = File.Create(path);(The error is in here)
try
{
// read from file or write to file
StreamWriter fwrite = new StreamWriter(fpath);
fwrite.WriteLine(datadress);
fwrite.WriteLine(dataname);
fwrite.WriteLine(databaseadress);
fwrite.WriteLine(tablexist);
fwrite.WriteLine(dsname);
fwrite.WriteLine(databak);
fwrite.WriteLine(dataldf);
fwrite.WriteLine(databakldf);
fwrite.Close();
}
finally
{
}
File.Copy(filepath + #"\" + filename + #"\Data" + datadress, #"C:\tempFile.SMP");
return 10;
}
}
Rather than using filepath + #"\" + filename + #"\Data" + datadress;,
Try using System.IO.Path.Combine instead:
Path.Combine(filepath, fileName, Data, datadress);
which returns a string.
i am working on a API Project which require a functionality to upload a file. When i run the project on localhost and trying to upload a file it works perfectly, but when i publish the project and deploy it on IIS the upload functionality it's not working and produce 500 Internal Server Error.
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UserFilesController : ControllerBase
{
private IConfiguration configuration;
public UserFilesController(IConfiguration iConfig)
{
configuration = iConfig;
}
[HttpPost]
public async Task<IActionResult> PostFormData([FromForm]IFormFile file)
{
var dict = new Dictionary<string, string>();
HttpContext.User.Claims.ToList()
.ForEach(item => dict.Add(item.Type, item.Value));
string userid = dict.ElementAt(2).Value;
FileConverter fileConverter = new FileConverter();
if (file == null || file.Length == 0)
return Content("file not selected");
var path = Path.Combine(
Directory.GetCurrentDirectory(), "File",
file.FileName);
string ext = Path.GetExtension(file.FileName);
string newFileName = Guid.NewGuid().ToString();
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "File", newFileName+ext);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
fileConverter.ConvertToPdf(filePath, newFileName);
var pdfPath = Path.Combine(
Directory.GetCurrentDirectory(), "File",
newFileName+".pdf");
DateTime ExpiredOn = DateTime.Now.AddDays(1);
DateTime CreatedOn = DateTime.Now;
string fileUrl = "/File/" + newFileName + ext;
string pdfUrl = "/File/" + newFileName + ".pdf";
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
string createdon = CreatedOn.ToString("yyyy-MM-dd HH:mm:ss").Replace(".", ":");
string expiredon = ExpiredOn.ToString("yyyy-MM-dd HH:mm:ss").Replace(".", ":");
var value = connection.Execute(
"INSERT INTO uf (ufid, name, oriformat, fileurl, pdfurl, createdon, expiredon, isdeleted, systemuserid) VALUES (uuid_generate_v4(), '" + file.FileName + "', '" + ext.Replace(".","") + "', '" + fileUrl + "', '" + pdfUrl + "', '" + createdon + "', '" + expiredon + "', false, '" +userid+ "');"
);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
TableUserFileBaru result = new TableUserFileBaru();
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
var value = connection.Query<TableUserFileBaru>(
"select * from uf where systemuserid = '"+userid+"' order by createdon desc;"
);
result = value.First();
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
string ori_format = result.oriformat.ToString().Replace(".", "");
PostUserFileResp resp = new PostUserFileResp();
resp.UFId = result.ufid.ToString();
resp.Name = result.name;
resp.OriFormat = ori_format;
resp.FileURL = result.fileurl;
resp.PdfURL = result.pdfurl;
resp.CreatedOn = result.createdon;
resp.ExpiredOn = result.expiredon;
resp.SystemUserId = result.systemuserid;
resp.IsDeleted = result.isdeleted;
return Ok(resp);
}
}
UPDATE :
After i followed ArunPratap's step to show the error detail i got this following message.
An unhandled exception occurred while processing the request.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\NetCore\File\7ebb3a76-f194-41f2-8a4b-a576308856aa.pdf' is denied. System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
After i
Did anyone know how to solve it?
Thanks.
You can create a System Environment variable named ASPNET_ENV and set its value to Development and call the UseDeveloperExceptionPage() method. that will show the details of the error and after that, you can fix that
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Update
As now you are getting request.UnauthorizedAccessException: Access to the path denied Try to go to App_Data folder property and add ASPNET user with reading and write privileges
Look for instruction
I followed a quick guide to get a SQL Server database backed up from .Net (http://www.bidn.com/blogs/ShawnHarrison/ssis/2134/access-denied-during-database-backup). In short, updated SQL Service (Service) > Properties > Log On tab > Built-in account to Local Service.
I was wondering how I could avoid changing through Windows directly and specify some type of authentication in my code? Say I don't have access to the Service (via RDP, etc).
My code is as follows:
public void BackupDatabase()
{
try
{
Backup sqlBackup = new Backup
{
Action = BackupActionType.Database,
BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString(),
BackupSetName = "Archive"
};
ServerConnection connection = new ServerConnection
{
ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
};
DatabaseName = (new SqlConnectionStringBuilder(connection.ConnectionString)).InitialCatalog;
FileName = DatabaseName + "_" + DateTime.Now.ToString("yyyyMMdd-hhmmss") + ".bak";
AbsolutePath = DestinationPath + FileName;
BackupDeviceItem deviceItem = new BackupDeviceItem(AbsolutePath, DeviceType.File);
sqlBackup.Database = DatabaseName;
Server sqlServer = new Server(connection);
Microsoft.SqlServer.Management.Smo.Database db = sqlServer.Databases[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);
Success = true;
Result = string.Format("<i>{0}</i> was successfully backed up to the following location: <i>{1}</i>", FileName, DestinationPath);
}
catch (Exception ex)
{
ExceptionLogHelper.AddExceptionLog("Helper.DatabaseHelper.BackupDatabase", ex.Message.ToString(), ex.StackTrace.ToString());
Success = false;
Result = string.Format("{0}, {1}", ex.Message.ToString(), ex.InnerException.InnerException.Message.ToString());
}
}
The code below is supposed to rename a file with numbers if another file with the same name already exists. For example, test.docx, test(2).docx, etc... It works just fine on my localhost, but when I put it on the web server it changes the file name to test.docx(2). Any help would be greatly appreciated. Here's what I'm currently using:
protected void btn_submit_new_doc_vsn_Click(object sender, EventArgs e)
{
int i = 0;
string filename = fu_new_doc_vsn.FileName;
if (fu_new_doc_vsn.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_new_doc_vsn.FileName + " (" + i.ToString() + ")";
}
fu_new_doc_vsn.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
doc_path_text.Text = (Server.MapPath("~/Data/") + filename);
SqlConnection idrf_cnxn = new SqlConnection("Data Source=SRVER\\MYDB;Initial Catalog=idrf;Integrated Security=True");
{
SqlCommand new_doc_cmd = new SqlCommand("Insert Into tbl_doc(doc_title, doc_type_list, doc_org_list, doc_dept_list, doc_desc, prior_contract_cd, legal_comp_contract_id, doc_upld_dt, doc_path, crnt_doc_stat_list, vendor_id_fk) Values(LTRIM(RTRIM(#doc_title)), LTRIM(RTRIM(#doc_type_list)), LTRIM(RTRIM(#doc_org_list)), LTRIM(RTRIM(#doc_dept_list)), LTRIM(RTRIM(#doc_desc)), LTRIM(RTRIM(#prior_contract_cd)), LTRIM(RTRIM(#legal_comp_contract_id)), LTRIM(RTRIM(#doc_upld_dt)), LTRIM(RTRIM(#doc_path)), LTRIM(RTRIM(#crnt_doc_stat_list)), LTRIM(RTRIM(#vendor_id_fk)))", idrf_cnxn);
new_doc_cmd.Parameters.AddWithValue("#doc_title", doc_title_text.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_type_list", doc_type_text.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_org_list", doc_org_list_text.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_dept_list", doc_dept_list_text.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_desc", doc_desc_text.Text);
new_doc_cmd.Parameters.AddWithValue("#prior_contract_cd", prior_contract_cd_text.Text);
new_doc_cmd.Parameters.AddWithValue("#legal_comp_contract_id", legal_comp_contract_id_text.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_upld_dt", doc_upld_dt_text.Text);
new_doc_cmd.Parameters.AddWithValue("#doc_path", doc_path_text.Text);
new_doc_cmd.Parameters.AddWithValue("#crnt_doc_stat_list", crnt_doc_stat_list_text.Text);
new_doc_cmd.Parameters.AddWithValue("#vendor_id_fk", vendor_id_fk_text.Text);
idrf_cnxn.Open();
new_doc_cmd.ExecuteNonQuery();
idrf_cnxn.Close();
if (IsPostBack)
{
Response.Redirect("~/Default.aspx");
}
}
}
Any help would be greatly appreciated.
I'm using VS2013, framework is 4.5.1, this is an asp.net web forms application.
Thanks,
J
So it should be somthing like this, if you read my prior comment:
int i = 0;
string filename = fu_new_doc_vsn.FileName;
if (fu_new_doc_vsn.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = fu_new_doc_vsn.Name + " (" + i.ToString() + ")" + Path.GetFileNameWithoutExtension(fu_new_doc_vsn.FileName);
}
fu_new_doc_vsn.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
Here's the code...
int i = 0;
string filename = fu_new_doc_vsn.FileName;
string fnnnoext = System.IO.Path.GetFileNameWithoutExtension(fu_new_doc_vsn.FileName);
string fnnextonly = System.IO.Path.GetExtension(fu_new_doc_vsn.FileName);
if (fu_new_doc_vsn.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = (fnnnoext + "(" + i.ToString() + ")" + fnnextonly);
}
fu_new_doc_vsn.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
}
hdn_doc_path_text.Value = (Server.MapPath("~/Data/") + filename);
Suppose I have this method from one class:
private void btnChangeImage_Click(object sender, EventArgs e)
{
using (var openFileDialogForImgUser = new OpenFileDialog())
{
string location = null;
string fileName = null;
openFileDialogForImgUser.Filter = "Image Files (*.jpg, *.png, *.gif, *.bmp)|*.jpg; *.png; *.gif; *.bmp|All Files (*.*)|*.*"; // filtering only picture file types
var openFileResult = openFileDialogForImgUser.ShowDialog(); // show the file open dialog box
if (openFileResult == DialogResult.OK)
{
using (var formSaveImg = new FormSave())
{
var saveResult = formSaveImg.ShowDialog();
if (saveResult == DialogResult.Yes)
{
imgUser.Image = new Bitmap(openFileDialogForImgUser.FileName); //showing the image opened in the picturebox
location = openFileDialogForImgUser.FileName;
fileName = openFileDialogForImgUser.SafeFileName;
FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read); //Creating a filestream to open the image file
int fileLength = (int)fs.Length; // getting the length of the file in bytes
byte[] rawdata = new byte[fileLength]; // creating an array to store the image as bytes
fs.Read(rawdata, 0, (int)fileLength); // using the filestream and converting the image to bits and storing it in an array
MySQLOperations MySQLOperationsObj = new MySQLOperations("localhost", "root", "myPass");
MySQLOperationsObj.saveImage(rawdata);
fs.Close();
}
else
openFileDialogForImgUser.Dispose();
}
}
}
}
And this method from another class (MySQLOperations):
public void saveImage(byte[] rawdata)
{
try
{
string myConnectionString = "Data Source = " + server + "; User = " + user + "; Port = 3306; Password = " + password + ";";
MySqlConnection myConnection = new MySqlConnection(myConnectionString);
string currentUser = FormLogin.userID;
string useDataBaseCommand = "USE " + dbName + ";";
string updateTableCommand = "UPDATE tblUsers SET UserImage = #file WHERE Username = \'" + currentUser + "\';";
MySqlCommand myCommand = new MySqlCommand(useDataBaseCommand + updateTableCommand, myConnection);
myCommand.Parameters.AddWithValue("#file", rawdata);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
If I must, this is my constructor for the MySQLOperations class:
public MySQLOperations(string server, string user, string password)
{
this.server = server;
this.user = user;
this.password = password;
}
What I'm trying to do is save an image file (which the user selects through the open file dialog box) to the database. Problem is I get this error: "You have an error in your SQL syntax; check the manual that correponds to your MySQL server version for the right syntax to use near ';UPDATE tblUsers SET UserImage = _binary'?PNG ... (and so on with some random characters). So, I can't really save the file in the database. I would love to post a picture on how the error is seen at the MessageBox, but I guess my account is not given the privilege to do so yet.
I'm not really sure where the syntax error is in that. I'm thinking, it's in the #file - but that's just a guess. Your help would be very much appreciated.
And oh, the table column UserImage has a type of LONGBLOB.
Other things I'm interested to know about also:
Is it necessary that I add another column for my table to store the
size of the file (because I'm going to need to retrieve the file
to display the image later on)?
Is it okay that I used the using statement that way in the method
btnChangeImage_Click?
Thank you very much.
EDIT: Got the problem solved. Such a simple thing not given attention to. Thanks to everybody who tried to help. I'm still willing to hear your opinion on the questions at the bottom (those on bullets).
I think the problem is in the following line of code:
WHERE Username = \'" + currentUser + "\';"
It should change to the following one:
WHERE Username = " + currentUser;
Or better (to avoid sql injections) to the following one:
WHERE Username = #Username";
myCommand.Parameters.AddWithValue("#Username", currentUser);
Do not store binary files in a MySQL table. Instead, save it to disk and save path to PNG file to MySQL database. Also, use Christos advice to avoid SQL injections.