file upload error, "not found on selected data source" - c#

I've written the following code and when it was simply uploading the file to the folder everything was fine. I've changed it to insert the file name and file path into a database and I'm getting an error:
A field or property with the name 'DataUpload' was not found on the selected data source
DataUpload is the folder name and worked fine before. I'm probably missing something simple but I'm not seeing it.
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
try
{
FileUpload1.SaveAs(Server.MapPath("DataUpload\\" + FileUpload1.FileName));
Guid newGUID = Guid.NewGuid();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string InsertUser = "INSERT INTO UserUpload (ID, Comment, FilePath, FileName) VALUES (#ID, #Comment, #FilePath, #FileName)";
SqlCommand com = new SqlCommand(InsertUser, conn);
com.Parameters.AddWithValue("#ID", newGUID.ToString());
com.Parameters.AddWithValue("#Comment", TextBoxComment.Text);
com.Parameters.AddWithValue("#FilePath", "DataUpload/" + FileName);
com.Parameters.AddWithValue("#FileName", FileName);
com.ExecuteNonQuery();
LabelMessage.Text = ("Your Upload Is Complete");
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}

Add single quotes to the string you are creating for the FilePath, like:string.Format("'DataUpload/{0}'", FileName);

Related

Visual studio app.config file database path for installed apps

I am using local database in my app and when I generate installation file (By Installer Package), after installing program it gives database path errors.
Eample
an attempt to attach an auto-named database for file....
//OR
The given path format is not supported
I've tried to edit database path in app.config file but it failed every time, By default my code line is like this:
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
And my app installing in C:\Program Files (86)\App_Folder\Setup Please note that future users might install it in custom path so I need a way to get dynamic path of installed app.
My question is How can I get app installed path to replace with this part AttachDbFilename=|DataDirectory|\SampleDatabase.mdf?
You could try to use AppDomain.CurrentDomain.SetData method to change your mdf file path.
Since, I don't know how do you published the winform project.
I recommend that you use Clickonce to publish it.
First, please include your mdf file in your project.
Second, you could try the following code to change the installed path after you published it.
private void Form1_Load(object sender, EventArgs e)
{
if(System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
string path = ApplicationDeployment.CurrentDeployment.DataDirectory; //Get installed path
AppDomain.CurrentDomain.SetData("DataDirectory", path);//set the DataDirectory
}
}
Finally, based on my test, I can get the information from the mdf file after I publised it and installed it in another computer.
In production mode |DataDirectory| refers to 'bin' directory, not 'app_data'. If you placed the .mdf file in the app_data directory, you can change it like this:
|DataDirectory|\SampleDatabase.mdf to |DataDirectory|\app_data\SampleDatabase.mdf
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\app_data\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Update1:
I'm sending some code. I just want to give you an idea. You can change it for your situation.
private void Form1_Load(object sender, EventArgs e)
{
if (!IsExist())
{
CreateDatabase();
CreateTables();
}
}
// Create the Database
private void CreateDatabase()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string ldfFile = "TestDatabase_Log.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
string ldfFullPath = System.IO.Path.Combine(basePath, "Data", ldfFile);
SqlConnection myConn = new SqlConnection("Server=.;Data Source=(LocalDB)\\MSSQLLocalDB;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE TestDatabase ON PRIMARY " +
"(NAME = TestDatabase, " +
$"FILENAME = '{mdfFullPath}', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
"LOG ON (NAME = MyDatabase_Log, " +
$"FILENAME = '{ldfFullPath}', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Create the tables and other stuff that you want
private void CreateTables()
{
string conStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\TestDatabase.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection myConn = new SqlConnection(conStr);
string str = #"CREATE TABLE [dbo].[TestTable]
(
[Id] INT NOT NULL PRIMARY KEY,
[Test] NVARCHAR(50) NULL
)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Check if there is the database
private bool IsExist()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
return System.IO.File.Exists(mdfFullPath);
}

AsyncFileUpload working on my machine but not on server

I have a page where I use AJAX AsyncFileUpload. It works locally on my computer, but on the server when I try to upload this error appears:
The account used is a computer account. Use your global user account
or local user account to access this server.
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3282.0
Any help to how to go about this issue is appreciated thank you!
Here is my aspx.cs code behind the asyncfileupload (On upload the file is saved in a table by a stored procedure):
protected void AsyncFileUpload_Att_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
try
{
string filename = e.FileName;
if (AsyncFileUpload_Att.PostedFile.ContentLength > 2097151)
{
Label_AttErr.Text = "File must not exceed 2,097,151 KB (2 GB)";
return;
}
else
if (Directory.Exists(#"\\svr-cif01\NetStore4\DASTORE1\ORA Project\" + TxtBx_ORAID.Text))
{
}
else { Directory.CreateDirectory(#"\\svr-cif01\NetStore4\DASTORE1\ORA Project\" + TxtBx_ORAID.Text); }
string folderPath = (#"\\svr-cif01\NetStore4\DASTORE1\ORA Project\" + TxtBx_ORAID.Text + #"\");
//check if exists
if (!File.Exists((folderPath) + filename))
{
AsyncFileUpload_Att.SaveAs((folderPath) + filename);
string ext = Path.GetExtension(filename);
string contenttype = string.Empty;
string strQuery = "Insert INTO dbo.tbl_ProjAttach([ORAID],[FileName],[filePath],[Date], [ProjAttachTypID],[UserName],[Status],[Notes]) values (#ORAID, #FileName ,#filePath, #Date, #ProjAttachTypID, #UserName, #Status, #Notes)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#ORAID", SqlDbType.VarChar).Value = TxtBx_ORAID.Text;
cmd.Parameters.Add("#FileName", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#filePath", SqlDbType.VarChar).Value = (folderPath + filename);
cmd.Parameters.Add("#Date", SqlDbType.VarChar).Value = DateTime.Today.ToString();
if (string.IsNullOrEmpty(DropDwn_ProjTyp.Text))
{
cmd.Parameters.Add("#ProjAttachTypID", DBNull.Value);
}
else cmd.Parameters.Add("#ProjAttachTypID", SqlDbType.VarChar).Value = DropDwn_ProjTyp.SelectedValue.ToString();
cmd.Parameters.AddWithValue("#UserName", SqlDbType.VarChar).Value = txtLogIn.Text;
cmd.Parameters.Add("#Status", DBNull.Value);
cmd.Parameters.Add("#Notes", SqlDbType.VarChar).Value = TextArea_Att.InnerText;
InsertUpdateData(cmd);
GridView_Att.DataBind();
Label_Saved.Visible = true;
Label_Saved.Text = "File uploaded";
}
else
{
Label_AttErr.Text = "File ''" + filename + "'' already Exists. Please Rename the file then Attach again.";
}
}
catch (Exception ex)
{
Label_AttErr.Text = ex.Message;
}
}
I think you need wrapper save this
using (new ImpersonatedUser(login, domain, password))
{
save here
}
The folder where the file is uploaded to needs "modify" permissions for the user IIS_IUSRS.

C# store data error in Microsoft Access database

private void okbtn_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Desktop\GameMuseumManagementSystem.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Email = txtEmail.Text.ToString();
String Password = txtPassword.Text.ToString();
String my_query = "INSERT INTO Member(Member_Name,Member_Password,Member_Email)VALUES('" + Name + "','" + Email + "','" + Password + "')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
I am coding for the member registeration for a guest to use it. I have 3 pieces of data, member_name, member_ID, and password. I coded this and I get an error. My Visual Studio is connected to my MS Access database via the tools, after I write this code, the data can't be stored in Access, what should I do now? Any suggestion?

Unable to connect MS Access DB in Server

I am trying to connect the MS Access Database from the server and finding no luck.
I see the below image("Insert Operation Error") message while trying to save the information.
Can anyone please help? What went wrong in the below code?
Insert Operation Error
protected void btnsave_Click(object sender, EventArgs e)
{
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");
string SqlString = "Insert Into BUREAUXDETUDES (mail1,mail2,tel1,tel2) Values (#mail1,#mail2,#tel1,#tel2)";
OleDbConnection con = new OleDbConnection(constring);
try
{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.Parameters.AddWithValue("#mail1", txtemail1.Text);
cmd.Parameters.AddWithValue("#mail2", txtemail2.Text);
cmd.Parameters.AddWithValue("#tel1", txttel1.Text);
cmd.Parameters.AddWithValue("#tel2", txttel2.Text);
cmd.ExecuteNonQuery();
lblmessage.Text = "Your Information Saved Successfully";
}
catch (Exception emsg)
{
lblmessage.Text = emsg.Message;
}
finally
{
con.Close();
}
}
The Error is telling you that the location of your .db file is incorrect.
You can change the path to the file in this line.
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");
You need to install Microsoft Excel engine first.
You can download it from the link bellow
https://www.microsoft.com/en-us/download/details.aspx?id=13255

format of the initialization string does not conform to specification at index 33

I have a simple query to update the users information however i get the error stating 'format of the initialization string does not conform to specification at index 33' and it seems to highlight this specific code Connection.Close(); however im not sure why, here is the complete code:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("FirstName=\'"
+ (txtFirstName.Text + ("\', " + ("LastName=\'"
+ (txtLastName.Text + ("\' "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("Student added successfully!", "Registered");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
EDIT:
Here are the file paths:
const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Users\\Zack\\My Documents\\Test\\Database.mdb";
const string DBFile = "C:\\Users\\Zack\\My Documents\\Test\\Database.mdb";
Your command text is wrong and you should use parametirized queries, here is correct version:
command.CommandText = "UPDATE enroll SET SSN= #ssn, FirstName = #fname, LastName = #lastName WHERE ID = #id";
command.Parameters.AddWithValue("#ssn", txtSSN.Text);
command.Parameters.AddWithValue("#fname", txtFirstName.Text);
command.Parameters.AddWithValue("#lastName", txtLastName.Text);
command.Parameters.AddWithValue("#id", _UserID);
And connection string:
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\Zack\My Documents\Test\Database.mdb'";
Zack,
There are quite a number of issues with this code. Primarly if you were to run this (as SLacks states) you are open to sql injection attacks. (Read up on it).
First off.. Your connection string (based on your code) when run will be.
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Users\\Zack\\My Documents\\Test\\Database.mdb\\C:\\Users\\Zack\\My Documents\\Test\\bin\Debug\\C:\\Users\\Zack\\My Documents\\Test\\Database.mdb
Well that is a guess. You should be using the following (note your path is hard coded).
const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\"";
const string DBFile = "Database.mdb";
//...
var connection = new System.Data.OleDb.OleDbConnection(ConnectionString)
If you wanted to make your connection string dynamic to the path try this.
string conString = string.Format(ConnectionString, Path.Combine(Application.StartupPath, DBFile));
var connection = new System.Data.OleDb.OleDbConnection(conString);
This should set your connection string properly to you application startup. Now you may find it more useful to work of the executing assembly path as opposed to the application startup (your call).
Next your queries are a mess. I have cleaned it up to use parameterized queries instead with the resulting code somthing like. (note this has not been tested).
const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"{0}\"";
const string DBFile = "Database.mdb";
public void AddNewUser()
{
string conString = string.Format(ConnectionString, Path.Combine(Application.StartupPath, DBFile));
using (var connection = new System.Data.OleDb.OleDbConnection(conString))
{
try
{
string sql = "UPDATE enroll SET SSN=#ssn, FirstName=#firstName, LastName=#lastName WHERE ID=#userID";
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#ssn", txtSSN.Text);
command.Parameters.AddWithValue("#firstName", txtFirstName.Text);
command.Parameters.AddWithValue("#lastName", txtLastName.Text);
command.Parameters.AddWithValue("#userID", _UserID);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Student added successfully!", "Registered");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
}
EDIT:
I created a test lab for the code above and all ran correctly. Let me know if you have any questions.
Cheers.

Categories