Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this error: The ConnectionString property has not been initialized

I have searched and tried everything but can't figure this one out. I am trying to do something simple but it seems as though I am doing something wrong. Basically, any user that has made a deposit, I want to return true, if they have not, I want to return false. This should be easy I suppose but I am stumped on this.

Here is the error:

The ConnectionString property has not been initialized.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The ConnectionString property has not been initialized.

Source Error:

Line 59:         Cmd.Parameters.AddWithValue("@UserID", userId);
Line 60:         con.Open();
Line 61: 
Line 62:         result = (int)Cmd.ExecuteScalar();

Here is the top of the stack trace:

[InvalidOperationException: The ConnectionString property has not been initialized.] System.Data.SqlClient.SqlConnection.PermissionDemand() +4879939 System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122

Here is my method for returning true or false:

public static bool HasDeposit(int userId)
{
    int result = 0;
    //since executeScalar is intended to retreive only a single value
    //from a query, we select the number of results instead of the email address
    //of each matching result.
    string queryTransaction = "SELECT COUNT(UserID) FROM Transaction WHERE TransactionTypeID = 6 AND UserID = @UserID";
    string constr = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
    SqlConnection con = new SqlConnection(constr);

    SqlCommand Cmd = new SqlCommand(queryTransaction, con);

    Cmd.Parameters.AddWithValue("@UserID", userId);
    con.Open();

    result = (int)Cmd.ExecuteScalar();

    //returning a boolean comparator works like this :
    //will return true if the result is greater than zero, but false if it is not.
    con.Close();
    return result > 0;
}

Any help / guidance on this would be much appreciated.

like image 453
thenextmogul Avatar asked Aug 17 '13 01:08

thenextmogul


People also ask

What is ConnectionString property?

The value of the ConnectionString property is a connection string that includes the source database name and the parameters you need to establish the connection. The default value of the ConnectionString property is an empty string. The Server attribute is mandatory in all situations.

How do I add ConnectionString to .NET core?

The connection string should be added to your application's App. config file (Web. config if you are using ASP.NET). If your connection string contains sensitive information, such as username and password, you can protect the contents of the configuration file using Protected Configuration.

Where do I put ConnectionString in web config?

config file in the Views folder.) Find the <connectionStrings> element: Add the following connection string to the <connectionStrings> element in the Web.


2 Answers

If you have your connection strings in your configuration like this

<connectionStrings>
    <add name="ConnectionString" connectionString="data source=.;Initial Catalog=MyDatabase;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>

Then you will need to use this method to access it System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString

You should also wrap your data access in using statements so that you don't leak connections and flood the pool. Here's an updated example with using statements.

public static bool HasDeposit(int userId)
{
    //since executeScalar is intended to retreive only a single value
    //from a query, we select the number of results instead of the email address
    //of each matching result.
    const string queryTransaction = "SELECT COUNT(UserID) FROM Transaction WHERE TransactionTypeID = 6 AND UserID = @UserID";

    var constr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    using (var con = new SqlConnection(constr))
    {
        using (var cmd = new SqlCommand(queryTransaction, con))
        {
            cmd.Parameters.AddWithValue("@UserID", userId);
            con.Open();

            var result = (int)cmd.ExecuteScalar();

            //returning a boolean comparator works like this :
            //will return true if the result is greater than zero, but false if it is not.
            return result > 0;
        }
    }
}
like image 91
Kane Avatar answered Sep 26 '22 23:09

Kane


In web.config :

<appSettings>
    <add key="ConnectionString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
</appSettings>
like image 37
Samiey Mehdi Avatar answered Sep 22 '22 23:09

Samiey Mehdi