Showing posts with label initialized. Show all posts
Showing posts with label initialized. Show all posts

Thursday, March 22, 2012

ConnectionString property not initialized

I am getting an error message that says that my connection string has not been intialized I have initialized it.

Dim AirliquidiConnAsNew SqlClient.SqlConnection(ConfigurationManager.AppSettings("AirliquidiDatabase"))

Any suggestions??

Check out this article on using the connectionStrings element in the configuration file. Good luck!

http://weblogs.asp.net/jgaylord/archive/2005/05/12/406639.aspx

|||

with that line you've only created a connection instance, but have not initialized it. You'll need to actually use it before it will work now.

here's what you need to do. You need to add a "using" statement to the code and handle the data retrieval inside of it.

Dim connString As String = _
ConfigurationManager.ConnectionStrings(connStringName).ConnectionString

'Create a SqlConnection instance
Using myConnection As New SqlConnection(connString)
'Specify the SQL query
Const sql As String = "SELECT * FROM Customers"

'Create a SqlCommand instance
Dim myCommand As New SqlCommand(sql, myConnection)

'Get back a DataSet
Dim myDataSet As New DataSet

'Create a SqlDataAdapter instance
Dim myAdapter As New SqlDataAdapter(myCommand)
myAdapter.Fill(myDataSet)

'Bind the DataSet to the GridView
gvCustomers.DataSource = myDataSet
gvCustomers.DataBind()

'Close the connection
myConnection.Close()
End Using

You can visit http://aspnet.4guysfromrolla.com/articles/110905-1.aspx for a more thorough explanation (the page I got this code from)

|||I have this information in my web.config|||

This is what I have. Would I be putting a using statement in the Page_Load?

ProtectedSub Button1_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles Button1.Click

Dim connAirliquidiAsNew SqlClient.SqlConnection(ConfigurationManager.AppSettings("AirliquidiDatabase"))

Dim cmdInsertLoginAsNew SqlClient.SqlCommand("Insert into Logins(ID, Username, LoginDate) values (@.ID, @.Username,@.LoginDate)", connAirliquidi)

Dim activeUserAsString

Dim IDAs Guid = System.Guid.NewGuid

Dim cmdCheckUserCredentialsAsNew SqlClient.SqlCommand("select * From Usernames where(username=@.username and password=@.password)", connAirliquidi)

'If user did not fill in a username or password

If txtUsername.Text =""Or txtPassword.Text =""Then

Message("Please fill in a username/password")

Else

Try

connAirliquidi.Open()

cmdCheckUserCredentials.Parameters.AddWithValue("@.Username", Trim(txtUsername.Text))

cmdCheckUserCredentials.Parameters.AddWithValue("@.password", Trim(txtPassword.Text))

SelectCase activeUser

CaseTrue

cmdInsertLogin.Parameters.AddWithValue("@.ID", ID)

cmdInsertLogin.Parameters.AddWithValue("@.Username", Trim(txtUsername.Text))

cmdInsertLogin.Parameters.AddWithValue("@.LoginDate",Date.Now())

Session("Username") = Trim(txtUsername.Text)

FormsAuthentication.SetAuthCookie(txtUsername.Text,False)

Session("ID") = ID.ToString

Response.Redirect("ALSI.aspx?ID={" & ID.ToString &"}")

CaseFalse

Message("Inactive user")

CaseElse

Message("Invalid Username and/or Password")

EndSelect

Catch exAs Exception

Message("Error authenticating user. Please try again.")

Finally

connAirliquidi.Close()

EndTry

EndIf

EndSub

|||

you have to open the connection before you use the sql command. moveconnAirliquidi.Open() directly below this line

Dim connAirliquidiAsNew SqlClient.SqlConnection(ConfigurationManager.AppSettings("AirliquidiDatabase"))

which also means you'll have to move the connAirliquidi.close() down to directly above the End Sub line.

|||

I did that and I am still getting the same error message.

|||Can you post a snap from your web.config file where you've actually declared the connection string ?|||<configuration>

<appSettings>

<addkey="customerservice"value="abetha@.airsep.com"/>

<addkey="smtpserver"value=""/>

<addkey="AirliquidiConn"value="Airliquidi id=**;data source=SEPSQL;persist security info=True;initial catalog=Usernames;password=****"/>

</appSettings>

<connectionStrings>

<addname="AirliquidiConn"connectionString="Data Source=SEPSQL;Database=Airliquidi;User ID=**;Password=*****"

providerName="System.Data.SqlClient" />

</connectionStrings>

|||

Correct me if I'm wrong but in your earlier posts you've written the name of your connection string to be "AirliquidiDatabase" and you've set it to be used from appSettings. Now, the snap you've posted is not having a connection string with the name you might be using in your code. Both the connection strings that you've set in your config file are named "AirliquidiConn".

|||

Thank you for catching that. I have changed it to AirliquidiConn and I am still getting the same error.

ConnectionString property has not been initialized

My IT dept set up an SQL db on a server for me and I am connected to it through a port. They told me I had to create my tables through an MS Access adp, which I have done. I am using VWD Express and am trying to create a login page using usernames and pw's from a db table. I am connected (at least the db Explorer tab shows I am) to the MS Access adp and can drop a GridView from my Employees table from it onto a page and get results. I keep getting the "ConnectionString property not initialized" error message pointing to my sqlConn.Open() statement and cannot figure out why. I have looked at hundreds of posts but can't seem to find anything that works. If someone could point me to some post or website that could explain connecting to a SQL db through a port or whatever you think I need to learn to get this fixed I would appreciate it.
Web config:

<configurationxmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

<appSettings/>

<connectionStrings>

<addname="ASPNETDB"connectionString="Description=Training;DRIVER=SQL Server;SERVER=USAWVAS27;UID=usx14611;APP=Microsoft? Visual Studio? 2005;WSID=983QD21;Network=DBMSSOCN;Address=USAWVAS27,3180;Trusted_Connection=Yes"providerName="System.Data.Odbc"/>

</connectionStrings>

<system.web>

<authenticationmode="Forms" />

<authorization>

<denyusers="?" />

</authorization>

<customErrorsmode="Off" />

</system.web>

</configuration>
My login.aspx page

<%@.PageLanguage="VB"debug="true"%>

<%@.ImportNamespace="System.Data.SqlClient" %>

<%@.ImportNamespace="System.Configuration.ConfigurationManager" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<scriptrunat="server">

ProtectedSub LoginUser(ByVal sAsObject,ByVal eAs EventArgs)

Dim blnAuthenticateAsBoolean = Authenticate(username.Text, password.Text)

If blnAuthenticateThen

FormsAuthentication.RedirectFromLoginPage(username.Text,False)

EndIf

EndSub

Function Authenticate(ByVal strUsernameAsString,ByVal strPasswordAsString)AsBoolean

Dim strConnectionAsString = ConfigurationManager.AppSettings("ASPNETDB")

Tried this code as well
Dim sqlConn As New SqlConnection(ConfigurationManager.AppSettings("ASPNETDB"))

Dim sqlConnAsNew SqlConnection(strConnection)

Dim sqlCmdAs SqlCommand

Dim sqlDRAs SqlDataReader

Dim userFoundAsBoolean

sqlCmd =New SqlCommand("SELECT * FROM Employees " & _

"WHERE username='" & strUsername &" ' AND password='" & strPassword &"'", sqlConn)

sqlConn.Open()

sqlDR = sqlCmd.ExecuteReader()

userFound = sqlDR.Read()

sqlDR.Close()

Return userFound

EndFunction

</script>

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<p>Username:<asp:TextBoxID="username"runat="server"></asp:TextBox><br/>

<br/>

<p>Password:<asp:TextBoxID="password"runat="server"></asp:TextBox><br/>


<br/>

<asp:ButtonID="btnSubmit"runat="server"Text="Login"OnClick="LoginUser"/> </div>

</form>

</body>

</html>
Thanks

Still trying to figure this out. I can't believe that there isn't some resource(book, website..) out their that explains these types of errors. My IT dept insists that the database was set up correctly to allow me to use a table with usernames and pw's to build a login page but no matter what I try I get the same message. There doesn't seem to be any reason whatsoever for it to not work. I'm not even getting errors when I debug, just when I enter a login/password onto my login.aspx page and submit.
I removed my database connection and reconnected which gave me this as a new connection string:

<connectionStrings>

<addname="connString"connectionString="Data Source=USAWVAS27;Initial Catalog=MaterialsTraining;Integrated Security=False"/>

</connectionStrings>
Anybody have any ideas?
Thanks,
Toni

|||I haven't done this in VB, but here's what I think it should be based on how C# does it.
Looks like this:

Dim strConnectionAsString = ConfigurationManager.AppSettings("ASPNETDB")

Should be this:

Dim strConnectionAsString = ConfigurationManager.ConnectionStrings("ASPNETDB").ConnectionString

|||

Finally got this figured out so thought I'd share it. Thanks to those who responded with suggestions. It didn't like "DRIVER" and "Description" in my original system generated connection string, I'm assuming because it is an SQL database (?)
<connectionStrings>

<addname="ASPNETDB"connectionString="DataSource=Training;server=USAWVAS27;wsid=983QD21;network=DBMSSOCN;address=USAWVAS27,3180;trusted_connection=Yes"/>

</connectionStrings>

|||Hello, am getting a similar problem to the one you had. But I stilldon't know how to fix it. I only get the error when am runnign thelogin.It says the conn is not initialized. It's been giving me aheadache for 2 days now. Please help if possible
Protected Sub loginBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles loginBtn.Click
Dim strConnection As String = ConfigurationManager.AppSettings("sups")
Dim conn As New SqlConnection(strConnection)
Dim cmd As SqlCommand
Dim read As SqlDataReader
conn.Open()
The web.config file is like this...
<configuration>
<appSettings/>
<connectionStrings>
<add name="sups"connectionString="server=localhost;Trusted_Connection=true;database=sups;uid=abcd; pwd=abcd;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
Where am I going wrong? Thanks a lot
|||I fixed this error with this if anyone is having problems

Dim sSQL As String
sSQL = "SELECT * FROM optionitems WHERE id=" & ID.ToString


Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("cre8StoreConnectionString").ConnectionString)
Dim cmd As New SqlCommand(sSQL)
conn.Open()
cmd.Connection = conn

Dim reader As SqlDataReader = cmd.ExecuteReader

the problem I was having to genrate this error was caused because I was using the datareader without assigning a connection to the SQLcommand object.

Sunday, February 12, 2012

Connection property not initialized

Hi,

I'm trying to do a database operation in ASP.NET page using the following code:

string connString = "SERVER=localhost;DATABASE=chbr;UID=sa;PWD=password;Connection Timeout=120";
SqlConnection sqlConn = new SqlConnection(connString);
sqlConn.Open();

string commandStr = "...";

SqlCommand command = new SqlCommand(commandStr);

command.ExecuteNonQuery();
sqlConn.Close();

But I kept getting the exception saying "ExecuteNonQuery: Connection property has not been initialized."

What did I do wrong?

Thanks!

You should be doing as much of the "busy work" as possible before you open the connection. Also, you should use either the using statement or a try / finally block.You did not specify which SQL connection the SqlCommand is supposed to use, which is why you got that error.

SqlConnection sqlConn = null;

try
{
string connString = "SERVER=localhost;DATABASE=chbr;UID=sa;PWD=password;Connection Timeout=120";
sqlConn = new SqlConnection(connString);

string commandStr = "...";

SqlCommand command = new SqlCommand(commandStr, sqlConn);

sqlConn.Open();
command.ExecuteNonQuery();
}
finally
{
if (sqlConn != null)
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}