Why is my asp.net causing a runtime error? - asp.net

I am trying to connect to a database on my local server. The database is called "dbtest." Of course, I have left off my actual password and replaced it with "password."
This is the typical code I see on every tutorial, but it doesn't work at all. Please help.
<%
Dim con, rs
con = Server.CreateObject("ADODB.Connection") 'I think it is something to do with this line
con.Open "Provider=sqloledb;SERVER=localhost;DATABASE=dbtest;UID=administrator; PWD=password;"
rs = Server.CreateObject("ADODB.Recordset")
%>

This is not asp.net. This is classic ASP
You have to read about creating a database driven webapp first.
Read about SqlDataSource and GridView controls. You won't need any code.
here: http://www.asp.net/data-access/tutorials/querying-data-with-the-sqldatasource-control-cs

The tutorials you are following may be a little out of date, .net includes updated classes for SQL data access, have a look here
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx
Particularly at the SqlConnection class and SqlCommand class.
There is a useful tutorial that can be found here.
The equivalent of the ADODB.Recordset would be the SqlDataReader class.

Related

ASP.NET modify connectionstring at runtime

I need to change dataset connectionstrings to point to different DBs at run time.
I've looked at a number of solutions however they all seem to be related to WinForms or web application projects or other technology slightly different than what I'm using, so I haven't figured out how apply them.
The application is like a discussion. It's a web site project based on code originally written under VS2005, and there's no budget (or personal talent!) for major changes at this time. The app is written in vb.net; I can understand answers in c#. I'm working in VS2013.
The app has three typed datasets pointing to one MDF, call it "MainDB.mdf". There are dozens of tableadapters among the three datasets.
I'm going to deploy the app it as an "alpha/demo" version. I would like to use the same code base for all users, and a separate physical version of MainDB for each user, to reduce chances that the users crash each other.
The initial demo access URL will contain query string information that I can use to connect the user with the right physical database file. I should be able to identify the database name and thus the connection string parameters from the query string information (probably using replace on a generic connection string). If necessary I could use appsettings to store fully formed connection strings, however, I would like to avoid that.
I would like to be able to change the connection strings for all the datasets at the time that the entry point pages for the app are accessed.
Changing the tableadapter connection strings at each instantiation of the tableapters would require too much code change (at least a couple of hundred instantiations); I'd just make complete separate sites instead of doing that. That's the fall back position if I can't dynamically change the connectionstrings at runtime (or learn some other way to make this general scheme work).
Any suggestions on how to approach this would be appreciated.
Thanks!
UPDATE: Per comments, here is a sample instantiation of tableadapter
Public Shared Sub ClearOperCntrlIfHasThisStaff( _
varSesnID As Integer, varWrkprID As Integer)
Dim TA As GSD_DataSetTableAdapters.OPER_CNTRLTableAdapter
Dim DR As GSD_DataSet.OPER_CNTRLRow
DR = DB.GetOperCntrlRowBySesnID(varSesnID)
If IsNothing(DR) Then
Exit Sub
End If
If DR.AField = varWrkprID Then
DR.AField = -1
TA.Update(DR)
DR.AcceptChanges()
End If
End Sub
UPDATE: Below is the test code I tried in a test site to modify the connectionString in a single instantiation of a tableadapter. It feeds a simple gridview. I tried calling this from Page_Load, Page_PreLoad, ObjectDataSource_Init, and Gridview_Databind. At the concluding response.writes, the wrkNewConnString looks changed to TestDB2, and the TA.Connection.ConnectionString value looks changed to TestDB2, but the displayed gridview data is still from TestDB1. Maybe it needs to be called from somewhere else?
Sub ChangeTableAdapter()
Dim wrkNewConnStr As String = ""
Dim wrkSel As Integer
wrkSel = 2
wrkNewConnStr = wrkNewConnStr & "Data Source=.\SQLEXPRESS;"
wrkNewConnStr = wrkNewConnStr & "AttachDbFilename=D:\9000_TestSite\App_Data\TESTDB1.MDF;Integrated Security=True;User Instance=True"
Select Case wrkSel
Case 1
wrkNewConnStr = wrkNewConnStr.Replace("TESTDB1", "TESTDB1")
Case 2
wrkNewConnStr = wrkNewConnStr.Replace("TESTDB1", "TESTDB2")
Case 3
wrkNewConnStr = "Data Source=localhost; Initial Catalog=test01;"
wrkNewConnStr = wrkNewConnStr & " User ID=testuser1; Password=testuserpw1"
End Select
Try
Dim TA As New DataSetTableAdapters.NamesTableAdapter
TA.Connection.ConnectionString = wrkNewConnStr
Response.Write("1 - " & wrkNewConnStr)
Response.Write("<br/>")
Response.Write("2 - " & TA.Connection.ConnectionString)
Catch ex As Exception
Dim exmsg As String = ex.Message
Response.Write(exmsg)
End Try
End Sub
The connection string:
<add name="TestDB1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=D:\9000_TestSite\App_Data\TESTDB1.MDF;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
UPDATE: the following post has lots of solutions, however, they seem to focus on web application projects, that have a project file with settings, which this web site project does not.
link with possible solutions
UPDATE: this next link was brought to my attention, and in working on it I did get it to work, however, it still relies either on having a web application project (with project file) or modifying each table adapter as they are instantiated. So, while I'm not going to implement it, I believe that is the technical answer.
modifying connection strings
sorry if this answer is too late, but I have exactly the same problem and eventually came up with a solution using Reflection.
My solution was to "save" a new default value for the connection string in the settings at run time, which means any further use of the table adapter uses the the new connection string.
It should be noted the term "save" is misleading as the new value is lost when the application closes.
Have tested and worked perfectly.
public void ChangeDefaultSetting(string name, string value)
{
if (name == null)
throw new ArgumentNullException("name");
if (value == null)
throw new ArgumentNullException("value");
Assembly a = typeof({Put the name of a class in the same assembly as your settings class here}).Assembly;
Type t = a.GetType("{Put the full name of your settings class here}");
PropertyInfo propertyInfo = t.GetProperty("Default");
System.Configuration.ApplicationSettingsBase def = propertyInfo.GetValue(null) as System.Configuration.ApplicationSettingsBase;
//change the "defalt" value and save it to memory
def[name] = value;
def.Save();
}

'instance failure' error while connection string is correct

I have following code on page load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
con = New SqlConnection("Data Source=14GRAFICALI\\SQLEXPRESS;Initial Catalog=sagar;Integrated Security=True")
'-----------------------fill name ddl------------------------------'
Try
da = New SqlDataAdapter("select EmpName from empMaster_VB", con)
ds = New DataSet()
da.Fill(ds)
For i As Integer = 0 To ds.Tables(0).Rows.Count
ddlName.Items.Add(ds.Tables(0).Rows(i)(0).ToString())
Next
Catch ex As Exception
End Try
'--------------------------------------------------------------------'
'----------------fill expence-------------------------------------'
Try
da = New SqlDataAdapter("select ExpName from expenceType_VB", con)
ds = New DataSet()
da.Fill(ds)
For i As Integer = 0 To ds.Tables(0).Rows.Count
ddlExpence.Items.Add(ds.Tables(0).Rows(i)(0).ToString())
Next
Catch ex As Exception
End Try
'---------------------------------------------------------------'
End Sub
This code is to fill drop downs with names and expence values in database tables.
I am getting 'instance failure' error while executing the code.
I checked one of the answers on stack and checked my connection string. But, my connection string is also correct.
Please help me if anything else is missing in this code.
As you got the error "instance failure", that might be the error with your SQL Server instance..
Make sure your SQL Server instance(MSSQLSERVER) is running, where you can check in: Services list. TO get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter. That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS instead.. :)
Happy Coding... :)
I have connection:
Data Source=MyComputerName\SQL2012ENTERPRS;Initial Catalog=RESTFUL; User Id=myuser; Password=mypass123;
My server is : MyComputerName\SQL2012ENTERPRS
But since I use string, I add more \ so, at my code It will be:
public string connectionString = "Data Source=DAFWKN409C67Q\\SQL2012ENTERPRS;Initial Catalog=RESTFUL; User Id=rest_user; Password=rest_pwd_01;";
I have forgoten that I must remove one of \ since I am not use default string block, I use XML file to save my connection string. Then everything is ok. So, my suggestion is your instance name is not correct.
This is my connection string sample it I use local pc using SQL express:
string servername = #"Data Source=.\SQLExpress;Initial Catalog=Workshop;Integrated Security=True";
You should modify with your server name, and instance name by yourself, make sure it correct.
I had this issue because I got the connection string from appsettings.Development.json:
"Server=msi\\DataBaseName;Database=Super25;Trusted_Connection=True;"
but when I changed to
"Data Source=msi\DataBaseName;Initial Catalog=Super25;Integrated Security=True;"
solved!
in my case just kick up the double \\ to one slush \
:=)
The root cause is Regular literal ("Backslash: \") and Verbatim literal ("#"Backslash: \"") .
Reference https://csharpindepth.com/Articles/Strings
Use the wildcard "#" before "Data Source" declaration. someting like this:
connetionString = #"Data Source=...
So you'll be able to use only a back slash. Like this: #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\jcabarros...
I know this is an old thread, but perhaps a good update. I couldn't find a good answer on the web search.
I got the same 'Instance Failed' error when trying to reference a DbContext from another project in the same solution. The 1st project had a DbContext and the connection string, and the 2nd project in the solution was trying to reference it. The 1st app ran ok on its own, issue only occurred when running the 2nd app.
The issue was that the app.config file that had the connection string from the 1st project was not in view/scope of the 2nd project. So the connection string wasn't assembled.
My solution was to copy the app.config from the first project to the second project.
This was on VS 2019.
Hope this helps
Your answer lies in the connected services. edit provider and select the three dots once you find your database select advanced in the advanced you will see your connection string which looks like below.
Data Source=Server\ServerInstance;Initial Catalog=yourDatabaseName;Integrated Security=True
You can add more services and configure more there.

ASP javascript how to create an SQL SELECT statement using prepared statement

I am using ASP javascript to select from a MySQL database using a parameter passed by the user.
I would like to do this using a prepared statement. I have seen examples in VB script but can't figure it out in ASP JS.
I would normally do it in the following way:
var adoConnection = Server.CreateObject("ADODB.Connection");
adoConnection.Open("dsn=my-dsn;uid=userid;pwd=password;");
var getAdmin = "SELECT * FROM users WHERE username = '"+String(Request.QueryString("username"))+"'";
var rsAdmin = adoConnection.Execute(getAdmin);
I would like to change this to pass the user data in a safer way, can anyone help?
to parametrize correctly in ASP your Queries, you need to use "ADODB.Command" to execute your queries instead of using ADODB.Connection directly. ADODB.Command has method named ".CreateParameter()" that permits that you want.
Example code
'-------------------------------------------------------------------'
var oCmd = Server.CreateObject("ADODB.Command")
var sSQL = "SELECT username, action FROM userlog WHERE event_date < ? ;";
oCmd.CommandText = sSQL
oCmd.ActiveConnection= oConn
'-------------------------------------------------------------------'
var oPar = oCmd.CreateParameter("event_date",7,1,,dDate); 'Date
oCmd.Parameters.Append(oPar);
'-------------------------------------------------------------------'
.... do this until you have all the parameters appended and ....
var oRS = oCmd.Execute();
and you manipule the recordset as you wish
Aditional resources
ADODB Documentation
MSDN Example
ASP javascript is usually reffered to as JScript. If you search for '[jscript] [mysql]' on stackoverflow it will show you a question which will probably answer your question:
ADODB Command failing Execute with parameterised SQL query
You could also google 'msdn jscript ado' for additional samples.
Although calling into a database directly from browser-side code isn't a preferred method of retrieving data into the page (most folks prefer AJAX/JSON requests these days...), you could definitely improve the security of your code by converting the SQL statement to a stored procedure call.
For details, see http://andrewu.co.uk/clj/stored_procedures_with_jscript/

ASP to SQL Server connection basics?

I apologize in advance if the question is too noobish. I am new to the ASP and SQL server world (i've been using PHP and MySQL up to this point) (I've read other topics here, but none seemed to give me a clear answer)
I want to connect my ASP website to my SQL database (using sql server 2005 currently), how would i do that? I've been trying to use numerous connection strings, but everything seems confusing to me right now (too many varieties)
Also, how do i execute queries after making a succesful connection?
I believe an answer to those two would get me started on, i hope i'm not asking for much or something. Thanks in advance!
Dim objDbCon
Dim dataCount
Dim sqlQuery
Set objDbCon = Server.CreateObject("ADODB.Connection")
'Change the parameters with your own environment'
objDbCon.ConnectionString = "Provider=SQLOLEDB; Data Source=120.120.120.120; Initial Catalog=Database name; User Id=user1; Password=1234;"
objDbCon.Open
'Put sql script which you want to get result set'
sqlQuery = "SELECT COUNT(*) AS CNT FROM TABLE_NAME"
'This is how you execute sql script and bind the result set to dataset object'
Set Rs = objDbCon.Execute(sqlQuery)
dataCount = Rs("CNT")
Rs.Close
To add sql connection to a asp.net webpage, First we have to get the connection string.
For that open server explorer ->Data connections ->add connection.
Give the servername and database name in the given popup box.
After adding the connection take the property window of added connection, From there we will get the connection string.
After that write the following code:
using System.Data;
using System.Data.SqlClient;
public void dbconnection
{
SqlConnection con;
con = new SqlConnection("connectionstring");
con.Open();
SqlCommand cmd=new SqlCommand("Your sql query",con);
cmd.ExecuteNonQuery();
con.close();
}
for insert,update and delete queries we use ExecuteNonQuery().
for select queries we use
SqlDataReader dr = cmd.ExecuteReader();

ADODB.Recordset error '800a0bb9' : Arguments are of the wrong type

Set rsPlanID = Server.CreateObject("ADODB.Recordset")
rsPlanID.CursorLocation = adUseClient
strSQL = "SELECT PlanID FROM ATTJournals WHERE ATTUserDataID = " & ATTUserDataID
rsPlanID.Open strSQL, m_objConn, adOpenStatic, adLockOptimistic
If Not rsPlanID.EOF Then
response.Write "New PlanID:" & rsPlanID("PlanID")
End If
The above code is in classic asp.
I am getting the following error:
ADODB.Recordset error '800a0bb9'
Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
Dows anyone know the cause this error and how to fix it?
The most like cause is that you haven't included "ADOVBS.INC" or the equavalent META:-
<!--METADATA
TYPE="TypeLib"
NAME="Microsoft ActiveX Data Objects 2.6 Library"
UUID="{00000206-0000-0010-8000-00AA006D2EA4}"
VERSION="2.6"
-->
Hence the adxxxx constants do not exist. However your primary mistake is not including Option Explicit at the top your script. This will save you bucket loads of time hunting silly mistakes and typos.
BTW What happens if ATTUserDataID contained "0; DELETE ATTJournals;" ?
Avoid composing SQL using concatenation like the plague. Search for "ASP SQL Injection" to find examples of using parameterised command objects instead.
Unless you need to navigate back and forth in the recordset, just use the default settings:
strSQL = "SELECT PlanID FROM ATTJournals WHERE ATTUserDataID = " & ATTUserDataID
Set rsPlanID = m_objConn.Execute(strSQL)
Also, your code is wide open for SQL Injection attacks - you better learn about it and change your code to use Parameters instead.
I feel like I searched the whole internet and couldn't find the solution to this problem, and just as I was about to give up, I realized that I had declared my connection variable within an "If" statement and because the if statement did not execute neither did my command to the database giving the error as mentioned in your question.
First, when I devoleped application with vbscript I used always the numbers to open a recordset. I recommend following line:
rsPlanID.Open strSQL, m_objConn, 3, 3
Make sure that you include the file adovbs.inc first. The numbers are conntected to the different types of recordset properties. And don't foregt to open the databse connection first.
Second, I think you don't need the line
rsPlanID.CursorLocation = adUseClient
Thrird, see also this thread. Maybe it is a good template for you.
Function SQL_getRecordset(strQuery)
'On Error Resume Next
'Create Database connection object
Set objConnection = CreateObject("ADODB.Connection")
'Create Recordset object
Set objrecordset = CreateObject("ADODB.Recordset")
'Specify the connection string
strConnectionstring = "Provider=SQLOLEDB.1;Data Source=*<Server name>*;Initial Catalog=*<database>*;Integrated Security=SSPI"
objConnection.Open strConnectionstring
'Execute the Query
Set objrecordset = objConnection.Execute(strQuery)
'Return Recordset
Set SQL_getRecordset = objrecordset
'Release objects from the memory
Set objConnection = Nothing
Set objrecordset = Nothing
End Function

Resources