12 Replies - 594 Views - Last Post: 26 April 2013 - 06:13 AM Rate Topic: -----

#1 breakdown  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 11-April 13

Error if run without debugger

Posted 16 April 2013 - 12:57 PM

So I finished my program and tested it by compiling with the 'attached debugger' and it worked perfectly. However, when I run it without the attached debugger it crashes when either of two lines are compiled. It gives me a System.ArgumentNullException. The methods work fine if I compile it with the debugger, they perform exacly as they should. Here's the two relevant classes:


In this class, the error points to lines 252 and 260.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Assignment_3
{
	/// <summary>
	/// This class performs all the operations for the GUI and calls the static methods used in InputUtility.
	/// It also initializes the GUI and updates it when new info is put in.
	/// </summary>
	public partial class MainForm : Form
	{
		private const int totalNumOfSeats = 60;
		private const int m_totNumOfCols = 10;
		private const int m_totNumOfRows = 6;
		
		SeatManager m_seatMngr = new SeatManager(m_totNumOfRows, m_totNumOfCols);
		
		/// <summary>
		/// Basic start-up method.
		/// </summary>
		public MainForm()
		{
			m_seatMngr.InitArrays();
			InitializeComponent();
			InitializeGUI();
		}
		
			/// <summary>
			/// Inserts information into the list box, disables unnecessary fields, holds the formatting for
			/// the list box, shows how many seats are taken, vacant and there are in total and clears the fields
			/// when they've been used.
			/// </summary>
		public void UpdateGUI() 
		{	
			if (reserveRadio.Checked) //If reservation is used, put a marker in the name field.
			{
				nameField.Focus();
				nameField.Clear(); 
				priceField.Clear();
			}
		}
			/// <summary>
			/// Makes sure the reserve radio button is checked at start-up, the list box is empty and the
			/// name field is clear.
			/// </summary>
		private void InitializeGUI()
		{
			int numOfVacantSeats;
				
			reserveRadio.Checked = true; //Reservation is automatically checked at start-up.
			reservationsBox.Items.Clear(); //Nothing is in the reservations box at start-up.
			nameField.Text = string.Empty; //Clears the field for names at start-up.
			
			showCombo.Items.AddRange(Enum.GetNames(typeof(DisplayOptions))); //Fills the showBox with the enums.
			showCombo.SelectedIndex = (int)DisplayOptions.AllSeats; //Makes sure AllSeats is the selected option upon start-up.
			
			//Initiates labels so they don't display code until they're given an input.
			//Why is this assigned here and in UpdateGUI? I couldn't get them to display properly otherwise.
			totalSeatsLabel.Text = totalNumOfSeats.ToString(); 
			numOfVacantSeats = m_seatMngr.CountSeats();
			reservedSeatsLabel.Text = (totalNumOfSeats - numOfVacantSeats).ToString(); //Shows number of reserved seats
			vacantSeatsLabel.Text = numOfVacantSeats.ToString(); //Shows number of vacant seats
			reservationsBox.SelectedIndex = 0;
		}
		
			/// <summary>
			/// Executes when the user clicks on the OK button. Starts the validation of the input name and price
			/// and also calls the UpdateGUI method above.
			/// </summary>
			/// 
		private void OkBtnClick(object sender, EventArgs e)
		{
			int index = reservationsBox.SelectedIndex;
			string name = nameField.Text;
			string priceString = priceField.Text;
			
			UpdateGUI();
			
			if (reserveRadio.Checked)
			{
				ReserveOneSeat(name, priceString, index);
			}
			
			else
			{
				CancelOneSeat(index);
			}
		}
			/// <summary>
			/// Recieves a string for a name, a string for a price and a double for a price and sends them to the
			/// appropriate methods to be validated. If both name and price are validated, returns true.
			/// </summary>
		private bool ReadAndValidateInput(string name, string priceString) //Makes sure both name and price is okay.
		{
			double price = 0;
			bool nameOK = ReadAndValidateName(name);
			bool priceOK = ReadAndValidatePrice(priceString, price);
			return nameOK && priceOK;
		}
			/// <summary>
			/// Validates a name by making sure the field isn't empty or has unnecessary white spaces. Returns
			/// true if the validation is successful. 
			/// </summary>
		private bool ReadAndValidateName(string name)
		{
			if (InputUtility.ValidateString(name))//Makes sure the name field isn't empty.
			{				
				return true; 
			}
			
			else //Informs the user of his shortcoming and puts focus on the errenous name.
			{
				MessageBox.Show("Invalid name! It cannot be empty" + Environment.NewLine +
				               "and it must have at least one character!", "Error!", MessageBoxButtons.OK);
				nameField.Focus();
				nameField.SelectAll();
				return false;
			}
		}
			/// <summary>
			/// Validates a price by making sure it's positive and that it can be converted from a string to 
			/// a double and returns true if that validation is successful.
			/// </summary>
		private bool ReadAndValidatePrice(string priceString, double price) //Makes sure the number is positive.
		{		
			if (InputUtility.GetDouble(priceString, out price))
			{	
				return true;
			}
			
			else 
			{
				MessageBox.Show("Failed to input price!" + Environment.NewLine + //Display friendly message informing the user that he's doing it wrong.
				                "Make sure you use a ',' for decimals" + Environment.NewLine +
				                "and a positive price!", "Error!", MessageBoxButtons.OK);
				return false;
			}
		}
			/// <summary>
			/// If the reservation radio button is checked, will enable the price and name fields.
			/// </summary>
		private void ReserveRadioCheckedChanged(object sender, EventArgs e) //Disables the name field and price field if cancel is checked.
		{
			nameField.Enabled = true;
			priceField.Enabled = true;
		}
		/// <summary>
		/// If the cancellation radio button is checked, will disable the price and name fields.
		/// </summary>
		private void CancelReserveRadioCheckedChanged(object sender, EventArgs e)
		{
			nameField.Enabled = false;
			priceField.Enabled = false;
		}
		
		/// <summary>
		/// Contains the different steps for reserving or cancelling a seat. 
		/// If reservation is selected, it checks the array's element to see if
		/// it's used. If it is, it prompts the user, asking him if he wants to
		/// continue. If it's not used, it simply calls the necessary methods
		/// in order to write the element.
		/// </summary>
		/// <param name="name">The name written in the name field.</param>
		/// <param name="priceString">The price written in the price field.</param>
		private void ReserveOneSeat(string name, string priceString, int index)
		{	
			if (!m_seatMngr.IsArrayEmpty(index))
			{
				DialogResult seatContinue = MessageBox.Show("Seat is already taken, continue anyway?", "Seat taken", MessageBoxButtons.YesNo);
				
				if (seatContinue == DialogResult.Yes)
				{
					if (ReadAndValidateInput(name, priceString))
					{	
						m_seatMngr.ReserveSeat(name, priceString, index);
						reservationsBox.Items.Clear();
						reservationsBox.Items.AddRange(m_seatMngr.SeatsAll());
					}		
				}
			}
			
			else
			{
				if (ReadAndValidateInput(name, priceString)) 
				{
					m_seatMngr.ReserveSeat(name, priceString, index);
					reservationsBox.Items.Clear();
					reservationsBox.Items.AddRange(m_seatMngr.SeatsAll());
				}
			}
						reservationsBox.SelectedIndex = 0;
			
			//For the seat counter.
			int numOfVacantSeats = m_seatMngr.CountSeats();		
			reservedSeatsLabel.Text = (totalNumOfSeats - numOfVacantSeats).ToString(); //Shows number of reserved seats
			vacantSeatsLabel.Text = numOfVacantSeats.ToString(); //Shows number of vacant seats
		}
		
		private void CancelOneSeat(int index)
		{		
			if (cancelReserveRadio.Checked)
			{
				m_seatMngr.CancelSeat(index);
				reservationsBox.Items.Clear();
				reservationsBox.Items.AddRange(m_seatMngr.SeatsAll());
			}
			
			else
			{
				MessageBox.Show("You must select a reservation!");
			}

			//For the seat counter.
			int numOfVacantSeats = m_seatMngr.CountSeats();		
			reservedSeatsLabel.Text = (totalNumOfSeats - numOfVacantSeats).ToString(); //Shows number of reserved seats
			vacantSeatsLabel.Text = numOfVacantSeats.ToString(); //Shows number of vacant seats			
		}

		/// <summary>
		/// Allows the user to select the attribute of showing the seats; all, vacant-only or reserved-only.
		/// Also turns off certain functions of the form when using said functions would be a bad thing.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void ShowComboSelectedIndexChanged(object sender, EventArgs e)
		{
			if (showCombo.SelectedIndex == 0) 
			{
				okBtn.Enabled = true;
				seatWarning.Visible = false;
			}
			
			else
			{
				okBtn.Enabled = false;
				seatWarning.Visible = true;
			}
			
			if (showCombo.SelectedIndex == 0 && reserveRadio.Checked) //All seats visible.
			{
				reservationsBox.Items.Clear();
				reservationsBox.Items.AddRange(m_seatMngr.SeatsAll());
				nameField.Enabled = true;
				priceField.Enabled = true;
			}
			
			else if (showCombo.SelectedIndex == 1) //Vacant seats visible.
			{
				reservationsBox.Items.Clear();
				reservationsBox.Items.AddRange(m_seatMngr.SeatsVacant());
				nameField.Enabled = false;
				priceField.Enabled = false;
			}
			
			else if (showCombo.SelectedIndex == 2) //Reserved seats visible.
			{
				reservationsBox.Items.Clear();
				reservationsBox.Items.AddRange(m_seatMngr.SeatsReserved());
				nameField.Enabled = false;
				priceField.Enabled = false;
			}
		}
	}
}



using System;

namespace Assignment_3
{
	/// <summary>
	/// Handles the information used in MainForm.
	/// </summary>
	public class SeatManager
	{	
		private int m_totNumOfRows;
		private int m_totNumOfCols;
		private int m_totNumOfSeats;
		private string[,] m_nameMatrix;
		private string[,] m_priceMatrix;
		private string[,] seatMatrix;
				
		/// <summary>
		/// Constructor that transfers parameters from another class.
		/// </summary>
		/// <param name="totalRows">Total number of rows</param>
		/// <param name="totalCols">Total number of columns</param>
		public SeatManager(int totalRows, int totalCols)
		{				
			m_totNumOfCols = totalCols;
			m_totNumOfRows = totalRows;
			m_totNumOfSeats = (m_totNumOfRows * m_totNumOfCols);
			
			m_nameMatrix = new string[m_totNumOfRows,m_totNumOfCols];
			m_priceMatrix = new string[m_totNumOfRows,m_totNumOfCols];
			seatMatrix = new string[m_totNumOfRows,m_totNumOfCols];				
		}
		
		/// <summary>
		/// Fills the matrix with 'Vacant' strings.
		/// </summary>
		public void InitArrays()
		{		
			for (int row = 0; row < m_totNumOfRows; row++)
			{
				for (int col = 0; col < m_totNumOfCols; col++)
				{
					seatMatrix[row,col] = string.Format("{0,2}{1,4}{2,9}", row, col, "Vacant");
				}	
			}						
		}		
		
		/// <summary>
		/// Converts a single-dimension index into the row of a two-dimensional matrix.
		/// </summary>
		/// <param name="index">Selected index</param>
		/// <returns>The row of the two-dimensional matrix</returns>
		public int GetRow(int index)
		{
			int vectorRow = index;
			int row;
			row = (int)Math.Ceiling((double)(vectorRow / m_totNumOfCols));
			return row;
		}
		/// <summary>
		/// Same as above, but turns the index into the column of the two-dimensional matrix.
		/// </summary>
		/// <param name="index">Selected index</param>
		/// <returns>The column of the two-dimensional matrix</returns>
		public int GetCol(int index)
		{
			int row = index;
			int col = row % m_totNumOfCols;
			return col;
		}
		/// <summary>
		/// Creates an array and fills it with information based on the matrix, but it only takes vacant slots.
		/// </summary>
		/// <returns>An array with vacant seats.</returns>
		public string[] SeatsVacant()
		{
			int row, col;
			int count = 0;
			string[] vacantSeats = new string[m_totNumOfSeats]; //I do realize this way is essentially like taking your car to ride across your lawn
																//but I did try using an instance array and then simply refilling it based on what
			for (row = 0; row < m_totNumOfRows; row++)			//method was executed, but it didn't work. This, on the other hand, does.
			{
				for (col = 0; col < m_totNumOfCols; col++) 
				{
					if (string.IsNullOrEmpty(m_nameMatrix[row, col]))
					{
						vacantSeats[count++] = seatMatrix[row,col];
					}
						
					else
					{
						continue;
					}
				}
			}
			
			return vacantSeats;
		}
		/// <summary>
		/// Like the method above, it creates an array and fills it with seats based on the matrix, but this one fills it with reserved seats instead.
		/// </summary>
		/// <returns>An array with all reserved seats.</returns>
		public string[] SeatsReserved()
		{
			int row, col;
			int count = 0;
			string[] reservedSeats = new string[m_totNumOfSeats];
			
			for (row = 0; row < m_totNumOfRows; row++)
			{
				for (col = 0; col < m_totNumOfCols; col++) 
				{
					if (m_nameMatrix[row, col] != null)
					{
						reservedSeats[count++] = seatMatrix[row,col];
					}
						
					else
					{
						continue;
					}
				}
			}
			
			return reservedSeats;
		}
		
		/// <summary>
		/// Like the two previous methods, it fills an array based on the matrix, but this includes all seats.
		/// </summary>
		/// <returns>A one-dimensional array with all seats.</returns>
		public string[] SeatsAll()
		{
			int row, col;
			int count = 0;
			string[] allSeats = new string[m_totNumOfSeats];
			
			for (row = 0; row < m_totNumOfRows; row++)
			{
				for (col = 0; col < m_totNumOfCols; col++) 
				{
					allSeats[count++] = seatMatrix[row,col];
				}
			}
			return allSeats;
		}
		
		/// <summary>
		/// Count the amount of seats that are vacant, for the seat counter.
		/// </summary>
		/// <returns>Amount of vacant seats.</returns>
		public int CountSeats()
		{
			int seatCount = 0;
			for (int row = 0; row < m_totNumOfRows; row++)
			{
				for (int col = 0; col < m_totNumOfCols; col++) 
				{
					if (seatMatrix[row,col].Contains("Vacant"))
					    {
							seatCount++;
						}
					else
						continue;
				}
			}
			
			return seatCount;
		}
		
		/// <summary>
		/// Finds out if the selected position in the matrix has had a name assigned to it.
		/// </summary>
		/// <param name="index">Selected index</param>
		/// <returns>True or false</returns>
		public bool IsArrayEmpty(int index)
		{
			int row = GetRow(index);
			int col = GetCol(index);
			if (string.IsNullOrEmpty(m_nameMatrix[row,col]))
				return true;
			else 
				return false;					
		}
		
		/// <summary>
		/// Reserves a seat by changing a string to the info needed for display.
		/// </summary>
		/// <param name="name">Name of the occupant</param>
		/// <param name="priceString">Payment of the occupant</param>
		/// <param name="index">The one-dimensional index used for reserving.</param>
		public void ReserveSeat(string name, string priceString, int index)
		{
			int row = GetRow(index);
			int col = GetCol(index);
			string reserveString;

			m_nameMatrix[row, col] = name;
			m_priceMatrix[row, col] = priceString;
			
			reserveString = string.Format("{0,2}{1,4}\tOccupied by: {2,-10}{3,14}kr", row, col, m_nameMatrix[row,col], m_priceMatrix[row,col]);
			seatMatrix[row, col] = reserveString;
		}
		
		/// <summary>
		/// Cancels a seat by reverting it back to 'Vacant.'
		/// </summary>
		/// <param name="index">The index used to cancel</param>
		public void CancelSeat(int index)
		{
			int row = GetRow(index);
			int col = GetCol(index);
			string cancelString;
			
			m_nameMatrix[row,col] = null;
			m_priceMatrix[row, col] = null;
			
			cancelString = string.Format("{0,2}{1,4}{2,9}", row, col, "Vacant");
			seatMatrix[row, col] = cancelString;
		}
	}
}



This is beyond what I've encountered before, the debugger simply hasn't failed me up until this point. What can I do?

Is This A Good Question/Topic? 0
  • +

Replies To: Error if run without debugger

#2 Curtis Rutland  Icon User is offline

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


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: Error if run without debugger

Posted 16 April 2013 - 01:23 PM

Quote

It gives me a System.ArgumentNullException


Usually .NET errors will give you more information, like a stack trace. You should be able to get more than just the exception type, even if its an unhandled exception at runtime. Try giving us the stack trace, that might help a bit more.
Was This Post Helpful? 0
  • +
  • -

#3 breakdown  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 11-April 13

Re: Error if run without debugger

Posted 16 April 2013 - 04:22 PM

View PostCurtis Rutland, on 16 April 2013 - 01:23 PM, said:

Quote

It gives me a System.ArgumentNullException


Usually .NET errors will give you more information, like a stack trace. You should be able to get more than just the exception type, even if its an unhandled exception at runtime. Try giving us the stack trace, that might help a bit more.


I'm sorry, I haven't done that before. I looked around and, from my understanding, here's what you're looking for.

vid Assignment_3.SeatManager..ctor(Int32 totalRows, Int32 totalCols) i c:\Users\Krogen\Documents\SharpDevelop Projects\Assignment_4\Assignment_3\SeatManager.cs:rad 17
vid Assignment_3.MainForm..ctor() i c:\Users\Krogen\Documents\SharpDevelop Projects\Assignment_4\Assignment_3\MainForm.cs:rad 22
vid Assignment_3.InputUtility.Main(String[] args) i c:\Users\Krogen\Documents\SharpDevelop Projects\Assignment_4\Assignment_3\InputUtility.cs:rad 18


I added this in the field of SeatManager:
		System.Diagnostics.StackTrace stacktrace = new System.Diagnostics.StackTrace(true);
		string trace;


This to the constructor of that class:
			trace = stacktrace.ToString();


And finally this to one of the methods that seem to be causing the errors:
				System.Diagnostics.Debug.WriteLine(trace);

Was This Post Helpful? 0
  • +
  • -

#4 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3738
  • View blog
  • Posts: 13,067
  • Joined: 12-December 12

Re: Error if run without debugger

Posted 16 April 2013 - 05:05 PM

System.ArgumentNullException is quite specific: MSDN reference. So, for this line:

reservationsBox.Items.AddRange(m_seatMngr.SeatsVacant());

either m_seatMngr is null or SeatsVacant() returns null - most likely the second of these.

But, as mentioned, display the full content of the error message(s) that you receive.

This post has been edited by andrewsw: 16 April 2013 - 05:07 PM

Was This Post Helpful? 0
  • +
  • -

#5 breakdown  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 11-April 13

Re: Error if run without debugger

Posted 17 April 2013 - 05:08 AM

Full error. It's in swedish, but I don't think I can change that without reinstalling my OS

Information om att aktivera JIT-felsökning i stället för den 
här dialogrutan finns i slutet av det här meddelandet.

************** Undantagstext **************
System.ArgumentNullException: Värde får inte vara null.
Parameternamn: item
   vid System.Windows.Forms.ListBox.ObjectCollection.AddInternal(Object item)
   vid System.Windows.Forms.ListBox.ObjectCollection.AddRangeInternal(ICollection items)
   vid System.Windows.Forms.ListBox.ObjectCollection.AddRange(Object[] items)
   vid Assignment_3.MainForm.ShowComboSelectedIndexChanged(Object sender, EventArgs e) i c:\Users\Krogen\Documents\SharpDevelop Projects\Assignment_4\Assignment_3\MainForm.cs:rad 265
   vid System.Windows.Forms.ComboBox.onselectedIndexChanged(EventArgs e)
   vid System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
   vid System.Windows.Forms.ComboBox.WndProc(Message& m)
   vid System.Windows.Forms.Control.ControlNativewindow.OnMessage(Message& m)
   vid System.Windows.Forms.Control.ControlNativewindow.WndProc(Message& m)
   vid System.Windows.Forms.Nativewindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Inlästa sammansättningar **************
mscorlib
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
Assignment_4
    Sammansättningsversion: 1.0.4855.578
    Win32-version: 1.0.4855.578
    CodeBase: file:///C:/Users/Krogen/Documents/SharpDevelop%20Projects/Assignment_4/Assignment_3/bin/Debug/Assignment_4.exe
----------------------------------------
System.Windows.Forms
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
mscorlib.resources
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.1 (RTMRel.030319-0100)
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/mscorlib.resources/v4.0_4.0.0.0_sv_b77a5c561934e089/mscorlib.resources.dll
----------------------------------------
System.Configuration
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Windows.Forms.resources
    Sammansättningsversion: 4.0.0.0
    Win32-version: 4.0.30319.1 built by: RTMRel
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms.resources/v4.0_4.0.0.0_sv_b77a5c561934e089/System.Windows.Forms.resources.dll
----------------------------------------

************** JIT-felsökning **************
För att aktivera JIT-felsökning (just-in-time ) måste .config-filen för det här
tillämpningsprogrammet eller datorn (machine.config) ha 
jitDebugging-värdet angivet i avsnittet system.windows.forms.
Tillämpningsprogrammet måste också vara kompilerat med felsökning
aktiverat.

Till exempel:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

När JIT-felsökning är aktiverad kommer alla undantag som inte hanteras
att skickas till JIT-felsökaren som är registrerad på datorn
snarare än att hanteras av den här dialogrutan.




I also realize that it's saying the returned string array is null, but it still returns the array just fine with the debugger on. Compile without debugger, and there be exceptions.
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3650
  • View blog
  • Posts: 11,421
  • Joined: 05-May 12

Re: Error if run without debugger

Posted 17 April 2013 - 05:59 AM

Ah, that is more helpful. If you set breakpoints on lines 96 and 124 of SeatManager.cs, inspect what the value of count is. I suspect that count is less than m_totNumOfSeats.

For the minimal impact fix, I suggest using a List<string> within the functions, and then call ToArray() on the list to return an array with just enough entries.
Was This Post Helpful? 0
  • +
  • -

#7 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3650
  • View blog
  • Posts: 11,421
  • Joined: 05-May 12

Re: Error if run without debugger

Posted 17 April 2013 - 06:09 AM

For a better long term fix, I suggest dumping the 3 parallel 2-D arrays of strings, and actually using a class to keep the data together and using the correct data types for your model. Something like:
class Seat
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    public bool IsVacant
    {
        get { return String.IsNullOrEmpty(Name); }
    }
}

class SeatManager
{
    private Seat[,] _seatMatrix;
    :
}


Was This Post Helpful? 0
  • +
  • -

#8 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3650
  • View blog
  • Posts: 11,421
  • Joined: 05-May 12

Re: Error if run without debugger

Posted 17 April 2013 - 07:24 AM

Overall, I'm still puzzled as to why you would be getting the exception outside the debugger, but not within. Section 5.3.1 of the C# spec says that array elements will be initialized. So even if count is less than m_totNumOfSeats, they should have been filled with null's in both the debugger and non-debugger case, and should have caused an exception in both cases when AddRange() was called.

There is a special case on 64-bit Windows where exceptions are eaten when the exceptions are thrown during the window.Load event. If the code above was being called during the Load event, then there should have been no exception for both the debugger and non-debugger case.

Right now, the only thing I can think of is that you have a Debug build and a Release build, and in your Release build you have different behavior. Perhaps some bits of code mark with #if DEBUG, or [Conditional("DEBUG")]. In the debugger case, it is running the Debug build, and when outside the debugger, your are running the Release build.
Was This Post Helpful? 0
  • +
  • -

#9 breakdown  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 11-April 13

Re: Error if run without debugger

Posted 17 April 2013 - 01:20 PM

View PostSkydiver, on 17 April 2013 - 05:59 AM, said:

For the minimal impact fix, I suggest using a List<string> within the functions, and then call ToArray() on the list to return an array with just enough entries.


Is there an example of this somewhere? I've honestly never used a list or a ToArray class and, while the MSDN has helped a bit, I still haven't really figured out how to use the list/ToArray. This is what I've tried:

		public string[] SeatsReserved()
		{
			int row, col;
			int count = 0;
			string[] reservedSeats = new string[m_totNumOfSeats];
			System.Collections.Generic.List<int> list = new System.Collections.Generic.List<int>();
			
			
			for (row = 0; row < m_totNumOfRows; row++)
			{
				for (col = 0; col < m_totNumOfCols; col++) 
				{
					if (m_nameMatrix[row, col] != null)
					{
						list.Add(count);
						reservedSeats[count++] = seatMatrix[row,col];
					}
						
					else
					{
						continue;
					}
				}
			}
									foreach (int i in list) 
									{
										System.Diagnostics.Debug.WriteLine(list[i]);	
									}
									System.Diagnostics.Debug.WriteLine(trace);
			return reservedSeats;
		}
		


Quote

For a better long term fix, I suggest dumping the 3 parallel 2-D arrays of strings, and actually using a class to keep the data together and using the correct data types for your model. Something like:


Yeah, you're probably right, but I'm required to use arrays as a part of the exercise.

Quote

Right now, the only thing I can think of is that you have a Debug build and a Release build, and in your Release build you have different behavior. Perhaps some bits of code mark with #if DEBUG, or [Conditional("DEBUG")]. In the debugger case, it is running the Debug build, and when outside the debugger, your are running the Release build.


I didn't even know you could do an 'if DEBUG' operator. I've searched all my classes for the terms 'debug' and 'diagnostics' and I haven't discovered anything new.
Was This Post Helpful? 0
  • +
  • -

#10 Curtis Rutland  Icon User is offline

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


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: Error if run without debugger

Posted 17 April 2013 - 01:43 PM

Quote

I didn't even know you could do an 'if DEBUG' operator


Sidebar. Notice the syntax #if DEBUG. That # indicates a PreProcessor Directive. Basically this means that it's not really part of your code, it's instructions for the compiler on how to deal with your code (technically the #region/#endregion pair is instructions for your IDE and ignored by the compiler). It's a fairly advanced topic.

The DEBUG part is a symbol that is automatically defined by your IDE when you're building under a Debug build. If you switch to Release, or create your own build definition that explicitly does not include the DEBUG constant, it will not be defined, and thus will not test to true.
Was This Post Helpful? 0
  • +
  • -

#11 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3650
  • View blog
  • Posts: 11,421
  • Joined: 05-May 12

Re: Error if run without debugger

Posted 17 April 2013 - 10:15 PM

Something like this:
var list = new List<string>()
for(int i = 0; i < 10; i++)
{
    string s = String.Format("Entry #{0}", i + 1);
    list.Add(s);
}
var arr = list.ToArray();
for(int j = 0; j < arr.Length; j++)
{
    Console.WriteLine(arr[j]);
}


Was This Post Helpful? 0
  • +
  • -

#12 breakdown  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 19
  • Joined: 11-April 13

Re: Error if run without debugger

Posted 26 April 2013 - 05:09 AM

I got this solved with some help, it turns out that .AddRange cannot accept null values, so I had to change it to .Add and apply a foreach loop.
Was This Post Helpful? 0
  • +
  • -

#13 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3650
  • View blog
  • Posts: 11,421
  • Joined: 05-May 12

Re: Error if run without debugger

Posted 26 April 2013 - 06:13 AM

That still doesn't explain how you ended up with null values outside the debugger, but not have null values when running in the debugger. There is still something different between the two runtime environments.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1