Showing posts with label dim. Show all posts
Showing posts with label dim. 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 problem

Hay, I have a problem with this connectionstring.

Dim myConnectionAs New Data.OleDb.OleDbConnection("Provider=SQLNCLI;Data Source=whatever-ja4lbq\sqlexpress;Initial Catalog=Account;Integrated Security=SSPI;")
I use this code to receive a value on a specific query
 
Public Sub readdata(ByVal myconnectionstringAs String)Dim mySelectQueryAs String = "SELECT UserName, Password FROM TAccount WHERE UseName ='" & TextBox1.Text & "'; and Password = '" & TextBox2.Text & "';"Dim mycommandAs New Data.OleDb.OleDbCommand(mySelectQuery, myConnection) myConnection.Open()Dim myreaderAs Data.OleDb.OleDbDataReader myreader = mycommand.ExecuteReaderWhile myreader.Read Label1.Text = myreader.GetString(1)End While myreader.Close() myConnection.Close()End Sub 
 
But when it execute i receive this exeption
 
Login timeout expired
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
SQL Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].
 
Is this mean that i can not make a connection to my sql server 2005.

My sql server 2005 runs on my developer computer

 

By default SQL Server 2005 does not allow remote connections. Select Start -> All programs-> Microsoft SQL Server 2005 -> Configuration Tools -> SQL Server 2005 Surface Area Configuration. When the tool opens, pick "Surface Area Configuration for Services and Connections", when you get a tree view of all configurable services. Under "Database engine", there's a "remote connections" leaf, from which you can enable remote connections. You need also turn Sql Server Browser service on (since you use instance name in connection string)

More information:http://support.microsoft.com/kb/914277

|||

And i must make some permission properties in my databases

Thanks

Friday, February 10, 2012

Connection Problem trying to execute stored procedure

I am running the following code and getting the error below:

Dim connectionstringAsString ="<%$ ConnectionStrings:ConnectionString %>"Dim ConnectionAsNew SqlClient.SqlConnection(connectionstring)Dim CommandAsNew SqlClient.SqlCommand("StoredProcedure9", Connection)

Command.CommandType = Data.CommandType.StoredProcedure

Command.Parameters.Add(

New SqlClient.SqlParameter("@.bid_id", Data.SqlDbType.Int))

Command.Parameters(

"@.bid_id").Value ="Testing"

Connection.Open()

Command.ExecuteNonQuery()

Connection.Close()

ERROR:

Format of the initialization string does not conform to specification starting at index 0.

I think my connectionstring is wrong, please help.

Thanks

CAB

Try changing:
Dim connectionstringAsString ="<%$ ConnectionStrings:ConnectionString %>"

To

Dim connectionstring as String = System.Configuration.ConnectionStrings("MyConnectionStringName").ConnectionString (or something similar to that...)

Which will grab the connectionstring out of your web.config and plug it in as the property in question. (I'm not too up on VB.NET 2.0 so I may be wrong - but pretty sure you can't use the <% %> (i.e. pre-processing tags) inside of compilable VB.NET code - i.e. I think that's your issue)
|||

Hi,

Thanks for your help, but now I am getting:

'ConnectionStrings' is not a member of 'Configuration'.

Any ideas?

|||Cabby, can you let us know which version of the .NET Framework you are using? 1.1 or 2.0?|||

Hi, I am using version 2.0

I have updated that line of code to

Dim connectionstringAsString = System.Configuration.ConfigurationManager.AppSettings("connectionstring")

and am now getting:

The ConnectionString property has not been initialized.

This seems to be a similar problem tohttp://forums.asp.net/thread/402876.aspx but I am not sure I understand what needs to be done.

Please help!

Thanks

CAB

|||That other link was for ASP.NET 1.1. See if this article helps:Configuration API Improvements in ASP.NET 2.0
|||

Thanks for the link. But that seems to be working fine. When I run:

<%

@.ImportNamespace="System.Configuration" %>

<%

@.ImportNamespace="System.Web.Configuration" %>

<

scriptrunat=serverlanguage=C#>publicvoidPage_Load(objectsource,EventArgse)

{

Response.Write("Connection String:"

+

ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

}

</

script>

<

html>

<

head><title>Retrieving Connection Strings</title>

</

head>

<

body>

<

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

</

form>

</

body>

</

html>

I get:

Connection String:Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True

Which I assume means all is working with that page.

But when I run my code:

ProtectedSub DetailsView1_ItemInserted(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.DetailsViewInsertedEventArgs)

Dim connectionstringAsString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")Dim ConnectionAsNew SqlClient.SqlConnection(connectionstring)Dim CommandAsNew SqlClient.SqlCommand("StoredProcedure9", Connection)

Command.CommandType = Data.CommandType.StoredProcedure

Command.Parameters.Add(

New SqlClient.SqlParameter("@.bid_id", Data.SqlDbType.Int))

Command.Parameters(

"@.bid_id").Value ="Testing"

Connection.Open()

Command.ExecuteNonQuery()

Connection.Close()

Response.Redirect(

"Default.aspx")EndSub

I get:

The ConnectionString property has not been initialized.

Any ideas?

Thanks

|||

UPDATE:

I have changed the connection string to:

Dim

connectionstringAsString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString()This seems to be getting a bit further, now my error is:

Input string was not in a correct format.

which seems to be relating to the line:

Command.ExecuteNonQuery()

any ideas?

Thanks, CAB

|||

The problem is with my parameters, the stored procedure works fine if I dont try and pass it any parameters and remove :

Command.Parameters.Add(New SqlClient.SqlParameter("@.bid_id", Data.SqlDbType.Int))

I have realised that I can do this all in the stored procedure and not have to pass any variables so now all is working fine.

Thanks for all the help!!!!!

CABBY