?
Solved

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

Posted on 2007-10-15
3
Medium Priority
?
3,334 Views
Last Modified: 2013-12-17
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
Comment
Question by:tiehaze
2 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20079360
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
 
LVL 3

Accepted Solution

by:
jsakhtar earned 2000 total points
ID: 20106953
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

Featured Post

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

579 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