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
Related
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
We would like to update data in a SQL Server 2012 database with a value obtained from
changing a value on an ASP.Net DetailsView. I Would would like to update the database using
a strongly typed DataSet called DataSetParentsDetails
a TableAdapter called ParentsDetailsTableAdapter
a DataTable called ParentsDetails.
These were created with the DataSet Designer.
This is the code from the code-behind file used to figure out the amount we want to update into the database:
Protected Sub DetailsViewDetails_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs)
Dim dcmAmountToAdjust As Decimal
Dim StrSqlStatement As String
Select Case e.CommandName
Case "Add"
Case "Edit"
dcmOriginalRegistrationFee = GetValueFromLabelRegistrationFee()
Case "Delete"
Case "Update"
dcmNewRegistrationFee = GetValueFromTextBoxRegistrationFee()
dcmAmountToAdjust = dcmNewRegistrationFee - dcmOriginalRegistrationFee
' Update the tuition balance in the parent's data.
'-------------------------------------------------
StrSqlStatement =
"Update Students " & _
"Set RegistrationCode = RegistrationCode + #AmountToAdjust " & _
"Where StudentID = #ID"
' Code to update the database goes here.
'---------------------------------------
End Select
End Sub
I'm sure that this was asked many times before but I can't find a good example on how to use the query in: StrSqlStatement to update the database through the strongly typed DataSet.
First off you need a connection string, it's good practise to store your connection strings in the web.config file:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=putYourServerAndInstanceNameHere;Initial Catalog=putYourDatabaseNameHere;User ID=putYourSqlUsernameHere;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
This is a direct child of the root <configuration> element. For more information about connection strings, visit http://www.connectionstrings.com.
Then you'll need some imports in your code-behind, and you'll need to add them as references to your project if you haven't already got them in there:
Import System.Data
Import System.Data.SqlClient
Then we connect to the database and run our command, we use parameters because they're more secure.
'build the connection object using the string from the web.config file
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
'build the command object specifying the command text and the connection to use, conn
Using cmd As New SqlCommand("UPDATE Students SET RegistrationCode = RegistrationCode + #AmountToAdjust WHERE StudentID = #ID", conn)
'add the parameters needed by the command
cmd.Parameters.AddWithValue("#AmountToAdjust", amountToAdjust)
cmd.Parameters.AddWithValue("#ID", studentID)
'try to open the connection and execute the statement
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
'handle the exception here
End Try
End Using
End Using
Note that there is no need to use conn.Close() here as the Using statement will take care of that for you (SqlConnection's Dispose method closes the connection if it is still open).
In my ASP.NET(3.5) project, I am using inbuilt TableAdapters/Dataset for all Data Access. Does it provide the same security as SQLDataSource does from SQL injection? I am using parameters as follows.
Dim myDAL As New ABCTableAdapters.XYZTableAdapter
Label1.Text = myDAL.getDatafromDB(myParameter)
Update 1:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myParameter As String = getSafeURL(Request.QueryString("MS_Code")) 'getsafeurl encodes querystring using HttpUtility.UrlEncode
Dim myDAL As New ABCTableAdapters.XYZTableAdapter
Label1.Text = myDAL.getDatafromDB(myParameter)
End Sub
getDatafromDB corresponds to following query present in app_code/DAL.xsd
SELECT something FROM sometable where fieldname = #parameter
Update 2:
If I 'View Code' of XSD I am able to see following
<SelectCommand>
<DbCommand CommandType="Text" ModifiedByUser="true">
<CommandText>SELECT pageContent FROM [content] where name = #name</CommandText>
<Parameters>
<Parameter AllowDbNull="true" AutogeneratedName="name" ColumnName="name" DataSourceName="iseac.dbo.[content]" DataTypeServer="nchar(100)" DbType="String" Direction="Input" ParameterName="#name" Precision="0" ProviderType="NChar" Scale="0" Size="100" SourceColumn="name" SourceColumnNullMapping="false" SourceVersion="Current" />
</Parameters>
</DbCommand>
</SelectCommand>
It depends.
You could get SQL injection if you badly use tableAdapters.
The main thing is to use SqlParameters for all data that is gathered from users.
Can you show some of your data access code ?
Look up here How To: Protect From SQL Injection in ASP.NET
using System.Data;
using System.Data.SqlClient;
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet userDataset = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = #au_id",
connection);
myCommand.SelectCommand.Parameters.Add("#au_id", SqlDbType.VarChar, 11);
myCommand.SelectCommand.Parameters["#au_id"].Value = SSN.Text;
myDataAdapter.Fill(userDataset);
}
The important part here is that user entered data (what comes in from web request) is passed to DB inside database parameters like #au_id. In that case you are protected from SQL injection.
BAD WAY would be this (DON'T USE THIS):
myCommandText = string.Format(
"SELECT au_lname, au_fname
FROM Authors WHERE au_id = {0}", SSN.Text)
This way user can manipulate what is send to DB and if your connection to DB has enough privileges it can drop tables or database. Or it can silently modify your data and that is even worse.
So, always use database parameters.
Additionally if you do you gain in performance, because DB will cache execution plan and if you later execute same SQL with only different values for parameters, DB already have execution plan and it doesn't need to parse sql again.
I'm trying to write a method in VB.net so that when I click a button it queries the database and returns all the values which match a textbox which is located next to the button. I have no idea how to do this, I assume in the onclick method for the button I will need to pull in the value from the textbox, connect to the database and display the results to a gridview?
Any help is greatly appreciated.
thanks :)
Marc
The two "best" options are to either use a Table Adapter or Entity Framework.
http://msdn.microsoft.com/en-us/library/bz9tthwx(v=vs.80).aspx (Table Adapter)
http://msdn.microsoft.com/en-us/library/bb399567.aspx (Entity Framework)
Both options will give you a GUI interface to build the connection and back end database queries. Entity Framework is the newer technology of the two. Table Adapters are probably easier to learn/understand if your unsure. (Que "easy" comments now)
I would give code examples but you'll have to understand some basics of either for them to make any sense. The basic examples in either link should be enough for what you need.
Both options will give you the ability to databind your datagrid to the results.
DISCLAIMER: This code is prone to SQL injection attacks and should not be used in a production environment. For testing only. Specifically:
strSQL = "SELECT * from Table where charindex ('" & TextBox1.Text & "', columnname) > 0 "
First in the web.config add this section that points to your database:
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
For the example, I've just used the standard database which is attached when you start a new vb.net web application in VisualStudio 2010.
Then in your Default.aspx, have something like this:
<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
<asp:Button runat="server" Text="Button" ID="Button1" />
And in the code behind you could do something like this:
Imports System.Data.SqlClient
Public Class _Default
Inherits System.Web.UI.Page
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strSQL As String = String.Empty
' Define your select statement
strSQL = "SELECT * from Table where charindex ('" & TextBox1.Text & "', columnname) > 0 "
' Fire up SQLConnection with a DataReader
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString)
Dim command As New SqlCommand(strSQL, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Try
' Do some magic with reader.GetValue()
Catch ex As Exception
End Try
End While
reader.Close()
connection.Close()
End Using
End Sub
End Class
Ofcourse you'd have to validate the textbox.text before placing it directly into the select statement, but this will do the trick.
The 'CharIndex' will loop through the column specified as the second parameter and check if there's a match between the column data and the textbox.text, if so it will return the row.
The reader will loop through the results and with the reader.GetValue you can retrieve the data and do your magic.
Instead of using a SQLDataReader you can of course attach it to a Databound Grid or something else...
Okay this question could either be very broad or very specific because I am not sure if I am going about this in a fundamentally wrong way or if I am close to correct.
First an overview: What I am trying to do it create a server application for all of the clients in my organization to connect to. I think the best way to do this is to use a web service. Please correct me if I am wrong!
Anyway, if I use a web service I need the web service(server) to connect to the database. In MS Visual studio when you add a web service project the data menu disappears and you can't add a data source to the project. There may be a workaround for this by hand coding this, but I am not sure how to do it. This is my first time working with a web service and ASP.NET so I am a real noob in this area.
Any help would be greatly appreciated!!!
Add your database connection string to the <connectionStrings/> section of the web service web.config file. Check this web site for a list of the most common database connection strings: Connectionstrings.com
You would use standard ADO.Net commands and SQL statements, rather than using the dataset designer. Example (IN VB)
<WebMethod()> _
Public Function DoesOpenCallExist(ByVal CustID As String, ByVal CallType As String, ByVal SubCallType As String) As Boolean
Dim returnvalue As Boolean = False
' first, entry validation
' snip - code deleted
Dim conn As New System.Data.SqlClient.SqlConnection
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("HEATConnectionString").ConnectionString
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_GetCallCount"
cmd.Parameters.AddWithValue("#CustID", CustID)
' Etc...
Try
conn.Open()
returnvalue = cmd.ExecuteScalar() > 0
Catch ex As Exception
Throw New Exception(ex.ToString())
Finally
conn.Close()
End Try
Return returnvalue
End Function
*This should be done
web.config file*
here the datsource is the servername,initial catlog is the databasename and the userid ur sql userid and the password is as same.
And then in the class we want to get connect with the database......
****class.cs****
public class connect
{
public static SqlConnection con()
{
String con= ConfigurationManager.AppSettings["connections"].ToString();
SqlConnection cn = new SqlConnection(con);
cn.Open();
return cn;
}
}
here the connection is the keyname......
ok i think its sufficient............