11 Replies - 1349 Views - Last Post: 25 November 2013 - 01:43 PM Rate Topic: -----

#1 JasonHerr   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 08-September 09

C# Null Reference error on text file import.

Posted 21 November 2013 - 03:41 PM

I keep getting a null reference error with my code. The primary key of the table is set to not accept nulls, but there are not any nulls in my text file that I am trying to import. I know it is something simple that I need to add to my code, but I can't quite figure it out. A second set of eyes would be greatly appreciated.

On my first post I tried to put standard html tags around my code. I did not see the code tags.

private void importButton_Click(object sender, EventArgs e)
        {
            string myDate = DateTime.Now.ToString("yyMMdd");
            string myTime = DateTime.Now.ToString("HHmm");
            string myFileName = "Address_Update" + myDate + "_" + myTime;
            int i = 0;  // index counter for progress bar
            int myLineCount = 0;

            string mRefNum = "";
            string mPSD = "";
            string mAddress_1 = "";
            string mAddress_2 = "";
            string mCity = "";
            string mState = "";
            string mPostal_Code = "";
            string mReturn_Code = "";
            string mMove_Type = "";
            string mMove_Date = "";
            string mAddress_Error_Code = "";
            string mDelivery_Point = "";
            string mCarrier_Route = "";
            string mMail_Score = "";
            string mUAA = "";

            if (TextFileBox.Text.Length == 0)
                return;
            importButton.Enabled = false;
            mUnsavedData = true;
            StreamReader myFile = new StreamReader(TextFileBox.Text, System.Text.Encoding.ASCII, false, 32000);
            Cursor.Current = Cursors.WaitCursor;


            BeginTransaction();

            try
            {
                using (myFile = new StreamReader(TextFileBox.Text, System.Text.Encoding.ASCII, false, 32000))
                {

                    string line;
                    while ((line = myFile.ReadLine()) != null)
                    {
                        myLineCount++;
                        string[] items = line.Trim().Split('|'); // This line does the magic

                        MessageBox.Show("Got Invalid Record with the Length of :" + line.Length.ToString() + " Record # " + myLineCount.ToString());
                        break;
                    }
                    TextFileBox.ToString();
                    myFile.ToString();
                    //mDatabase.mCommand.Parameters.Clear();         
                    mDatabase.mQuery = @"INSERT INTO Individual_Update (RefNum, PSD, Address_1, Address_2, City, State, Postal_Code, Return_Code,
                    Move_Type, Move_Date, Address_Error_Code, Delivery_Point, Carrier_Route, Mail_Score, UAA) VALUES (:RefNum, :PSD, :Address_1, :Address_2, 
                    :City, :State, :Postal_Code, :Return_Code, :Move_Type, :Move_Date, :Address_Error_Code, :Delivery_Point, :Carrier_Route, :Mail_Score, :UAA)";
                    mDatabase.BeginQuery();

                    //mDatabase.mCommand.Parameters.Clear();

                    mDatabase.mCommand.Parameters.Add("RefNum", mRefNum.ToString());
                    mDatabase.mCommand.Parameters.Add("PSD", mPSD.ToString());
                    mDatabase.mCommand.Parameters.Add("Address_1", mAddress_1.ToString());
                    mDatabase.mCommand.Parameters.Add("Address_2", mAddress_2.ToString());
                    mDatabase.mCommand.Parameters.Add("City", mCity.ToString());
                    mDatabase.mCommand.Parameters.Add("State", mState.ToString());
                    mDatabase.mCommand.Parameters.Add("Postal_Code", mPostal_Code.ToString());
                    mDatabase.mCommand.Parameters.Add("Return_Code", mReturn_Code.ToString());
                    mDatabase.mCommand.Parameters.Add("Move_Type", mMove_Type.ToString());
                    mDatabase.mCommand.Parameters.Add("Move_Date", mMove_Date.ToString());
                    mDatabase.mCommand.Parameters.Add("Address_Error_Code", mAddress_Error_Code.ToString());
                    mDatabase.mCommand.Parameters.Add("Delivery_Point", mDelivery_Point.ToString());
                    mDatabase.mCommand.Parameters.Add("Carrier_Route", mCarrier_Route.ToString());
                    mDatabase.mCommand.Parameters.Add("Mail_Score", mMail_Score.ToString());
                    mDatabase.mCommand.Parameters.Add("UAA", mUAA.ToString());

                    mDatabase.mCommand.ExecuteNonQuery();
                    mDatabase.mCommand.Parameters.Clear();
                }
            }
            catch (OracleException ex)
            {
                ClearForm();
                myFile.Close();
                MessageBox.Show("Database Error: " + ex.Message.ToString());
                return;
            }

            MessageBox.Show("Finished Importing Individual Address Records. Total Records Exported: " + i.ToString());
            CommitTransaction();
            mdbIndividual.Clear();
            myFile.Close();
            myFile.Dispose();
            importButton.Enabled = true;
        }      
    }
}




Is This A Good Question/Topic? 0
  • +

Replies To: C# Null Reference error on text file import.

#2 Michael26   User is offline

  • Futurama: Insert funny joke here
  • member icon

Reputation: 414
  • View blog
  • Posts: 1,664
  • Joined: 08-April 09

Re: C# Null Reference error on text file import.

Posted 21 November 2013 - 03:58 PM

It would be helpful to know where is the error. Does BeginQuery opens database connection, i don't see that here.

What is a NullReferenceException and how do I fix it?
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6818
  • View blog
  • Posts: 28,231
  • Joined: 12-December 12

Re: C# Null Reference error on text file import.

Posted 21 November 2013 - 03:59 PM

On what line in your posted code does the error occur?

BTW A quick look suggests all the variables mRefNum, etc., remain empty. Perhaps you intended to do something with items[]?
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: C# Null Reference error on text file import.

Posted 22 November 2013 - 07:09 AM

I strongly encourage you to do a few things to clean this up.

1) GUI control handlers like Button_click shouldn't be doing so much. They really should just call a method that does something. What happens when you want to call this same functionality from a menu? Or from a touchscreen swipe? Or a hotkey? Or programmatically from another method?

2) Use properties and not this crappy direct check of textbox.text all the time. GUI is just for interaction, it is not meant to be your local variables. This function falls down completely without the GUI, meaning you can't have a stand alone class that does processing... so you couldn't make several forms for different needs: clerk, supervisor, manager, customer, on-line....

3) Separation of responsibilities. Import should *just* import. It has nothing to do with saving to the database. If you wanted to import the textfile, then show it on screen to be approved by an operator and maybe make corrections, *then* send it of to the database you're stuck.

4) It should have no side effects like enabling/disabling GUI controls. That is not the responsibility of an "import" routine.

5) Use statusbar displays instead of messagebox. MessageBox holds up operation. What if you wanted to loop this for 10,000 records in a directory? You're fraked. Or maybe have a ListBox that keeps a rolling log of operations but without stopper execution to wait on an operator to click a button.

A good method should be a black-box. It takes parameters, it does its ONE and only job, and it returns its results, all without having any side effects.
Was This Post Helpful? 0
  • +
  • -

#5 JasonHerr   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 08-September 09

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 06:03 AM

@ Michael26

It is bombing on line 59 at RefNum. RefNum is the primary key. I should have mentioned that earlier. Yes BeginQuery opens the database connection.
Was This Post Helpful? 0
  • +
  • -

#6 JasonHerr   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 08-September 09

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 06:24 AM

@andrewsw

With Items[] I just wanted to parse the file inserting the pipe character between fields. Then insert the records from the file into the database columns. RefNum is the primary key in another table that is linked with the Individual_Update table.
Was This Post Helpful? 0
  • +
  • -

#7 JasonHerr   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 08-September 09

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 07:47 AM

@tlhIn`toq

Thanks for the suggestions. Yes it should not be so GUI dependent. I have made some changes to my code based on your suggestions. Also, I created a method for a status bar. However, I am not sure how to create an oracle exception without using a MessageBox.

 private void importButton_Click(object sender, EventArgs e)
        {
            string myDate = DateTime.Now.ToString("yyMMdd");
            string myTime = DateTime.Now.ToString("HHmm");
            string myFileName = "Address_Update" + myDate + "_" + myTime;
            int i = 0;  // index counter for progress bar
            int myLineCount = 0;

            string mRefNum = "";
            string mPSD = "";
            string mAddress_1 = "";
            string mAddress_2 = "";
            string mCity = "";
            string mState = "";
            string mPostal_Code = "";
            string mReturn_Code = "";
            string mMove_Type = "";
            string mMove_Date = "";
            string mAddress_Error_Code = "";
            string mDelivery_Point = "";
            string mCarrier_Route = "";
            string mMail_Score = "";
            string mUAA = "";

            if (TextFileBox.Text.Length == 0)
                return;
            importButton.Enabled = false;
            mUnsavedData = true;
            StreamReader myFile = new StreamReader(TextFileBox.Text, System.Text.Encoding.ASCII, false, 32000);
            Cursor.Current = Cursors.WaitCursor;

            BeginTransaction();

            try
            {
                using (myFile = new StreamReader(TextFileBox.Text, System.Text.Encoding.ASCII, false, 32000))
                {
                    string line;
                    while ((line = myFile.ReadLine()) != null)
                    {
                        myLineCount++;
                        string[] items = line.Trim().Split('|'); // This line does the magic

                        MessageBox.Show("Got Invalid Record with the Length of :" + line.Length.ToString() + " Record # " + myLineCount.ToString());
                        break;
                    }                   
                }   
            }
            catch (Exception ex)
            {
                MyStatusBar();
                MessageBox.Show("The file could not be read:" + ex.Message.ToString());
            }
                              
            try
            {
                mDatabase.mQuery = @"INSERT INTO Individual_Update (RefNum, PSD, Address_1, Address_2, City, State, Postal_Code, Return_Code,
                Move_Type, Move_Date, Address_Error_Code, Delivery_Point, Carrier_Route, Mail_Score, UAA) VALUES (:RefNum, :PSD, :Address_1, :Address_2, 
                :City, :State, :Postal_Code, :Return_Code, :Move_Type, :Move_Date, :Address_Error_Code, :Delivery_Point, :Carrier_Route, :Mail_Score, :UAA)";
                mDatabase.BeginQuery();

                mDatabase.mCommand.Parameters.Add("RefNum", mRefNum);
                mDatabase.mCommand.Parameters.Add("PSD", mPSD);
                mDatabase.mCommand.Parameters.Add("Address_1", mAddress_1);
                mDatabase.mCommand.Parameters.Add("Address_2", mAddress_2);
                mDatabase.mCommand.Parameters.Add("City", mCity);
                mDatabase.mCommand.Parameters.Add("State", mState);
                mDatabase.mCommand.Parameters.Add("Postal_Code", mPostal_Code);
                mDatabase.mCommand.Parameters.Add("Return_Code", mReturn_Code);
                mDatabase.mCommand.Parameters.Add("Move_Type", mMove_Type);
                mDatabase.mCommand.Parameters.Add("Move_Date", mMove_Date);
                mDatabase.mCommand.Parameters.Add("Address_Error_Code", mAddress_Error_Code);
                mDatabase.mCommand.Parameters.Add("Delivery_Point", mDelivery_Point);
                mDatabase.mCommand.Parameters.Add("Carrier_Route", mCarrier_Route);
                mDatabase.mCommand.Parameters.Add("Mail_Score", mMail_Score);
                mDatabase.mCommand.Parameters.Add("UAA", mUAA);
            
                mDatabase.mCommand.ExecuteNonQuery();
                mDatabase.mCommand.Parameters.Clear();               
            }
            catch (OracleException ex)
            {
                ClearForm();
                myFile.Close();
                MyStatusBar();
                MessageBox.Show("Database Error: " + ex.Message.ToString());
                return;
            }
                              
            MessageBox.Show("Finished Importing Individual Address Records. Total Records Exported: " + i.ToString());
            CommitTransaction();
            mdbIndividual.Clear();
            myFile.Close();
            myFile.Dispose();
            importButton.Enabled = true;
        }


Was This Post Helpful? 0
  • +
  • -

#8 Robin19   User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 09:26 AM

Make classes that do parts of the work. Those classes can raise events when errors occur and when they are finished. Your GUI can listen for these events and make appropriate changes on the form.

I can't make heads or tails of what your button click is supposed to do, so adjust my advice accordingly. Have a class that handles the reading of the file. Have a class that handles inserting a Person class into the database. The Person class can be built by a property on the form using the text boxes.

These classes should have no knowledge of the form or how they received their information. They should also have no knowledge of what to do if an error occurs. They should raise an event if they have an error and stop processing. If they complete their work, they can raise an event signalling so. That way you can change out the UI without having to make a change to the domain classes.
Was This Post Helpful? 0
  • +
  • -

#9 JasonHerr   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 08-September 09

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 11:01 AM

All the import button is supposed to do is load a file, parse the data, and then add the items to the database. I have re-worked the code and I no longer get the null reference error. I was getting the error because I was not adding the items of the array to the database, so it kept trying to insert null at RefNum and RefNum does not accept nulls. andrewsw was correct. All of the variables were empty. I was trying to load the individual fields into the database with nothing in them.

private void importButton_Click(object sender, EventArgs e)
        {
            string myDate = DateTime.Now.ToString("yyMMdd");
            string myTime = DateTime.Now.ToString("HHmm");
            string myFileName = "Address_Update" + myDate + "_" + myTime;
            int i = 0;  // index counter for progress bar
            int myLineCount = 0;

            if (TextFileBox.Text.Length == 0)
                return;
            importButton.Enabled = false;
            mUnsavedData = true;
            StreamReader myFile = new StreamReader(TextFileBox.Text, System.Text.Encoding.ASCII, false, 32000);
            Cursor.Current = Cursors.WaitCursor;

            BeginTransaction();

             mDatabase.mQuery = @"INSERT INTO Individual_Update (RefNum, PSD, Address_1, Address_2, City, State, Postal_Code, Return_Code,
                Move_Type, Move_Date, Address_Error_Code, Delivery_Point, Carrier_Route, Mail_Score, UAA) VALUES (:RefNum, :PSD, :Address_1, :Address_2, 
                :City, :State, :Postal_Code, :Return_Code, :Move_Type, :Move_Date, :Address_Error_Code, :Delivery_Point, :Carrier_Route, :Mail_Score, :UAA)";
                mDatabase.BeginQuery();

                 string line;
                 string[] items;

                 line = myFile.ReadLine();

                 items = items = line.Split('|');
                
                    while ((line = myFile.ReadLine()) != null)
                    {
                        myLineCount++;
                        items = items = line.Split('|'); // This line does the magic

                        mDatabase.mCommand.Parameters.Add("RefNum", items[0]);
                        mDatabase.mCommand.Parameters.Add("PSD", items[1]);
                        mDatabase.mCommand.Parameters.Add("Address_1", items[2]);
                        mDatabase.mCommand.Parameters.Add("Address_2", items[3]);
                        mDatabase.mCommand.Parameters.Add("City", items[4]);
                        mDatabase.mCommand.Parameters.Add("State", items[5]);
                        mDatabase.mCommand.Parameters.Add("Postal_Code", items[6]);
                        mDatabase.mCommand.Parameters.Add("Return_Code", items[7]);
                        mDatabase.mCommand.Parameters.Add("Move_Type", items[8]);
                        mDatabase.mCommand.Parameters.Add("Move_Date", items[9]);
                        mDatabase.mCommand.Parameters.Add("Address_Error_Code", items[10]);
                        mDatabase.mCommand.Parameters.Add("Delivery_Point", items[11]);
                        mDatabase.mCommand.Parameters.Add("Carrier_Route", items[12]);
                        mDatabase.mCommand.Parameters.Add("Mail_Score", items[13]);
                        mDatabase.mCommand.Parameters.Add("UAA", items[14]);

                        mDatabase.mCommand.ExecuteNonQuery();
                        mDatabase.mCommand.Parameters.Clear();
                   }  
            
            MessageBox.Show("Finished Importing Individual Address Records. Total Records Exported: " + i.ToString());
            CommitTransaction();
            importButton.Enabled = true;
            myFile.Close();
            myFile.Dispose();        
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#10 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6818
  • View blog
  • Posts: 28,231
  • Joined: 12-December 12

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 11:16 AM

Quote

andrewsw was correct.

:smartass:

Glad you sorted ;)
Was This Post Helpful? 0
  • +
  • -

#11 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 12:10 PM

Quote

All the import button is supposed to do is load a file, parse the data, and then add the items to the database


All?

In the future, you should read up on OOP. The idea is that you'd make classes to model functionality. So, you might have a DataManager class that handles the DB connection and queries, a FileManager class that would handle loading data from the file, and perhaps a model class to represent what each of your file rows means, so you don't have to go around using items[4], since nobody knows what that particular index represents.

It sounds like more work, but trust me, when you come back to it later you'll be glad you've logically organized everything. Especially if you have to make a change. You'd have to chase down every place you did something instead of fixing it once in the class.
Was This Post Helpful? 0
  • +
  • -

#12 JasonHerr   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 08-September 09

Re: C# Null Reference error on text file import.

Posted 25 November 2013 - 01:43 PM

I understand OOP quite well. I was not trying to undermine the concept(s). There just wasn't supposed to be many operations for the method.

The database stuff is handled in its own class. However, there is no file manager class or model class. Thanks for the suggestions. I will separate them in the future.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1