Hello experts,
I am trying to debug and application built with c#, and I am not that familiar with the language. Â The application was built with 2005 and I upgraded to 2008. Â I keep getting this error: Â The type initializer for 'class name here' threw an exception. Â Is this because I am missing a call to a new constructor? Â Like I said not very familiar with c# most of the stuff i have worked with was in vb.net. Â Also could upgrading from 2005 to 2008 cause issues?
I have included a screen shot. Â UI.mainApplication.loggedInUser = arg[0]; Â is where the program is stopping. program-error.jpg
Microsoft Development.NET ProgrammingVisual C++.NET
Last Comment
skyzipper
8/22/2022 - Mon
kaufmed
Does the mainapplicaiton class have any static constructors, properties, or fields? Perhaps you are getting an exception when one of those members is accessed.
sarabande
you try to access UI.mainApplication object at a time where the UI is not established.
if you comment the statement or save the argv[0] (what is the program name and not the username) to a member of your application class rather than to the ui part it shouldwork.
Sara
Bob Learned
If you look at the full stack trace, there should be an inner exception, that would give you a clue to the real exception.
you try to access UI.mainApplication object at a time where the UI is not established.
It looks to me that loggedInUser is a static property, so it would be accessible. If it were not a static property, then skyzipper would be trying to access an instance property by way of the class name, and  he would have a compile-time error, not a run-time error.
...the argv[0] (what is the program name and not the username)
Not in .NET (well, at least in C# and VB.NET... not sure about managed C++) Â = )
skyzipper
ASKER
Here is the mainApplication class, Â i thought the code above was trying to set a property.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HDS.UI_todo;
namespace HDS.UI
{
  /// <summary>
  /// Contains the main application controls and
  /// global application information
  /// </summary>
  public partial class mainApplication : Form
  {
    #region Events
    /// <summary>
    /// Ocurrs when a user begins a logout procedure
    /// </summary>
    public static event EventHandler LoggedOut;
    #endregion
    #region Delegates
    public delegate void addControlToForm(Control c);
    public delegate void zeroArgDelegate();
    #endregion
    #region Static Fields
    //user who's logged in
    public static string loggedInUser = null;
    //TODO - not needed
    public static users systemUsers = new users();
    #endregion
    #region Fields
    private static bool exitPlease;
    #endregion
    #region Constructors
    public mainApplication()
    {
      InitializeComponent();
      LoggedOut += new EventHandler(mainApplication_LoggingOut);
    }
    #endregion
    #region Methods
    //adds a control to the main empty area of the mainApplication
    public void addControlToMainApplication(Control c)
    {
      c.Dock = DockStyle.Fill;
      c.AutoSize = true;
      mainAppPanel.Controls.Clear();
      mainAppPanel.Controls.Add(c);
    }
    //TODO - can remove - not needed
    public static bool login(String loginID, String password)
    {
      if (loggedInUser != null)
      {
        return false;
      }
      user tmp = systemUsers.getUser(loginID);
      if (tmp == null)
      {
        return false;
      }
      if (tmp.role == user.UserRole.ADMINISTRATOR && password.Equals(""))
      {
        throw (new userPasswordRequiredException());
      }
      if (tmp.login(password))
      {
        //loggedInUser = tmp;
        return true;
      }
      return false;
    }
    //TODO - can remove - not needed
    public static void logout()
    {
      loggedInUser = null;
      if (LoggedOut != null)
        LoggedOut(null, new EventArgs());
    }
    public void showLoginForm()
    {
      loginForm lf = new loginForm();
      lf.Disposed += new EventHandler(lf_Disposed);
      lf.ShowDialog();
    }
    #endregion
    #region Properties
    public static bool ExitPlease
    {
      get { return exitPlease; }
      set { exitPlease = value; }
    }
    #endregion
    #region Event Handler
    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
      (new AboutBox()).Visible = true;
    }
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
      ExitPlease = true;
      Application.Exit();
    }
    //TODO -- can remove - login not needed
    //user has logged in -- show them their application
    void lf_Disposed(object sender, EventArgs e)
    {
      testingContainerControl tcc = new testingContainerControl();
      addControlToForm actf = new addControlToForm(addControlToMainApplication);
      administrateControl a = new administrateControl();
      if (loggedInUser == null)
      {
        zeroArgDelegate zad = new zeroArgDelegate(this.Dispose);
        zad();
        return;
      }
      /*switch (loggedInUser.role)
      {
        case user.UserRole.ADMINISTRATOR:
          this.Invoke(actf, new Object[] { a });
          exitToolStripMenuItem.Enabled = true;
          break;
        case user.UserRole.QAAGENT:
          this.Invoke(actf, new Object[] { tcc });
          exitToolStripMenuItem.Enabled = false;
          tcc.restartTests();
          break;
      }*/
    }
    //TODO - needs to be modified
    private void mainApplication_FormClosing(object sender, FormClosingEventArgs e)
    {
      if (!ExitPlease)
        e.Cancel = true;
    }
    private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
    {
      mainApplication.logout();
    }
    private void mainApplication_Load(object sender, EventArgs e)
    {
      //TODO EBC update - showLoginForm();
      testingContainerControl tcc = new testingContainerControl();
      addControlToForm actf = new addControlToForm(addControlToMainApplication);
      this.Invoke(actf, new Object[] { tcc });
     Â
      tcc.restartTests();
    }
    private void mainApplication_LoggingOut(object sender, EventArgs e)
    {
      mainAppPanel.Controls.Clear();
      showLoginForm();
    }
    #endregion
  }
}
There is a user and users class, Â I only see the call for the user class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace HDS
{
  public class user
  {
    #region Fields
    private String FirstName;
    private String LastName;
    private String LoginID;
    internal String Password;
    private UserRole Role;
    #endregion
    #region Enums
    public enum UserRole { ADMINISTRATOR = 0, QAAGENT = 1 };
    #endregion
    #region Constructors
    public user()
    {
      firstName = "";
      lastName = "";
      loginID = "";
      password = "";
      role = user.UserRole.QAAGENT;
    }
    public user(String loginID)
      : this()
    {
      this.loginID = loginID;
    }
    public user(String loginID, String password)
      : this(loginID)
    {
      this.password = password;
    }
    public user(String loginID, String password, UserRole role)
      : this(loginID, password)
    {
      this.role = role;
    }
    public user(String firstName, String lastName, String loginID, String password, user.UserRole role)
      : this(loginID, password, role)
    {
      this.firstName = firstName;
      this.lastName = lastName;
    }
    #endregion
    #region Properties
    public String firstName
    {
      get
      {
        return FirstName;
      }
      set
      {
        FirstName = value;
      }
    }
    public String lastName
    {
      get
      {
        return LastName;
      }
      set
      {
        LastName = value;
      }
    }
    public String loginID
    {
      get
      {
        return LoginID;
      }
      set
      {
        LoginID = value;
      }
    }
    public String password
    {
      get
      {
        return Password;
      }
      set
      {
        MD5 crypto = new MD5CryptoServiceProvider();
        System.Text.ASCIIEncoding asciiEncoding = new ASCIIEncoding();
        Password = System.Convert.ToBase64String(crypto.ComputeHash(asciiEncoding.GetBytes(value)));
      }
    }
    public UserRole role
    {
      get
      {
        return Role;
      }
      set
      {
        Role = value;
      }
    }
    #endregion
    #region Methods
    public override bool Equals(object obj)
    {
      bool objIsEqual = false;
      if (obj is user)
      {
        user objToTest = (user)obj;
        if (objToTest.loginID == this.loginID)
        {
          objIsEqual = true;
        }
        else
        {
          objIsEqual = false;
        }
      }
      else
      {
        objIsEqual = false;
      }
      return objIsEqual;
    }
    public bool login(String passwd)
    {
      MD5 crypto = new MD5CryptoServiceProvider();
      System.Text.ASCIIEncoding asciiEncoding = new ASCIIEncoding();
      return password.Equals(System.Convert.ToBase64String(crypto.ComputeHash(asciiEncoding.GetBytes(passwd))));
    }
    #endregion
  }
}
Not to say I didn't overlook anything, but that's the only line I could see that could cause an error (based on how your class is written). I'm not certain it is in error, but since it's the only static variable for which I can't tell what's going on behind the scenes, I wondered what that constructor might be doing.
I believe what you posted is the user class (singular), correct?
skyzipper
ASKER
Yes, i will post the users class as well. Â How do i get the full exception? Â I know in vb.net i could use e.message to get a shorten string, or e.tostring to get the full message.
Here is my c# try/catch, they both give the same error.
  try
      {
      Â
        Â
        UI.mainApplication.loggedInUser = args[0];
      }
      catch (Exception e) {
        MessageBox.Show(e.Message.ToString());
        MessageBox.Show(e.Message);
      }
Users class:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Oracle.DataAccess.Client;
using System.Data;
using System.Windows.Forms;
namespace HDS
{
  /// <summary>
  /// manages accessing the list of users in the database. provides some login services
  /// </summary>
  public class users : IEnumerable<user>
  {
    #region Fields
    private OracleConnection oc = new OracleConnection(dbConnectionInfo.ConnStr);
    #endregion
    #region Constructors
    public users()
    {
      /*addUser(new user("test", "last", "testme2", "12345", user.ADMINISTRATOR));
      addUser(new user("test", "last", "dman", "", user.QAAGENT));*/
    }
    #endregion
    #region Methods
    public void addUser(user u)
    {
      oc.Open();
      OracleCommand ocomm = new OracleCommand("SELECT count(*) FROM users WHERE loginID = :login", oc);
      ocomm.Parameters.Add(new OracleParameter("login", OracleDbType.Varchar2)).Value = u.loginID;
      OracleDataAdapter oda = new OracleDataAdapter(ocomm);
      DataSet ds = new DataSet();
      oda.Fill(ds);
      if (!(ds.Tables[0].Rows[0][0].Equals((decimal)0)))
      {
      }
      else
      {
        //add a user
        OracleCommand ocommIns = new OracleCommand("INSERT INTO users (FIRSTNAME, LASTNAME, LOGINID, PASSWORD, ROLE) VALUES(:firstname, :lastname, :loginid, :password, :role)", oc);
        ocommIns.Parameters.Add(new OracleParameter("firstname", OracleDbType.Varchar2)).Value = u.firstName;
        ocommIns.Parameters.Add(new OracleParameter("lastname", OracleDbType.Varchar2)).Value = u.lastName;
        ocommIns.Parameters.Add(new OracleParameter("loginid", OracleDbType.Varchar2)).Value = u.loginID;
        ocommIns.Parameters.Add(new OracleParameter("password", OracleDbType.Varchar2)).Value = u.password;
        ocommIns.Parameters.Add(new OracleParameter("role", OracleDbType.Int32)).Value = u.role;
        ocommIns.ExecuteNonQuery();
      }
      oc.Close();
    }
    public bool contains(String loginID)
    {
      //get selected user and return
      return !(getUser(loginID) == null);
    }
    public user getUser(String loginID)
    {
      //get selected user and return
      OracleCommand ocomm = new OracleCommand("SELECT * FROM users WHERE LOGINID = :login", oc);
      ocomm.Parameters.Add(new OracleParameter("login", OracleDbType.Varchar2)).Value = loginID;
      OracleDataAdapter oda = new OracleDataAdapter(ocomm);
      DataSet ds = new DataSet();
      oda.Fill(ds);
      if (ds.Tables[0].Rows.Count == 0)
      {
        oc.Close();
        return null;
      }
      DataRow dr = ds.Tables[0].Rows[0];
      user retVal = new user();
      retVal.firstName = dr["FIRSTNAME"].ToString();
      retVal.lastName = dr["LASTNAME"].ToString();
      retVal.loginID = dr["LOGINID"].ToString();
      retVal.Password = dr["PASSWORD"].ToString();
      retVal.role = (user.UserRole)(int)(decimal)dr["ROLE"];
      oc.Close();
      return retVal;
    }
    public void removeUser(String loginID)
    {
      //remove selected user
      oc.Open();
      OracleCommand ocomm = new OracleCommand("DELETE FROM users WHERE loginID = :login", oc);
      ocomm.Parameters.Add(new OracleParameter("login", OracleDbType.Varchar2)).Value = loginID;
      ocomm.ExecuteNonQuery();
      oc.Close();
    }
    public void updateUser(user u)
    {
      oc.Open();
      OracleCommand ocomm = new OracleCommand("SELECT count(*) FROM users WHERE loginID = :login", oc);
      ocomm.Parameters.Add(new OracleParameter("login", OracleDbType.Varchar2)).Value = u.loginID;
      OracleDataAdapter oda = new OracleDataAdapter(ocomm);
      DataSet ds = new DataSet();
      oda.Fill(ds);
      if ((ds.Tables[0].Rows[0][0].Equals((decimal)1)))
      {
        //update user
        OracleCommand ocommIns = new OracleCommand("UPDATE users set FIRSTNAME=:firstname, LASTNAME=:lastname, PASSWORD=:password, ROLE=:role WHERE loginID = :loginid", oc);
        ocommIns.Parameters.Add(new OracleParameter("firstname", OracleDbType.Varchar2)).Value = u.firstName;
        ocommIns.Parameters.Add(new OracleParameter("lastname", OracleDbType.Varchar2)).Value = u.lastName;
        ocommIns.Parameters.Add(new OracleParameter("password", OracleDbType.Varchar2)).Value = u.password;
        ocommIns.Parameters.Add(new OracleParameter("role", OracleDbType.Int32)).Value = u.role;
        ocommIns.Parameters.Add(new OracleParameter("loginid", OracleDbType.Varchar2)).Value = u.loginID;
        ocommIns.ExecuteNonQuery();
      }
      oc.Close();
    }
    #endregion
    #region IEnumerable Members
    public IEnumerator<user> GetEnumerator()
    {
      //enumerate users
      //get selected user and return
      OracleCommand ocomm = new OracleCommand("SELECT * FROM users", oc);
      OracleDataAdapter oda = new OracleDataAdapter(ocomm);
      DataSet ds = new DataSet();
      oda.Fill(ds);
      oc.Close();
      DataRowCollection drc = ds.Tables[0].Rows;
      foreach (DataRow dr in drc)
      {
        user retVal = new user();
        retVal.firstName = dr["FIRSTNAME"].ToString();
        retVal.lastName = dr["LASTNAME"].ToString();
        retVal.loginID = dr["LOGINID"].ToString();
        retVal.Password = dr["PASSWORD"].ToString();
        retVal.role = (user.UserRole)(int)(decimal)dr["ROLE"];
        yield return retVal;
      }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }