Server Error in '/' Application (Error 40 on ASP.net page) - asp.net

Hey all I am currently trying to connect to a database on a differnt server from where the .ASPX file is being called from.
In VS2013, in debug, It calls the query just fine without problems but once I compile and call that same page from the actual web server it displays this error:
The MS SQL server I am calling is a 2008 version.
The connection string I have tried are:
Dim sqlQ As SqlCommand = Nothing
Dim conn As SqlConnection = Nothing
Dim reader As SqlDataReader = Nothing
Dim strConnString As String = "Data Source=zzSQL004;Initial Catalog=C_Data;Trusted_Connection=True;Integrated Security=SSPI;"
Dim strConnString As String = "Server=zzSQL004,2866;Database=C_Data;User Id=C_user;Password=zzzzzzz;"
Dim strConnString As String = "Data Source=zzSQL004;Initial Catalog=C_Data;Persist Security Info=True;User ID=C_user;Password=zzzzzzz"
Dim strConnString As String = "Data Source=zzSQL004,2866;Initial Catalog=C_Data;Trusted_Connection=True;Integrated Security=SSPI;User ID=C_user;Password=zzzzzzz"
Dim strConnString As String = "Data Source=zzSQL004,2866;Initial Catalog=C_Data;Persist Security Info=True;User ID=C_user;Password=zzzzzzz"
Dim strConnString As String = "Data Source=zzSQL004\PNC_user;Initial Catalog=C_Data;Persist Security Info=True;User ID=C_user;Password=zzzzzzz"
Dim strConnString As String = "Provider=SQLOLEDB.1;Password=zzzzzzzz;Persist Security Info=True;User ID=C_user;Initial Catalog=C_Data;Data Source=zzSQL004"
In my Web.config file I have no to the database since I have the code above I am using. I am starting to wondering wither that is causing the issue or not?
I am just wondering what I could be forgetting in order to make this connection work? I spoke to the DBA's and they say everything is working/configured as it should be. Remote connection is enabled and all. It's just odd that in debug inside VS2013 I can get to it (which is on a different PC - not on the DB/web server itself) yet once on the server I can not.
Any help would be great!

Sounds like a network issue, I would do the following:
ping the database server from the web server
use telnet on the web server to open the connection towards the SQL server on the specific port

Related

NullReferenceExecption was unhandled by User code error while connecting Sql Local db using vb.net in visual studio 2013

I'm new to Visual studio 2013. i'm trying to develop a web application using vb.net. there is a scenario where i need to display data on webpage by fetching multiple data for different tables. i have a function where i'm trying to connect to my local database. below is the function
Private Function GetData(query As String) As DataTable
Dim dt As New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("Data Source= (LocalDB)\v11.0;AttachDbFilename=D:\Visual Studio Applications\TestDB\WebApplication1\App_Data\TestingDB.mdf;Integrated Security=True").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
On line 3 in the function, in connection strings("") here i'm getting an error
"NullReferenceExecption was unhandled by User code
An exception of type 'System.NullReferenceException' occurred in WebApplication1.dll but was not handled in user code"
when i check the properties of my project database, the connecting string was
Data Source=(LocalDB)\v11.0;AttachDbFilename="D:\Visual Studio Applications\TestDB\WebApplication1\App_Data\TestingDB.mdf";Integrated Security=True
If i use this connection string in the function, its is throwing syntax error because its has double quotes ("") in the connection string before and end of the Datadirectory ("D:\Visual Studio Applications\TestDB\WebApplication1\App_Data\TestingDB.mdf"). so due to that when i try placing this in my ConfigurationManager.ConnectionStrings ("connection string").ConnectionString its throwing syntax error (,')' expected).So i have removed those double quotes in my connection string but then its throwing NullReferenceExecption was unhandled by User code error.
In my web.config file the connection string is 'Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\TestingDB.mdf;Integrated Security=True'
i tried using this as my connection string but no use still getting that NullReferenceExecption error.
I'm very confused and frustrated:( please help me with this.
When you write
Dim constr As String = ConfigurationManager.ConnectionStrings("Data Source= (LocalDB)\v11.0;AttachDbFilename=....").ConnectionString
you are asking to the Configuration Manager to find a connection string named in that way, of course this is the Value not the Name of the constring in your config.
So suppose that you have in your config a line like this
<connectionStrings>
<add name="MyConString" connectionString="Data Source=...." />
</connectionStrings>
then you call
Dim constr As String = ConfigurationManager.ConnectionStrings("MyConString").ConnectionString
to retrieve the value to pass to the SqlConnection constructor

Migrating ADODB connection from ASP to ASPX

I have to migrate some Classic ASP pages to .NET. I've got the problem with ADODB connection that has been used in ASP App. Here is the code of old db.asp
<%
Option Explicit
' Declare variables...
Dim cnn ' ADO connection
Dim rst ' ADO recordset
Dim strTitle 'Title for each page
Sub OpenDatabase()
' Create an ADO Connection.
Set cnn = Server.CreateObject("ADODB.Connection")
' We're using SQL Server connection string
cnn.Open Session("SQLConnectString")
cnn.CommandTimeout = 0
Server.ScriptTimeout = 3000
' Create an ADO Recordset object
Set rst = Server.CreateObject("ADODB.Recordset")
End Sub
Sub RunSQL(strSQL)
'Open a recordset from the strSQL.
rst.Open strSQL, cnn
End Sub
Sub CloseDatabase()
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing
End Sub
%>
I want to use this code on every page for connection to DB. know that I have to remove Option Explicit from my code and add header as <%# Page Language="VB" %> I've copied this code to the new aspx page and now I'm getting errors:
1) VS ask me to put End Sub before Sub OpenDatabase(), but there is no Open Sub that need to be closed.
2) VS don't see those variables cnn, rst, strTitle
3) Now I'm storing ConnectionString in Web.config, so I've replaced open with the following code:
cnn.Open(System.Configuration.ConfigurationManager.ConnectionStrings("SQLConnectString").ConnectionString)
What else should I change to fix it? Any advise=) Thanks
You do not use ADODB in DotNet. Technically, you can, but that's not the way to do.
You use ADO.Net, IDataReaders, DataSets (loose or strongly-typed, I prefer strongly-typed).
ASP.NET is not ASP.
Don't feel bad, I was trying the same thing you are (albeit, back in 2002).
Until someone told me differently.
Here is a tutorial...probably at the right level for where you are now.
http://www.aspsnippets.com/Articles/Difference-between-ExecuteReader-ExecuteScalar-and-ExecuteNonQuery.aspx
Rule #1 in NET: connection string better be in web.config or other config files. Or in some cases in OS registry.
Using connection string defined in each and every page in NET is bad practice from security, maintenance and lot of other reasons and on top of that it show low qualification of a programmer who build it.
Rule #2. You can use inline SQL statement but for the same reason as in rule #1 it is a bad idea. Use parametrized stored procedures unless you do not have any like while working with access or Excel or plain text files as data storage.
So in your web.config you should have following entry:
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ProjectDatabases.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
then in your code you call
Public void main()
{
String CONN
String SQLString
CONN = String.Format(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString, rootPath);
SQLString=/// your stored procedure and parameters if any
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd = new SqlCommand(SQLString), CONN);
CONN.Open();
SqlDataReader reader = cmd.ExecuteReader();
/// do what ever you need to work with your data like build a string, html document etc
closeConn();
}
public void closeConn()
{
if (reader != null)
{
reader.Close();
}
if (CONN!= null)
{
CONN.Close();
}
}
You do not need Option Explicit for simple reason: C# will not allow you to use any undeclared variable

How can a create a test case in ASP.NET C# for DatabaseConnection Error using ExpectedException?

I want to create a test case for Database Connection Error.
Any ideas how to do this?
In your web.config, add a new connection string called ErrorConnectionString.
<connectionStrings>
<add name="ErrorConnectionString" connectionString="server=192.168.1.1;user id=sa;password=WRONG_PASSWORD;database=MyDatabase"/>
</connectionStrings>
Then, to test the connection error, you can use the following code (VB.NET)
Dim connectionString = ConfigurationManager.ConnectionStrings("ErrorConnectionString").ConnectionString
Dim connection As New SqlConnection(connectionString)
Dim adapter As New SqlDataAdapter("select * from MyTable", connection)
adapter.Fill(ds)
connection.Close()
Assuming you purposefully have incorrect login credentials in the connection string, you will get the exception thrown.
If you can't afford to modify the web.config, you can simply hardcode the invalid connection string into the connectionString variable.

SqlConnection localhost failed username

This is my first time trying to use a database in ASP.Net, and I have a problem here:
My database is on my computer (localhost), and it throws an exception on me when I click the "submit" button :
SQLException was unhandled by user code. Login failed for user ".
protected void Register_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server = localhost ;uid=; Password= database = Movies;");
connection.Open();
//FirstName***********
string firstName = UsernameTextBox.Text;
string sqlquery = ("INSERT INTO [Movie] (FirstName) VALUES (' " +FirstNameTextBox.Text + " ' ");
SqlCommand command = new SqlCommand(sqlquery , connection);
command.Parameters.AddWithValue("FirstName", firstName);
Since the server is on my computer, I dont have any username, right?!
You do need a username and password, or else you need to use integrated security, which means that your windows credentials are used.
You can add integrated security to your connection as follows:
SqlConnection connection = new SqlConnection("server = localhost ;integrated security=SSPI; database = Movies;");
A good resource for connection strings is http://www.connectionstrings.com
SQL server always requires a username, whether it's on your machine or a remote machine.
I'd suggest looking www.asp.net or try Google to find out how you configure your patricular version of SQL Server
Check this site for connectionstrings if you have problem with formating the connectionstring

ASP.NET application opening WAY too many SQL connections

I have an issue on a codebit with an ASP.NET Webforms 4 application.
I am using SQL server 2008 R2, IIS 7, the website is running on Windows Server 2008 R2 in separate Application pool (integrated mode, .NET4, with support for 32bit assemblies).
The following code is posing problems:
Dim sqlCmd = New SqlClient.SqlCommand
With sqlCmd
Using sqlConnectionToUse As SqlClient.SqlConnection = GetActiveConnexion(pstrConnectString), _
vAdaptor As New SqlClient.SqlDataAdapter
.Connection = sqlConnectionToUse
.CommandText = pstrSQL 'function parameter
vAdaptor.SelectCommand = sqlCmd
'query1: SELECT somecolumn FROM table WHERE somecolumn '' ==> opens a new connection in SQL Server
'query2: SELECT someothercolumn FROM anothertable WHERE someothercolumn 23 ==> uses my WebSite process active connection
vAdaptor.Fill(vDataSet)
End Using
End With
UPDATE: the GetActiveConnexion() method simply does the following code in my case:
Return New SqlClient.SqlConnection("my connection string obtained from the web.config file")
When I run the query2, everything goes smoothly, the ASP.NET application uses the openned connection of the application pool and I get my results in the dataset.
However, whenever I run the query1, a NEW connection is openned in SQL server (I can see it show up in the SSMS's Activity Monitor) and this one remains openned. The problem is that If I run this query1 100 times, I reach the connection pool's limit and very bad things happens. I still gets the results in the dataset, can use them etc...
The new connection is created on the call of vAdaptator.Fill().
Any idea on what's wrong ?
Thanks a lot for your time.
(PS: sorry for the bad english).
Here is the code in C# for those who prefer:
object sqlCmd = new SqlClient.SqlCommand();
using (SqlClient.SqlConnection sqlConnectionToUse = GetActiveConnexion(pstrConnectString)) {
using (SqlClient.SqlDataAdapter vAdaptor = new SqlClient.SqlDataAdapter()) {
sqlCmd.Connection = sqlConnectionToUse;
sqlCmd.CommandText = pstrSQL; //function parameter
vAdaptor.SelectCommand = sqlCmd;
//query1: SELECT F10_ID FROM FIN_MONTANT_TT_F10 WHERE F10_ID_TT_F19 = '' ==> opens a new connection in SQL Server
//query2: SELECT A48_ID FROM ADH_EPARTICIPANT_ADMIN_A48 WHERE A48_ID=23 ==> uses my WebSite process active connection
vAdaptor.Fill(vDataSet);
}
}
Your SqlCommand instance should be wrapped in a using block as it's Disposable. It's probably the source of your problems.
using (SqlClient.SqlConnection sqlConnectionToUse = GetActiveConnexion(pstrConnectString))
{
using (SqlCommand sqlCmd = sqlConnectionToUse.CreateCommand())
{
using (SqlClient.SqlDataAdapter vAdaptor = new SqlClient.SqlDataAdapter())
{
...
}
}
}
Or VB
Using sqlConnectionToUse As SqlClient.SqlConnection = GetActiveConnexion(pstrConnectString)
Using sqlCmd As SqlCommand = sqlConnectionToUse.CreateCommand()
Using vAdaptor As New SqlClient.SqlDataAdapter()
...
End Using
End Using
End Using

Resources