• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3489
  • Last Modified:

Error: "The type initializer for '...' threw an exception."

I am writing my first application in C# and I'm trying to set up an import from excel to sql. Here is what I have:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace FirstSQLApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string ExcelPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(this.GetType()).Location) + "\\Holdings.xls";
            DataTable table = App_Code.Bal.getDataFromXLS(ExcelPath, "Holdings$", "[Asset Code],[Fund Number],[Cusip],[Security Name],[Shares],[Market Value],[Cost]");
        }
    }
}



using System;
using System.Data;

namespace FirstSQLApp.App_Code
{
    public class Bal
    {
        public static DataTable getDataFromXLS(string path, string sheet, string headers)
        {
            return Dal.getDataFromXLS(path, sheet, headers);
        }
        public static void getDataFromXLSAndCopy(string path, string sheet, string headers)
        {
            Dal.getDataFromXLSAndCopy(path, sheet, headers);
        }
        public static int InsertHolding(DataTable t)
        {
            return Dal.InsertHolding(t);
        }
    }
}




using System;
using System.Data;
using System.Configuration;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Web;

/// <summary>
/// Summary description for Dal
/// </summary>
public class Dal
{

    #region "Fields"

    static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["FundamentalConnectionString"].ConnectionString;

    #endregion

    public static DataTable getDataFromXLS(string path, string sheet, string headers)
    {
        try
        {
            string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=" + path + ";" + "Extended Properties=" + (char)34 + "Excel 8.0;HDR=Yes;IMEX=1;" + (char)34;

            OleDbConnection cnCSV = new OleDbConnection(strConnectionString);
            cnCSV.Open();
            OleDbCommand cmdSelect = new OleDbCommand(@"SELECT " + headers + " FROM [" + sheet + "]", cnCSV);
            OleDbDataAdapter daCSV = new OleDbDataAdapter();
            daCSV.SelectCommand = cmdSelect;
            DataTable dtCSV = new DataTable();
            daCSV.Fill(dtCSV);
            cnCSV.Close();
            daCSV = null;
            return dtCSV;
        }
        catch (Exception ex)
        {
            string message = ex.Message;
            return null;
        }
    }

    public static void getDataFromXLSAndCopy(string path, string sheet, string headers)
    {
        try
        {
            string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=" + path + ";" + "Extended Properties=" + (char)34 + "Excel 8.0;HDR=Yes;IMEX=1;" + (char)34;

            // Create Connection to Excel Workbook
            using (OleDbConnection connection = new OleDbConnection(strConnectionString))
            {
                OleDbCommand command = new OleDbCommand(@"SELECT " + headers + " FROM [" + sheet + "]", connection);
                connection.Open();
                // Create DbDataReader to Data Worksheet
                using (DbDataReader dr = command.ExecuteReader())
                {
                    // SQL Server Connection String
                    //string sqlConnectionString = "Data Source=.;  Initial Catalog=Test;Integrated Security=True";
                    string sqlConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Documents and Settings\thayes\Desktop\FirstSQLApp\FirstSQLApp\App_Data\Fundamental.mdf";Integrated Security=True;User Instance=True";
                    // Bulk Copy to SQL Server
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
                    {
                        bulkCopy.DestinationTableName = "FUND_Holdings";
                        bulkCopy.WriteToServer(dr);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string message = ex.Message;
            //return null;
        }
    }
    public static int InsertHolding(DataTable t)
    {
        int newID = 0;
        try
        {
            using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
            {
                using (SqlCommand command = new SqlCommand("FUND_InsertHolding", sqlConnection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    sqlConnection.Open();
                    SqlParameter pramAssetCode = command.Parameters.Add(new SqlParameter("@AssetCode", SqlDbType.VarChar));
                    SqlParameter pramFundNumber = command.Parameters.Add(new SqlParameter("@FundNumber", SqlDbType.Float));
                    SqlParameter pramCusip = command.Parameters.Add(new SqlParameter("@Cusip", SqlDbType.VarChar));
                    SqlParameter pramSecurityName = command.Parameters.Add(new SqlParameter("@SecurityName", SqlDbType.VarChar));
                    SqlParameter pramShares = command.Parameters.Add(new SqlParameter("@Shares", SqlDbType.Float));
                    SqlParameter pramMarketValue = command.Parameters.Add(new SqlParameter("@MarketValue", SqlDbType.Float));
                    SqlParameter pramCost = command.Parameters.Add(new SqlParameter("@Cost", SqlDbType.Float));
                    SqlParameter outPram = command.Parameters.Add("@HoldingsID", SqlDbType.Int);
                    outPram.Direction = ParameterDirection.Output;
                    foreach (DataRow row in t.Rows)
                    {
                        pramAssetCode.Value = row["Asset Code"];
                        pramFundNumber.Value = row["Fund Number"];
                        pramCusip.Value = row["Cusip"];
                        pramSecurityName.Value = row["Security Name"];
                        pramShares.Value = row["Shares"];
                        pramMarketValue.Value = row["Market Value"];
                        pramCost.Value = row["Cost"];
                        command.ExecuteNonQuery();
                        newID = Convert.ToInt32(command.Parameters["@HoldingsID"].Value);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            newID = 0;
            string message = ex.Message;
        }
        return newID;
    }
}


I am getting an error at "return Dal.getDataFromXLS(path, sheet, headers);" in class 'Bal'

The error states:
The type initializer for 'Dal' threw an exception.
0
tiehaze
Asked:
tiehaze
1 Solution
 
Bob LearnedCommented:
That means when the class is initialized to process the method, there was an exception.  My guess would be that it had a problem getting the connection string.

Bob
0
 
jsakhtarCommented:
You need to know what the inner exception was.

But, one thing i see is

string ExcelPath = System.IO.Path.Combine(Application.StartupPath, "Holdings.xls");

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

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now