Solved

Type initializer for class threw an exception

Posted on 2012-03-16
11
2,538 Views
Last Modified: 2012-04-04
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
0
Comment
Question by:skyzipper
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37731663
Does the mainapplicaiton class have any static constructors, properties, or fields? Perhaps you are getting an exception when one of those members is accessed.
0
 
LVL 34

Expert Comment

by:sarabande
ID: 37732408
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
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 37732645
If you look at the full stack trace, there should be an inner exception, that would give you a clue to the real exception.
0
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37732689
@sarabande
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++)   = )
0
 

Author Comment

by:skyzipper
ID: 37737456
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
    }
}
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37737498
Is it possible to show the Users class as well?
0
 

Author Comment

by:skyzipper
ID: 37738840
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
    }
}
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37738869
I was going by what I saw here:

public static users systemUsers = new users();

Open in new window


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?
0
 

Author Comment

by:skyzipper
ID: 37742314
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();
        }

        #endregion

    }
}
0
 

Accepted Solution

by:
skyzipper earned 0 total points
ID: 37742406
I found the problem, by using e.innerexception.  It was a database issue.  The Oracle driver  the previous developer was using was not the same as the one i normally use.  I will let you know if i can get it solved.
0
 

Author Closing Comment

by:skyzipper
ID: 37805109
I found the answer to my own question.  It was unrelated to any of the answers provided.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Consume a webservice via VB in Visual Studio 2015 3 45
SSIS GUID Variable 2 57
Installing .NET 3.5 on Windows Server 2012 1 93
Nested forach loop to linq 3 43
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question