AsyncFileUpload working on my machine but not on server - c#

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.

Related

Check if same username exists in sql server management..... if so dont add the username

It is showing me 2 errors.. please help .....required for my project work
The error showing in both cases is as follows:-
Error 1 'System.Data.SqlClient.SqlDataAdapter' does not contain a
definition for 'loginregistration' and no extension method
'loginregistration' accepting a first argument of type
'System.Data.SqlClient.SqlDataAdapter' could be found (are you missing
a using directive or an assembly reference?)
private void btnSave_Click(object sender, EventArgs e)
{
{
if (txtUsername.Text == "" || txtEmail.Text == "")
{
MessageBox.Show("Please enter all Details");
}
else
{
SqlCommand cmd = new SqlCommand("select * from loginregistration WHERE username='" + txtUsername.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = da.loginregistration[0].Rows.Count;//.........(ERROR HERE)
if (i > 0)
{
MessageBox.Show("Username Already Exists");
da.Clear();//............(ERROR HERE)
}
else
{
try
{
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into loginregistration(username,FirstName,LastName,Email,Address,Contact_No) VALUES('" + txtUsername.Text + "','" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtAddress.Text + "','" + txtContact.Text + "')";
cmd1.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Inserted Successfully");
txtUsername.Text = txtFirstName.Text = txtLastName.Text = txtEmail.Text = txtContact.Text = txtAddress.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("ex.Message");
}
}
}
}
}
Let's extract a method for checking user's existence. We don't need to load all the data into a DataTable with a help of SqlDataAdapter; one query will be enough:
private bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection("Connection_String_Here")) {
conn.Open();
// Keep query readable
// Make query parametrized
string sql =
#"select 1
from LoginRegistration
where UserName = #prmUserName";
// Do not share the single connection, but create a new one
using (SqlCommand q = new SqlCommand(sql, conn)) {
q.Parameters.Add("#prmUserName", SqlDbType.VarChar).Value = userName;
// If we can read at least one record
using (var reader = q.ExecuteReader()) {
// we can be sure the user exists
return reader.Read();
}
}
}
}
Now, let's use our method:
if (string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtEmail.Text))
MessageBox.Show("Please enter all Details");
else {
if (UserExists(txtUsername.Text))
MessageBox.Show("Username Already Exists");
else {
...
}
}
try to use dataset
DataSet loginregistration = new DataSet();
da.Fill(loginregistration ,"loginregistration ");
To fix your existing code:
int i = da.loginregistration[0].Rows.Count;
should be
int i = ds.Tables[0].Rows.Count;
That said you should pay attention to the answer Dmitry gave and parameterise your SQL. Your current method is wide open to SQL Injection.

C# Syntax Error in INSERT INTO statement C#

if (txtUsername.Text != "")
{
string q = "insert into info(Username) values ('" + txtUsername.Text.ToString() + "')";
dosomething(q);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
if (txtPassword.Text != "")
{
string a = "insert into info(Password) values ('" + txtPassword.Text.ToString() + "')";
dosomething(a);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Every time I run this it always show that error. I dont know how to fix it.
The code should record the data i put in a textbox to ms access database. plz helpp
Presumably, you've initialized cn somewhere by doing something like
cn = new SqlConnection();
You need to pass the connection string for the database to the constructor:
cn = new SqlConnection("your connection string here");
or set it sometime later, before you connect:
cn.ConnectionString = "your connection string here";

file upload error, "not found on selected data source"

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

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.

unable to update profile picture using varbinary

I'm trying to update my profile picture using varbinary (SQL Server 2008). It don't seem to update the picture that I put in the fileupload. Below is the code I use to update my profile picture. Do help me take a look on which part of my coding did I do wrongly.
Thanks.
protected void btnUpload_Click(object sender, EventArgs e)
{
String username = (String)Session["username"];
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".jpg":
contenttype = "image/jpg";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "Update LoginRegisterOthers Set profilepic = #Data Where username = '" + username + "'";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Profile Updated.";
Response.Redirect("MemberProfile.aspx");
}
else if (contenttype == String.Empty)
{
lblMessage.Text = "Please select your image before uploading!";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." + " Upload Image formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
try this:
...
//insert the file into database
string strQuery = "Update LoginRegisterOthers Set profilepic = (SELECT BULKCOLUMN FROM OPENROWSET(BULK N'"+filename+"', SINGLE_BLOB) AS FIle_picture) Where username = '" + username + "'";
...
You can load a file directly with sql.

Categories