Convert SQL connection from Asp classic to asp.net - asp.net

I would like to convert my web pages from Asp classic to Asp.net (VB), What should I do instead of this code?
conn.asp:
<%
Dim conn,connstr
connstr = "Provider=sqloledb; Data Source=.\SQLEXPRESS ;Initial Catalog=My_DB ;User Id=sa;Password=12345"
on error resume next
set conn=server.createobject("ADODB.CONNECTION")
conn.open connstr
if err then
err.clear
set conn=nothing
response.write "Connect Error!"
response.End
End IF
%>
Thank you for your time!

In C#
using (SqlConnection connection = new SqlConnection("Provider=sqloledb; Data Source=.\SQLEXPRESS ;Initial Catalog=My_DB ;User Id=sa;Password=12345"))
{
connection.Open();
// Do work here; connection closed on following line.
}
VB.NET
Using connection As New SqlConnection("Provider=sqloledb; Data Source=.\SQLEXPRESS ;Initial Catalog=My_DB ;User Id=sa;Password=12345")
connection.Open()
// Do work here; connection closed on following line.
End Using
Various connection strings can be found here

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

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

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

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.

Query about Oracle Connections

I seem to be getting intermittent problems with my Oracle connection indicating something about a problem with semaphores which suggest that Oracle is somehow holding onto the connections instead of removing them after they have been used.
Here's the code and connection string I use:
Connection string: user id=user;password=password;data source=dataSource; Validate Connection=true;Min Pool Size=10;Connection Lifetime=5;Connection Timeout=60;Incr Pool Size=5;
And the code I use is this:
Dim OracleConn As New OracleConnection()
Dim DataTable As DataTable
Dim queryOracle As OracleCommand
Dim OracleDataAdapter As OracleDataAdapter
Dim connStr As String = "user id=user;password=password;data source=dataSource; Validate Connection=true;Min Pool Size=10;Connection Lifetime=5;Connection Timeout=60;Incr Pool Size=5;"
OracleConn.ConnectionString = connStr
Try
OracleConn.Open()
queryOracle = OracleConn.CreateCommand()
queryOracle.CommandText = "select * from table1"
DataTable = New DataTable()
OracleDataAdapter = New OracleDataAdapter(queryOracle)
OracleDataAdapter.Fill(DataTable)
table1.DataSource = DataTable.DefaultView
table1.DataBind()
Catch OracleEx As OracleException
Throw
Catch ex As Exception
Throw
Finally
If Not OracleConn Is Nothing And OracleConn.State = ConnectionState.Open Then
OracleConn.Close()
End If
End Try
Now my questions are:
Is this the best way of doing this?
I only "Close" my connection do I need to "Dispose" of it also?
I'm using Oracle.DataAccess.Client by the way.
Any help will be much appreciated
Try to put everything between Using.
Using oracleConn as OracleConnection = new OracleConnection()
'Your stuff goes here
End Using
the same goes for Commands.
P.S. There's is no need to catch Exception if they are just thrown again.
I suggest you to use using block (Execute Dispose in the end)
Using connection As New OracleConnection()
....
End Using
2 An application can call Close more than one time. No exception is generated.
If you called Dispose method SqlConnection object state will be reset. If you try to call any method on disposed SqlConnection object, you will receive exception.

Resources