Showing posts with label property. Show all posts
Showing posts with label property. Show all posts

Thursday, March 22, 2012

ConnectionString Property Not Set

Hi, After many nights without sleep I'm not seeing this? Can anyone help why I'm getting a ConnectionString Property not set error? thanks!

Dim SconnAsString
Dim DBConAsNew Data.SqlClient.SqlConnection
Sconn = ConfigurationManager.AppSettings("LocalSqlServer")
DBCon =New SqlClient.SqlConnection(Sconn)
Dim cmdCommandAsNew Data.SqlClient.SqlCommand'Dont forget to instantiate a connection object

cmdCommand.Connection = DBCon
DBCon.Open()

You created a command and you assigned connection to it, but maybe you should also assign command itself?

Try to see if your connection string is retrieved from configuration file, maybe your connection name or connection string in it is wrong?

Dim SconnAsString
Dim DBConAsNew Data.SqlClient.SqlConnection
Sconn = ConfigurationManager.AppSettings("LocalSqlServer")
DBCon =New SqlClient.SqlConnection(Sconn)
Dim cmdCommandAsNew Data.SqlClient.SqlCommand("select * from yourTable")

'Dont forget to instantiate a connection object

cmdCommand.Connection = DBCon
DBCon.Open()

|||

That didn't help. Perhaps a tracecode might give more information of what's going on. The error happens at line DBCon.Open()

Any help greatly appreciated.

System.InvalidOperationException was unhandled by user code
Message="The ConnectionString property has not been initialized."
Source="System.Data"
StackTrace:
at System.Data.SqlClient.SqlConnection.PermissionDemand()
at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at Admin_DistributorDetail.Button1_Click(....)
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

|||could you provide your connection string?|||

This is what I have now. Not sure if I needed the remove name statement after I've manually configured asp.net db to get another db name instead of the default.

<

connectionStrings>

<

removename="LocalSqlServer" />
<addname="LocalSqlServer"connectionString="Data Source=XXXXXXX;Initial Catalog=YYYYYYY;Persist Security Info=True;User ID=ZZZZZZ;Password=TTTTT"providerName="System.Data.SqlClient" />

</

connectionStrings>|||

BTW the connection string appears to be working fine for the rest of the site through the aspx pages and the VS sqladapters is just in the code behind I getting this problem.

|||

try to modify your code to be like this below and check if your SConn contain valid connection string

Dim SconnAsString
Sconn = ConfigurationManager.AppSettings("LocalSqlServer")
Dim DBConAsNew SqlClient.SqlConnection(Sconn)
DBCon =Dim cmdCommandAsNew Data.SqlClient.SqlCommand("select * from yourTable")

DBCon.open

Thanks

|||

Thanks but I haven't been able to run this code yet because an error occurs at the "Dim cmdCommand" with curlies under the "Dim" stating that it expects an expression. The cmdCommand in later code then has curlies underneath stating the cmdCommand is not declared.

Hope there is a small adjustment to this that can get it going?

|||

sorry something left in my code try it without any command and check if it works

Dim SconnAsString
Sconn = ConfigurationManager.AppSettings("LocalSqlServer")
Dim DBConAsNew SqlClient.SqlConnection(Sconn)

DBCon.open

dbcon.close

|||

This certainly looks tidy and concise, a step in the right direction, however unfortunate, I'm still getting the "The ConnectionString Property has not been initialized" error on DBCon.open

hmmm any ideas left?

|||

have you checked what is returned as your connection string?

Thanks

|||

I'm sorry I'm somewhat of a newby when it comes to debugging. How would I do this? My watch list does not show a connection string but only a red exlamation mark stating.

--------
Name Value
Div[1] End of expression expected
--------

If you mean something other than the watch list please let me know and how to do it.

thnks

|||

Sorry I've just found the debugging tab I'm supposed to look for. Locals right?

The connectionstring indeed returns "" thus empty.

Why in the world would it do that?

|||

Could it have something to do with my webconfig <appsettings> part? its has nothing in it. is now set to <appsettings></appsettings>

|||

your

Sconn = ConfigurationManager.AppSettings("LocalSqlServer")

probably points to wrong place try this:

Sconn = ConfigurationManager.ConnectionStrings("LocalSqlServer")

sqlsql

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.

ConnectionString Property

I am having trouble initializing my connection. This is the code:

DimDBConnPhone As NewSqlConnection(ConfigurationManager.AppSettings("DBConnPhone"))

Dim DBConnClient As NewSqlConnection(ConfigurationManager.AppSettings("DBConnClient"))

Dim Sqlcomm1 As New SqlCommand

Dim Sqlcomm2 As New SqlCommand

DBConnPhone.Open()

DBConnClient.Open()

Once I start debugging, it stops and give me the error "The ConnectionString Property was not initialized" Any suggestions?

If you want to retrieve connection strings, you should use ConfigurationManager.ConnectionStrings property, not ConfigurationManager.AppSettings. So the code changes to:

Dim DBConnPhone As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnPhone"))

Dim DBConnClient As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnClient"))

...

|||I did that and it said that Value of type 'System.Configuration.ConnectionStringSettings' cannot be converted to 'String'|||Dim DBConnClient As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnClient").ConnectionString)|||I didn't get any errors with that, but I also did not see where the newrecord was inserted into the table. I got to check my code some more.Thanks

Sunday, February 19, 2012

connection string based CREATE CUBE supported in AS 2005.

Hi,

I am trying to use the CREATECUBE functionality in AS 2005 through
connection string property, but getting following error:

Microsoft OLE DB Provider for Analysis Services 2005:
The following system error occurred: Unspecified error .

csSourceDSN=PROVIDER=MSOLAP;DATASOURCE=WOTTRANSUBHSXP\DEV;INITIAL
CATALOG=National;

CREATE CUBE [National] (
DIMENSION [Line],
LEVEL [All Line] TYPE ALL,
LEVEL [Line],
LEVEL [Brand],
LEVEL [Item Name],
DIMENSION [Date],
LEVEL [All Date] TYPE ALL,
LEVEL [Year] TYPE YEAR,
LEVEL [Quarter] TYPE QUARTER,
LEVEL [Month] TYPE MONTH,
DIMENSION [Market],
LEVEL [All Market] TYPE ALL,
LEVEL [Market],
DIMENSION [State],
LEVEL [All State] TYPE ALL,
LEVEL [State],
LEVEL [Outlet],
MEASURE [Quantity] FUNCTION SUM FORMAT '#,#',
MEASURE [Cost] FUNCTION SUM FORMAT 'Standard',
MEASURE [Revenue] FUNCTION SUM FORMAT 'Standard'
)

INSERT INTO [National](
[Line].[Line],
[Line].[Brand],
[Line].[Item Name],
[Date].[Year],
[Date].[Quarter],
[Date].[Month],
[Market].[Market],
[State].[State],
[State].[Outlet],
[Measures].[Quantity],
[Measures].[Cost],
[Measures].[Revenue]
)
OPTIONS ATTEMPT_ANALYSIS
SELECT
[National].[Line:Line],
[National].[Line:Brand],
[National].[Line:Item Name],
[National].[Date:Year],
[National].[Date:Quarter],
[National].[Date:Month],
[National].[Market:Market],
[National].[State:State],
[National].[State:Outlet],
[National].[Measures:Quantity],
[National].[Measures:Cost],
[National].[Measures:Revenue]
FROM [National]
WHERE [Line:Line] = 'Microwaves'
AND [Date:Year] = '1994'

I also tried using CREATE GLOBAL CUBE statement:
"CREATE GLOBAL CUBE [National123] Storage 'C:\\National1.cub' FROM
[National] ( MEASURE [National].[Quantity], DIMENSION
[National].[Line] ( LEVEL [Line], LEVEL [Brand], LEVEL [Item
Name] ) )";

Any idea if we can still use CREATECUBE & INSERTINTO properties in AS
2005 or we need to switch to CREATE GLOBAL CUBE?

Any help in this regard would be appreciated.

Thanks,
Santosh.

Hi Santosh,

No, you can't use this syntax to create a local cube from an AS2005 server cube any more. The CREATE GLOBAL CUBE syntax will work, as will using XMLA to create your local cube.

Chris

|||

Hi Chris,

Has this thing been documented somewhere on msdn?

I need a reference in order to put in my document, which would substantiate this change.

Thanks,
Santosh.

|||

No, the only place that it's documented as far as I know is the chapter on local cubes in 'MDX Solutions' second edition, which I updated from the first edition. I got the information that CREATE CUBE is no longer supported direct from the dev team.

Chris

|||Thanks Chris. Even this reference is good enough for me.

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();
}
}
}