Record not created

Hi,
Here are the codes

        private byte[] ImageToStream(string fileName)
        {
            return File.ReadAllBytes(fileName);
        }

                    cmd6 = new OleDbCommand("insert into ite_feat (ord_key,ite_id,feat_desc,feat_file,add_dt) values (1,@ite_id,@feat_desc,@feat_file,date)", conn2);
                    cmd6.Parameters.Add("@ite_id", OleDbType.VarChar).Value = lb_ite_id.Text.Trim();
                    cmd6.Parameters.Add("@feat_desc", OleDbType.VarWChar).Value = Request.Form["tb_p1_desc"];
                    cmd6.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(lb_feat.Text);
                    if (cmd6.ExecuteNonQuery() < 1) 
                    {
                        ...

Open in new window

to insert the record into Access table, while at the moment, I am able to show the picture within the Markup page like

                    <img src=<%=lb_pict.Text %> />
                    ...

Open in new window

why can't I insert the record, as there is no record created within Access table, after the execution of the above codes?
LVL 11
HuaMin ChenProblem resolverAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
unless you get an error that you hide by a generic catch statement, impossible to tell apart from double-checking the table and column names...
0
HuaMin ChenProblem resolverAuthor Commented:
I don't know why I got no record inserted, after running the above codes.
0
ste5anSenior DeveloperCommented:
Please, don't x-post..

Can you post the entire method? Can you post the table definition? How do you check, whether the insert has worked or not?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

HuaMin ChenProblem resolverAuthor Commented:
The method is just having the above codes. I don't know why record is not created, after running the above lines.
0
ste5anSenior DeveloperCommented:
The method is just having the above codes.
Nope. this does not even compile..
0
HuaMin ChenProblem resolverAuthor Commented:
Here is the full codes
        protected void save_det_rec(string ret_msg)
        {
            OleDbConnection conn2;
            conn2 = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=????;Data Source=C:\inetpub\VS2012\ite_DB.accdb");
            OleDbCommand cmd6 = null;
            ret_msg = "";

            conn2.Open();
            try
            {
                cmd6 = new OleDbCommand("insert into ite_feat (ord_key,ite_id,feat_desc,feat_file,add_dt) values (1,@ite_id,@feat_desc,@feat_file,date)", conn2);
                cmd6.Parameters.Add("@ite_id", OleDbType.VarChar).Value = lb_ite_id.Text.Trim();
                cmd6.Parameters.Add("@feat_desc", OleDbType.VarWChar).Value = Request.Form["tb_p1_desc"];
                cmd6.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(lb_feat.Text);
                if (cmd6.ExecuteNonQuery() < 1)
                {
                    ret_msg = "failed";
                    return;
                }
            catch (Exception ex)
            {
                ret_msg = "ex 1";
                return;
            }
            finally
            {
                conn2.Close();
            }
        }

Open in new window

0
ste5anSenior DeveloperCommented:
Well, you don't want to answer my questions: How do you test whether the row was inserted or not?

You should also refactor your code:  
 // Provider class (factory method). 
// This allows you to keep and use your connection string  at exactly one place.
public class OleDbConnectionProvider
{
	public static OleDbProvider CreateConnection()
	{
		const string CONNECTION_STRING = @"Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=????;Data Source=C:\inetpub\VS2012\ite_DB.accdb";
		return new OleDbConnection(CONNECTION_STRING);
	}
}

class WhatEver 
{
	protected bool AddItemFeature(int itemID, string featureDescription, string imageFileName, out string resultMessage)
	{
		// TODO: Error handling due to ImageToStream() method.
		const string SQL_COMMAND = "INSERT INTO ite_feat ( ord_key, ite_id, feat_desc, feat_file, add_dt) VALUES ( 1, @ite_id, @feat_desc, @feat_file, Date);";
         
		bool result = false;
		
		resultMessage = "D'oh?";
		using (OleDbConnection connection = OleDbConnectionProvider.CreateConnection())
		{
			using (OleDbCommand command = new OleDbCommand(SQL_COMMAND))
			{
				command.Parameters.Add("@ite_id", OleDbType.Integer).Value = itemID;
				command.Parameters.Add("@feat_desc", OleDbType.VarWChar).Value = featureDescription;
				command.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(imageFileName);
				try
				{
				    result = (command.ExecuteNonQuery() == 1);
					if (result
					{
						resultMessage = "Item added.";						
					}
					else
					{
						resultMessage = "Item not added.";
					}
				}
				catch (Exception exception)
				{
					resultMessage = exception.Message;
				}
			}
		}
		
		return result;
	}

	private object ImageToStream(string imageFileName)
	{
		// TODO: Error handling.
		return File.ReadAllBytes(imageFileName);
	} 
}

Open in new window


You're using an Access database file for a web site, this may cause later own concurrency issues. btw, gets your database file overwritten by your deployment process?

I would recommend that you use SQL Server (Express is free).
0
HuaMin ChenProblem resolverAuthor Commented:
Thanks. I think it is not a good idea to change the codes above.

I see that

lb_ite_id.Text.Trim()
Request.Form["tb_p1_desc"]
lb_feat.Text

Open in new window

are all having values inside. But I don't know why my codes are not inserting the record successfully.
0
ste5anSenior DeveloperCommented:
It's a really good idea, because it is a really bad idea to insert non-validated input from users...

But I don't know why my codes are not inserting the record successfully.
Gosh, HOW DO YOU TEST THIS???
0
HuaMin ChenProblem resolverAuthor Commented:
The point is just why no record has not been inserted
0
HuaMin ChenProblem resolverAuthor Commented:
Correction: The problem is just why no record has been inserted
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
Dear HuaMinChen,

  it is "your" problem that the record is not inserted, which we have understood.

 it is "our" problem that you are not telling us the information we need.
 you are our eyes in regards to your problem, code, etc...
 so far, you where not really collaborative in regards to that part of the problem-solving process.

 we (the voluntary people trying to help) cannot solve the problem if you don't tell us the things.

 just 1 quick idea: your code (connection string) refers to this file:
 Data Source=C:\inetpub\VS2012\ite_DB.accdb

 1 simple "gotcha" would be that you are not looking into THAT database, but in another one...
 
 so again : HOW EXACTLY do you check that the record is not inserted.
 also, are you 200% sure there error/exception is not hidden anywhere down the lines (which can happen quite easily in a web application ...)
 does the code work for other tables? what if you don't fill the field for feat_file column, does it work then?
0
HuaMin ChenProblem resolverAuthor Commented:
Hi,
I get this exception and stacktrace
Could not find file 'c:\windows\system32\inetsrv\t737.png'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.File.InternalReadAllBytes(String path, Boolean checkHost) at App7._Default.save_det_rec(String ret_msg)Could not find file 'c:\windows\system32\inetsrv\t737.png'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.File.InternalReadAllBytes(String path, Boolean checkHost) at App7._Default.save_det_rec(String ret_msg) 

Open in new window


how to correct the last line below

        private byte[] ImageToStream(string fileName)
        {
            return File.ReadAllBytes(fileName);
        }
        ...
        
        	cmd6.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(lb_feat.Text);
		...

Open in new window

for referring to the relevant picture file, as the file does reside in this folder, to which the project was deployed?

C:\inetpub\VS2012\App7
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
see, now we are speaking.
the issue is that visibly, lb_feat.Text is only containing the file NAME, and not the file PATH.
to solve that, you can use this:
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath%28v=vs.110%29.aspx

  private byte[] ImageToStream(string fileName)
        {
            return File.ReadAllBytes( HttpServerUtility.MapPath( fileName) );
        }


this should properly set the folder of you web page
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, I get this
Error	2	An object reference is required for the non-static field, method, or property 'System.Web.HttpServerUtility.MapPath(string)'	C:\App7\App7\Default.aspx.cs	41	38	App7

Open in new window

due to this line
           
return File.ReadAllBytes(HttpServerUtility.MapPath(fileName));
            ...

Open in new window

0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
is this is not a web application (asp.net)?

if it is a web application, the above should work. please check which object/value is null at that place...

if it's not a web application (plain C#), you need to get the application path like this;
string path;
   path = System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
   MessageBox.Show( path );

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
It is one web application (.Net) but I got the problem when building it.
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
the please use Server.MapPath(fileName) instead
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry I still get his

No value given for one or more required parameters. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at App7._Default.save_det_rec(String ret_msg)

Open in new window

while

lb_ite_id.Text
Request.Form["tb_p1_desc"]
lb_feat.Text

Open in new window

are respectively having these values inside.

18
房间1
t737.png 

Open in new window


based on these codes.


                    cmd6 = new OleDbCommand("insert into ite_feat (ord_key,ite_id,feat_desc,feat_file,add_dt) values (1,@ite_id,@feat_desc,@feat_file,date)", conn2);
                    cmd6.Parameters.Add("@ite_id", OleDbType.Integer).Value =Convert.ToInt32(lb_ite_id.Text.Trim());
                    cmd6.Parameters.Add("@feat_desc", OleDbType.VarWChar).Value = Request.Form["tb_p1_desc"];
                    cmd6.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(lb_feat.Text);
                    if (cmd6.ExecuteNonQuery() < 1)
                    {
                        ret_msg = "failed";
                        ...

Open in new window

0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
no need to be sorry, but as you notice, the previous error has been solved.

this one is simple:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters%28v=vs.110%29.aspx
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.

Open in new window

hence:
cmd6 = new OleDbCommand("insert into ite_feat (ord_key,ite_id,feat_desc,feat_file,add_dt) values (1,?,?,?,date)", conn2);
                    cmd6.Parameters.Add("@ite_id", OleDbType.Integer).Value =Convert.ToInt32(lb_ite_id.Text.Trim());
                    cmd6.Parameters.Add("@feat_desc", OleDbType.VarWChar).Value = Request.Form["tb_p1_desc"];
                    cmd6.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(lb_feat.Text);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ste5anSenior DeveloperCommented:
Please, please, please: Don't use user input directly. Validate it.
0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks Guy Hengel.

with these codes

                conn2.Open();
                try
                {
                    cmd6 = new OleDbCommand("insert into ite_feat (ord_key,ite_id,feat_desc,feat_file,add_dt) values (1,?,?,?,date)", conn2);
                    cmd6.Parameters.Add("@ite_id", OleDbType.Integer).Value =Convert.ToInt32(lb_ite_id.Text.Trim());
                    cmd6.Parameters.Add("@feat_desc", OleDbType.VarWChar).Value = Request.Form["tb_p1_desc"];
                    cmd6.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(lb_feat.Text);
                    if (cmd6.ExecuteNonQuery() < 1) // if it returned 1 it means one (or more) row has been updated, otherwise no change made in DB
                    {
                        ret_msg = "failed";
                        ...
                    }
                }
                catch (SqlException ex)
                {
                    ...

Open in new window

while

lb_ite_id.Text
Request.Form["tb_p1_desc"]
lb_feat.Text

Open in new window


                                         
are respectively having these values inside.

18
房间1
t737.png 

Open in new window

I still get this exception and stacktrace

No value given for one or more required parameters. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at App7._Default.save_det_rec(String ret_msg)

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
With these codes actually
        private byte[] ImageToStream(string fileName)
        {
            return File.ReadAllBytes(Server.MapPath(fileName));
        }

                conn2.Open();
                try
                {
                    cmd6 = new OleDbCommand("insert into ite_feat (ord_key,ite_id,feat_desc,feat_file,add_dt) values (1,?,?,?,date())", conn2);
                    cmd6.Parameters.Add("@ite_id", OleDbType.Integer).Value =Convert.ToInt32(lb_ite_id.Text.Trim());
                    cmd6.Parameters.Add("@feat_desc", OleDbType.VarWChar).Value = Request.Form["tb_p1_desc"];
                    cmd6.Parameters.Add("@feat_file", OleDbType.Binary).Value = ImageToStream(lb_feat.Text);
                    if (cmd6.ExecuteNonQuery() < 1)
                    {
                        ret_msg = "failed";
                        ...
                    }
                }
                catch (SqlException ex)
                {
                    ...

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Please omit my last reply above. Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.