Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Monday, March 26, 2012

the connection string property has not been initialized

in one of my classes i have a private function, which sets connection
other public shared functions call this connection
when i try to call the public shared functions say to my form code i get that error
any one ever had that beforemake sure that the SQLCommand object's connection property is set to the SQLConnection object:

string connString = "blah"; //insert REAL conn string here
SQLConnection theConnection = new SQLConnection(connString);
SQLCommand theSQLCommand = new SQLCommand();
theSQLCommand.Connection = theConnection; //This line
..
..

The ConnectionString property has not been initialized.

I am trying to use a connection string from web.config file for the first time. Here is my code.

Try
Dim cmd As String = _
("SELECT [Name], BirthDate, StartDate From " & _
"Employees WHERE PayGroup='20' AND Status='A'")

Dim conn As String = _
System.Configuration. _
ConfigurationManager. _
AppSettings("myConString")

Dim myConn As New SqlConnection(conn)
Dim myCmd As New SqlDataAdapter(cmd, myConn)
Dim ds As New DataSet
myCmd.Fill(ds)
gvEmp.DataSource = ds
gvEmp.DataBind()

Catch ex As Exception
Response.Write(ex.Message & "<br>")
Finally

End Try

I am getting The ConnectionString property has not been initialized. What am I doing wrong?Show your web.config code.
<connectionStrings>
<add name="myConString" connectionString="Data Source=myServer;Initial Catalog=Employees;User ID=myUser;Password=mypass"
providerName="System.Data.SqlClient" />
</connectionStrings>

Saturday, March 24, 2012

the difference between string.Empty and null

greetings, i have some questions below, what are the differences between
private string _strVal = string.Empty; and _strVal = null;
does the string.Empty; allocate memory for it? how about _strVal = ""
thanks for enlightening me on this.string.Empty points to one string that equal "". due to literal pooling,
there is only one copy per assembly for "". null is a different value, and
takes no gc memory.
"Asha" <Asha@.discussions.microsoft.com> wrote in message
news:5AD99FFB-A480-4951-9F7D-E7DCBFE34453@.microsoft.com...
> greetings, i have some questions below, what are the differences between
> private string _strVal = string.Empty; and _strVal = null;
> does the string.Empty; allocate memory for it? how about _strVal = ""
> thanks for enlightening me on this.
To expand on Bruce's comment:
String.Empty is a valid instance of the string class, you can invoke
the Length property (and get back a value of 0). A null reference does
not refer to a valid object.
Scott
http://www.OdeToCode.com/blogs/scott/
On Mon, 1 Nov 2004 17:09:01 -0800, "Asha"
<Asha@.discussions.microsoft.com> wrote:

>greetings, i have some questions below, what are the differences between
>private string _strVal = string.Empty; and _strVal = null;
>does the string.Empty; allocate memory for it? how about _strVal = ""
>thanks for enlightening me on this.
To expand on Scott's comment:
A string is actually an array of char. The array is terminated with a null
zero character (ASCII 0 or \0). The null zero does not count when referring
to the length of the string. It is simply the terminator character for the
array. A null string is a variable that is not initialized and points to
null. An empty string is a variable that points to an array with only a null
zero in it.
HTH,
Kevin Spencer
.Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living
"Scott Allen" <bitmask@.[nospam].fred.net> wrote in message
news:8n1eo052sbblhhqq4ao03tdaske5r869n5@.
4ax.com...
> To expand on Bruce's comment:
> String.Empty is a valid instance of the string class, you can invoke
> the Length property (and get back a value of 0). A null reference does
> not refer to a valid object.
> --
> Scott
> http://www.OdeToCode.com/blogs/scott/
> On Mon, 1 Nov 2004 17:09:01 -0800, "Asha"
> <Asha@.discussions.microsoft.com> wrote:
>
>

the difference between string.Empty and null

greetings, i have some questions below, what are the differences between

private string _strVal = string.Empty; and _strVal = null;

does the string.Empty; allocate memory for it? how about _strVal = ""

thanks for enlightening me on this.string.Empty points to one string that equal "". due to literal pooling,
there is only one copy per assembly for "". null is a different value, and
takes no gc memory.

"Asha" <Asha@.discussions.microsoft.com> wrote in message
news:5AD99FFB-A480-4951-9F7D-E7DCBFE34453@.microsoft.com...
> greetings, i have some questions below, what are the differences between
> private string _strVal = string.Empty; and _strVal = null;
> does the string.Empty; allocate memory for it? how about _strVal = ""
> thanks for enlightening me on this.
To expand on Bruce's comment:

String.Empty is a valid instance of the string class, you can invoke
the Length property (and get back a value of 0). A null reference does
not refer to a valid object.

--
Scott
http://www.OdeToCode.com/blogs/scott/

On Mon, 1 Nov 2004 17:09:01 -0800, "Asha"
<Asha@.discussions.microsoft.com> wrote:

>greetings, i have some questions below, what are the differences between
>private string _strVal = string.Empty; and _strVal = null;
>does the string.Empty; allocate memory for it? how about _strVal = ""
>thanks for enlightening me on this.
To expand on Scott's comment:

A string is actually an array of char. The array is terminated with a null
zero character (ASCII 0 or \0). The null zero does not count when referring
to the length of the string. It is simply the terminator character for the
array. A null string is a variable that is not initialized and points to
null. An empty string is a variable that points to an array with only a null
zero in it.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living

"Scott Allen" <bitmask@.[nospam].fred.net> wrote in message
news:8n1eo052sbblhhqq4ao03tdaske5r869n5@.4ax.com...
> To expand on Bruce's comment:
> String.Empty is a valid instance of the string class, you can invoke
> the Length property (and get back a value of 0). A null reference does
> not refer to a valid object.
> --
> Scott
> http://www.OdeToCode.com/blogs/scott/
> On Mon, 1 Nov 2004 17:09:01 -0800, "Asha"
> <Asha@.discussions.microsoft.com> wrote:
> >greetings, i have some questions below, what are the differences between
> >private string _strVal = string.Empty; and _strVal = null;
> >does the string.Empty; allocate memory for it? how about _strVal = ""
> >thanks for enlightening me on this.

Thursday, March 22, 2012

The eternal connection string problem

I am still struggling with a connection string problem.

I have tried a lot of different, and non-working, solutions.

I am developing on a laptop. When I get this the way I want it, I will upload it to my web site. Naturally the physical address is different for the DB file. I am trying to find a solution where I don't have to cut and paste.

I have tried web.config and it works okay for the laptop, but when I upload it and edit the .config to the new address on the server it doesn't work. I just tried the below and it doesn't work either.


Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\inetpub\wwwroot\AITCdotnet\atad\AlpaIntlTC_BP.mdb;

Doesn't "c:\inetpub\wwwroot" take you to a site root? Shouldn't this point to my site root folder on the server, even if it's on a "D" drive?

Regards,
Is your mdb file stored under your application folder? You may need to use Server.MapPath() method to get the full path to your database at runtime. Instead of storing the full path in web.config, just store the relative path. Get this working on your own machine first.

Jamie,
Thanks for the reply. I have tried variously; Server.MapPath, Path.GetFullPath, and Application.Path to try and "get" the physical path I need. I had no luck using any of those methods in the web.config. I concluded that was due to the fact that is a only an XML/text string file and it wouldn't be "complied" or processed when the .dll read its contents.

The last part of the filename to the .mdb is indeed the same on both the server and the laptop, but its the first part of the address that I am just not getting.

I have assumed that if I run Server.MapPath, that it is related to the directory in which the aspx file that "asked" for it lives. Then anything it returns could be the first half and the known subfolder and filenames could be appended.

Given the connection string I originally posted, can you give me some idea how I should use the Server.MapPath method?

I have read lots of Forum posts, have a whole collection of MS Press and other books, and only seem to find over-simplified or incomplete examples. I can't be the only person on the planet who is trying to solve this problem.

Thanks again.
To answer your questions

www.siteroot.net
AITCdotnet - folder
atad - folder
AlpaIntlTC_BP.mdb
You should call Server.MapPath() from your page class, passing in the database name that is stored in your web.config file.
You have to use Server.MapPath, Application.Path, etc. in your code, not in web.config (I would suggest usingRequest.PhysicalApplicationPath as this will give you the path to your root folder, not to the .aspx file). For example:

 void Page_Load ( Object src, EventArgs eArgs ) {

String ConnPath = Request.PhysicalApplicationPath + ConfigurationSettings.AppSettings ( "ConnPath" );

...
}


I have been working with this approach for 30 hours. I have modifiied it using Server.MapPath since this recent exchange.


Private Sub cnSb()
Dim sbPath As New StringBuilder(200)
sbPath.Append("""")
sbPath.Append("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=")
sbPath.Append(Server.MapPath("\AITCdotnet\atad\AlpaIntlTC_BP.mdb"))
sbPath.Append(";""")
'Response.Write(sbPath.ToString)
Dim cnStr As String = sbPath.ToString
Dim cnIssues As New OleDb.OleDbConnection(cnStr)
End Sub

If you uncomment the Response.Write and comment out the two following Dim's, the sbPath returns a perfectly formatted connection string.

However, whether I use the code as shown, or strike the first Dim and pass sbPath.ToString to the Connection object, I get an error about the "initialization string not being properly formatted at index 142." Near as I can tell, that is around the end of the string, but I can;t determine what it thinks is wrong. It has a trailing semi-colon, so any extra "spaces" shouldn't matter.

Once I can get this to work in the code, I will try and place the known end of the relative path in the web.config file. I think I can make that work, but first I have to get the conn string to work at all.

? Thoughts

PS. If it isn't already horribly obvious, I am still looking mostly upwards on the learning curve.
Link to a previous post along the same effort to make this connection string work. Previous work was with ASP/VBScript using DSN's...that was painless comnpared to this.
I changed Server.MapPath to Request.PhysicalApplicationPath and modified the rest of that line to satisfy the syntax. It returns the same otherwise perfect conn string in the Response Write, but fails the same way with index 142.
The connection string itself doesn't contain quotation marks!! Use:

 Private Sub cnSb()

Dim sbPath As New StringBuilder(200)
sbPath.Append("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=")
sbPath.Append(Server.MapPath("\AITCdotnet\atad\AlpaIntlTC_BP.mdb"))
sbPath.Append(";")
Dim cnStr As String = sbPath.ToString
Dim cnIssues As New OleDb.OleDbConnection(cnStr)
End Sub


The reason that I said to user Request.PhysicalApplicationPath is so that if you use this code in files that are in subdirectories, etc then you don't have to change the path that you pass into Server.MapPath().
> then you don't have to change the path that you pass into Server.MapPath().

Should read:

then you don't have to change the path that you would have to pass into Server.MapPath().
Some success! I have it working now on my laptop. I had to edit the initialization string in the "web designer Region" in order for the index 142 problem to go away. I think the Properties box, the web designer region and the "real" code must have it out before any application will work. With your help I stumbled into a workable balance.

Regretably it is still gving an error on the web server. I'll have to investigate that a bit more, since it may be a problem of the /bin folder.

Thanks to my New Brunswick and Yorkshire friends for your kind help this morning.
The error I am now getting on the web server :

Server Error in '/' Application.
------------------------

File or assembly name System.Data, or one of its dependencies, was not found.
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.IO.FileNotFoundException: File or assembly name System.Data, or one of its dependencies, was not found.

This leads me to believe that the Request.PhysicalApplicationPath object may be from a namespace other than those I "Imported." Can you tell me where it derives from?
I have now imported System.Web, having answered my own question by pursuing a link to the MSDN library online provided by Steven. It did nothing to fix the above error message, and did not harm the successful running of the application on the "laptop/localhost."

Any thoughts?

The given paths format is not supported??

Can anyone explain to me why this works...

string Email_Loc; //Stores the emails full path.
TextReader Msg_Reader = File.OpenText(Email_Loc);
Email_Msg = Msg_Reader.ReadLine();
Msg_Reader.Close();

but this
string Email_Loc; //Stores the emails full path.
TextReader Msg_Reader = File.OpenText(Email_Loc);
Email_Msg = Msg_Reader.ReadToEnd();
Msg_Reader.Close();
or this does not??

string Email_Loc = ""; //Stores the emails full path.
TextReader Msg_Reader = File.OpenText(Email_Loc);
while(Msg_Reader.ReadLine() != null)
{
Email_Msg += Msg_Reader.ReadLine();
}
Msg_Reader.Close();
I need to be able to read the entire file but when I try ether of the second two code blocks I get the following error.
System.NotSupportedException: The given path's format is not supported.
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at System.Security.Util.StringExpressionSet.AddExpressions(String[] str, Boolean checkForDuplicates, Boolean needFullPath)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path)
at SpamCenturion.MainClass.scanMessage(String Current_Msg, String Msg_Path)Where does Email_Loc get set? It does not appear to be set correctly in any of your examples.

Thanks for the replyDouglas.
I'm actually setting it higher up, but fortunately I figured out that it was just a simple oversight on my part.
A few lines further down I'm calling a method that actually wrote back to the file.
The only problem was that I was passing the file path to it twice.
And so the error "The given path's format is not supported".
I hadn't made it that far down in my debugging because it seemed that the code was failing at this point.
Sorry to waste your time.
Thanks again for the quick response.