Related
I am creating an ASP.Net website with VB.Net as code behind and this is the error that appears from the published version on a web server (this does not appear when run directly from the code or from the published version on the IIS server):
error message screenshot
This is a snippet from the controller:
Function Index(ByVal pSurveyName As String) As ActionResult
Try
If IsNothing(pSurveyName) Then
Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
End If
Dim l_question As Object = GetQuestion()
Return View(l_question)
Catch ex As Exception
Call ExceptionHandler(ex)
Return View()
End Try
End Function
Function GetQuestion() As Object
Dim l_questionnaire = Session("ActiveQuestionnaire")
Dim l_surveySession = Session("SurveySession")
Dim l_redirectQueue = Session("RedirectQueue")
Dim l_sessionAnswers = Session("SessionAnswers")
Dim l_CurrentQuestion As CurrentItem = New CurrentItem
Dim l_Choices As List(Of Choice) = New List(Of Choice)
Dim l_TempDBQuestions = db.Questions
Dim l_TempDBChildQuestions = db.ChildQuestions
Dim l_TempDBChoices = db.Choices
Dim l_tempFiltered_Q
Dim li_questionnaireID As Integer
Dim li_questionCtr As Integer
Dim li_total_NoOfQuestion As Integer = 0
Dim li_resultCount As Integer = 0
Dim li_childQID As Integer = 0
Dim ls_prevAnswer As String = ""
Dim ls_err As String = ""
Try
li_questionnaireID = l_questionnaire.ID
li_questionCtr = l_surveySession.QuestionCtr
If Session("Back") = False Then
li_questionCtr = GetQuestionCtr(NEXT_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers,, ls_prevAnswer)
Else
Dim l_current = Session("CurrentQuestion")
li_questionCtr = GetQuestionCtr(PREVIOUS_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers, l_current, ls_prevAnswer)
End If
l_tempFiltered_Q = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
li_resultCount = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr)).Count
If li_resultCount = 0 Then
l_tempFiltered_Q = l_TempDBChildQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
Session("FrmChildQuestions") = True
Else
Session("FrmChildQuestions") = False
End If
For Each item In l_tempFiltered_Q
'item could be from Questions or ChildQuestions
If li_resultCount = 0 Then
Session("IsNextQuestionChild") = item.IsNextQuestionChild
End If
With l_CurrentQuestion
.ID = item.ID
.QuestionnaireID = item.QuestionnaireID
.QuestionOrder = item.QuestionOrder
.Description = item.Description
.AnswerType = item.AnswerType
.AllowMultipleAnswers = item.AllowMultipleAnswers
.QuestionNo = item.QuestionNo
.Required = item.Required
.TempAnswer = ls_prevAnswer
End With
Next
If l_CurrentQuestion.AnswerType = constants.MULTIPLE_CHOICE Then
'Get Choices
Dim li_questionID As Integer = l_CurrentQuestion.ID
If li_resultCount = 0 Then
l_Choices = db.Choices.SqlQuery("select * from Choices where ChildQuestionID = " & li_questionID & "").ToList
Else
l_Choices = db.Choices.SqlQuery("select * from Choices where QuestionID = " & li_questionID & "").ToList
End If
Session("Choices") = l_Choices
End If
If Session("TotalQuestions") Is Nothing Then
li_total_NoOfQuestion = db.Database.SqlQuery(Of Integer) _
("select max(a.MaxOrder) from(select max(QuestionOrder) " &
"as MaxOrder from Questions union select QuestionOrder from " &
"ChildQuestions)a").FirstOrDefault
Session("TotalQuestions") = li_total_NoOfQuestion
End If
With l_surveySession
.QuestionCtr = li_questionCtr
End With
Session("SurveySession") = l_surveySession
Session("CurrentQuestion") = l_CurrentQuestion
Session("Back") = False
Return l_CurrentQuestion
Catch ex As Exception
Call ExceptionHandler(ex)
End Try
End Function
And this is from the view:
#ModelType Survey_App.Models.CurrentItem
#Code
ViewData("Title") = "Index"
Layout = "~/Views/Shared/_Layout.vbhtml"
Dim l_choices = Session("Choices")
Dim l_activeSurvey = Session("ActiveSurvey")
Dim ls_tempAnsType As String = Model.AnswerType.ToString 'this is the line indicated in the error msg
Dim ls_temp As String = ""
Dim ls_tempAnswer() As String = Nothing
Dim li_totalQuestions As Integer = 0
li_totalQuestions = Session("TotalQuestions")
Dim ls_POSTAction As String = vbNullString
The error appears some time (maybe 10-15 seconds) after going through the home page but not always immediately. I also tried some debugging and it looks like the session variables also return nothing after that some time.
The code below is causing me some real headaches. It was written probably two years ago and has been chugging away ever since, but we've noticed that sometimes the insert query will run twice, and sometimes not at all. The code basically takes integer and decimal values from webpage (aspx) labels and inserts them into a master table.
The problem lately seems to be affected by the number of users on the system. When there is only one person using it there seems to be no issue, but with multiple users the problems start to occur. I was using session variables rather than labels but as a process of elimination i stopped using these.
If anyone can help or give me some pointers that would be great, many thanks.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
'local
Dim subidString As String = "SELECT [Submission_ID], [Week Ending] FROM tbl_Weekly_Expenses WHERE [Submission_ID] = #SubID AND [Week Ending] = #WeekEnding AND [SentToPayroll] IS NULL"
'local
Dim mtdString As String = "SELECT SUM([Mileage Covered]) AS SumOfMileageCovered FROM tbl_Weekly_Expenses WHERE [Gabem Employee Reference] = #NovaRef"
'remote
Dim vehicleString As String = "SELECT [Vehicle] FROM tblExpensesMileage WHERE [SubID] = #SubID"
'local
Dim insertString As String = "INSERT INTO tbl_Weekly_Expenses ([Week Ending], [Date Expenses Processed], [Expenses_From], [Expenses_To], [Date Expenses received], [Gabem Employee Reference], [Identifying Number], [Submission_ID], [Car], [Motorcycle], [Pushbike], [Mileage Covered], [Mileage Amount Claimed], [Accommodation], [Meal Allowance], [Daily Allowance], [Tools/Clothing], [Details_Of_Tools], [Travel Amount], [Telephone], [Professional Fees], FuelVAT, MAVAT, TAVAT, AVAT, DAVAT, TCVAT, TelVAT, PfVAT, processedby) " & _
"VALUES (#WeekEnding, #DateProcessed, #ExpensesFrom, #ExpensesTo, #DateReceived, #NovaRef, #IdentifyingNumber, #SubID, #Car, #Motorcycle, #Pushbike, #MileageCovered, #MileageAmountClaimed, #Accommodation, #Meals, #DailyAllowance, #ToolsClothing, #ToolsDetails, #Travel, #TelephoneCalls, #ProfessionalFees, #FuelVAT, #MAVAT, #TAVAT, #AVAT, #DAVAT, #TCVAT, #TelVAT, #PfVAT, #processedby)"
'remote
Dim updateMileage As String = "UPDATE tblExpensesMileage SET [Status] = 'Processed' WHERE [MileageID] = #id"
Dim updateAccommodation As String = "UPDATE tblExpensesAccommodation SET [Status] = 'Processed' WHERE [AccommodationID] = #id"
Dim updateMeals As String = "UPDATE tblExpensesMeals SET [Status] = 'Processed' WHERE [MealsID] = #id"
Dim updateLaundry As String = "UPDATE tblExpensesLaundry SET [Status] = 'Processed' WHERE [LaundryID] = #id"
Dim updateDailyAllowance As String = "UPDATE tblExpensesDailyAllowance SET [Status] = 'Processed' WHERE [DailyAllowanceID] = #id"
Dim updateTravel As String = "UPDATE tblExpensesTravel SET [Status] = 'Processed' WHERE [TravelID] = #id"
Dim updateTools As String = "UPDATE tblExpensesTools SET [Status] = 'Processed' WHERE [ToolsID] = #id"
Dim updateTelephoneCalls As String = "UPDATE tblExpensesTelephoneCalls SET [Status] = 'Processed' WHERE [TelephoneCallsID] = #id"
Dim updateProfessionalFees As String = "UPDATE tblExpensesProfessionalFees SET [Status] = 'Processed' WHERE [ProfessionalFeesID] = #id"
Dim dbconnLocal As String = ConfigurationManager.ConnectionStrings("connection_nbsas2").ConnectionString
Dim dbconnRemote As String = ConfigurationManager.ConnectionStrings("connection_nbsa_web").ConnectionString
If txtWEDate.Text = String.Empty Then
Exit Sub
End If
Using myConnectionLocal As New SqlConnection(dbconnLocal)
myConnectionLocal.Open()
'VEHICLE TYPE AND PPM STARTS
Dim Car As Integer = 0
Dim Motorcycle As Integer = 0
Dim Pushbike As Integer = 0
Dim ppm As Decimal
Using myConnectionRemote As New SqlConnection(dbconnRemote)
myConnectionRemote.Open()
'Vehicle type
Dim cmdSelectVehicle As New SqlCommand(vehicleString, myConnectionRemote)
cmdSelectVehicle.Parameters.AddWithValue("#SubID", Session("subid"))
Dim readerVehicle As SqlDataReader = cmdSelectVehicle.ExecuteReader()
readerVehicle.Read()
If readerVehicle.HasRows = True Then
'MTD value for pence per mile (ppm)
Dim cmdSelectMTD As New SqlCommand(mtdString, myConnectionLocal)
cmdSelectMTD.Parameters.AddWithValue("#NovaRef", Session("novaref"))
Dim readerMTD As SqlDataReader = cmdSelectMTD.ExecuteReader()
readerMTD.Read()
If IsDBNull(readerMTD.Item(0)) = True Then
If readerVehicle.Item(0) = "Car" Then
ppm = 0.45
Car = "1"
ElseIf readerVehicle.Item(0) = "Motorcycle" Then
ppm = 0.24
Motorcycle = "1"
Else
ppm = 0.2
Pushbike = "1"
End If
Else
If readerVehicle.Item(0) = "Motorcycle" Then
ppm = 0.24
Motorcycle = "1"
ElseIf readerVehicle.Item(0) = "Car" And readerMTD.Item(0) < 10000 Then
ppm = 0.45
Car = "1"
ElseIf readerVehicle.Item(0) = "Car" And readerMTD.Item(0) > 10000 Then
ppm = 0.25
Car = "1"
Else
ppm = 0.2
Pushbike = "1"
End If
End If
readerMTD.Close()
End If
readerVehicle.Close()
myConnectionRemote.Close()
End Using
'VEHICLE TYPE AND PPM ENDS
'insert parameters etc
Dim cmdInsertWE As New SqlCommand(insertString, myConnectionLocal)
cmdInsertWE.Parameters.AddWithValue("#WeekEnding", CType(txtWEDate.Text, DateTime))
cmdInsertWE.Parameters.AddWithValue("#DateProcessed", Now())
cmdInsertWE.Parameters.AddWithValue("#ExpensesFrom", CType(lblMinDate.Text, DateTime))
cmdInsertWE.Parameters.AddWithValue("#ExpensesTo", CType(lblMaxDate.Text, DateTime))
cmdInsertWE.Parameters.AddWithValue("#DateReceived", CType(Session("daterec"), DateTime))
cmdInsertWE.Parameters.AddWithValue("#NovaRef", Session("novaref"))
cmdInsertWE.Parameters.AddWithValue("#IdentifyingNumber", "1")
cmdInsertWE.Parameters.AddWithValue("#SubID", Session("subid"))
cmdInsertWE.Parameters.AddWithValue("#Car", Car)
cmdInsertWE.Parameters.AddWithValue("#Motorcycle", Motorcycle)
cmdInsertWE.Parameters.AddWithValue("#Pushbike", Pushbike)
cmdInsertWE.Parameters.AddWithValue("#MileageCovered", CType(lblMileageNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#MileageAmountClaimed", CType(lblMileageNumber.Text, Decimal) * ppm)
cmdInsertWE.Parameters.AddWithValue("#Accommodation", CType(lblAccommodationNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#Meals", CType(lblMealsNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#DailyAllowance", CType(lblDailyAllowanceNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#ToolsClothing", CType(lblToolsNumber.Text, Decimal) + CType(lblLaundryNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#ToolsDetails", txtToolsDetails.Text)
cmdInsertWE.Parameters.AddWithValue("#Travel", CType(lblTravelNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TelephoneCalls", CType(lblTelephoneCallsNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#ProfessionalFees", CType(lblProfessionalFeesNumber.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#FuelVAT", CType(txtRec_Mileage.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#MAVAT", CType(txtRec_Meals.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TAVAT", CType(txtRec_Travel.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#AVAT", CType(txtRec_Accommodation.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#DAVAT", CType(txtRec_Daily.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TCVAT", CType(txtRec_ToolsLaundry.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#TelVAT", CType(txtRec_Telephone.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#PfVAT", CType(txtRec_ProFees.Text, Decimal))
cmdInsertWE.Parameters.AddWithValue("#processedby", Page.User.Identity.Name)
cmdInsertWE.ExecuteNonQuery()
cmdInsertWE.Dispose()
myConnectionLocal.Close()
'also clear totals labels
lblMileageNumber.Text = 0
lblAccommodationNumber.Text = 0
lblMealsNumber.Text = 0
lblLaundryNumber.Text = 0
lblDailyAllowanceNumber.Text = 0
lblTravelNumber.Text = 0
lblToolsNumber.Text = 0
txtToolsDetails.Text = String.Empty
lblTelephoneCallsNumber.Text = 0
lblProfessionalFeesNumber.Text = 0
End Using 'myConnectionLocal ENDS
'OPEN REMOTE CONNECTION AND UPDATE STATUS OF LIVE TABLES
Using myConnectionRemote As New SqlConnection(dbconnRemote)
myConnectionRemote.Open()
'Mileage()
updateCheckBoxes(MileageGridView, "MileageHeaderCheckBox", "MileageCheckBox", updateMileage, myConnectionRemote, lblMileageNumber)
'Accommodation()
updateCheckBoxes(AccommodationGridView, "AccommodationHeaderCheckBox", "AccommodationCheckBox", updateAccommodation, myConnectionRemote, lblAccommodationNumber)
'Meals()
updateCheckBoxes(MealsGridView, "MealsHeaderCheckBox", "MealsCheckBox", updateMeals, myConnectionRemote, lblMealsNumber)
'Laundry()
updateCheckBoxes(LaundryGridView, "LaundryHeaderCheckBox", "LaundryCheckBox", updateLaundry, myConnectionRemote, lblLaundryNumber)
'Daily(Allowance)
updateCheckBoxes(DailyAllowanceGridView, "DailyAllowanceHeaderCheckBox", "DailyAllowanceCheckBox", updateDailyAllowance, myConnectionRemote, lblDailyAllowanceNumber)
'Travel()
updateCheckBoxes(TravelGridView, "TravelHeaderCheckBox", "TravelCheckBox", updateTravel, myConnectionRemote, lblTravelNumber)
'Tools()
updateCheckBoxes(ToolsGridView, "ToolsHeaderCheckBox", "ToolsCheckBox", updateTools, myConnectionRemote, lblToolsNumber)
'Telephone(Calls)
updateCheckBoxes(TelephoneCallsGridView, "TelephoneCallsHeaderCheckBox", "TelephoneCallsCheckBox", updateTelephoneCalls, myConnectionRemote, lblTelephoneCallsNumber)
'Professional(Fees)
updateCheckBoxes(ProfessionalFeesGridView, "ProfessionalFeesHeaderCheckBox", "ProfessionalFeesCheckBox", updateProfessionalFees, myConnectionRemote, lblProfessionalFeesNumber)
myConnectionRemote.Close()
End Using 'myConnectionRemote ENDS
txtWEDate.Text = String.Empty
End Sub
I need some help in using a stored procedure in my case below: I have a table with a single XML column which takes in fields VoucherCode and Quantity, the data in SQL xml column looks like this:
<CampaignVoucher xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="Vouch001" Quantity="2" />
The below method will call my stored procedure to check if a particular voucher exist based on my voucher code and then either add a new row or update an existing voucher in my gridview:
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
Dim dbCommand As DbCommand = Nothing
'Dim cmd As New SqlCommand()
If TextBox1.Text = "" Or DropDownList1.SelectedIndex = 0 Then
Exit Sub
End If
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Test").ConnectionString)
Dim da As New SqlDataAdapter("SELECT CustomerID, VoucherXML FROM Customers", con)
Dim cmd As New SqlCommand("Campaign_InsertRewardsVoucher_XML", con)
cmd.CommandType = CommandType.StoredProcedure
Dim dt As New DataTable()
da.Fill(dt)
' Here we'll add a blank row to the returned DataTable
Dim dr As DataRow = dt.NewRow()
dt.Rows.InsertAt(dr, 0)
'Creating the first row of GridView to be Editable
GridView1.EditIndex = 0
GridView1.DataSource = dt
GridView1.DataBind()
'Changing the Text for Inserting a New Record
DirectCast(GridView1.Rows(0).Cells(0).Controls(0), LinkButton).Text = "Insert"
' Serialization ----------------------------
Dim cm As New CampaignVoucher(DropDownList1.SelectedValue, TextBox1.Text)
Dim serializer As New XMLserializer(cm.[GetType]())
Dim memoryStream As New MemoryStream()
Dim writer As New XmlTextWriter(memoryStream, Encoding.UTF8)
serializer.Serialize(writer, cm)
'get the stream from the writer
memoryStream = TryCast(writer.BaseStream, MemoryStream)
'apply encoding to the stream
Dim enc As New UTF8Encoding()
Dim xml As String = enc.GetString(memoryStream.ToArray()).Trim()
' -------------------------------------------
cmd.Parameters.Add("#p1", SqlDbType.VarChar, 50).Value = DropDownList1.SelectedValue
cmd.Parameters.Add("#p2", SqlDbType.Text).Value = xml
cmd.Connection = con
con.Open()
cmd.ExecuteScalar()
con.Close()
GridView1.EditIndex = -1
BindData()
TextBox1.Text = ""
End Sub
Backtrack a little, I wrote this working stored proc as shown below for the same purpose just that it was meant for a conventional storage: 1 table with a VoucherCode and Quantity column, now with the XML column, now encapsulating both VoucherCode and Quantity values, I am lost to how to rewrite my stored proc, tried different ways but apparently I made a mess out of it, please advice, thanks!:
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
#VoucherCode nvarchar(50) =NULL,
#Quantity int = NULL
--#ExistingQuantity int = NULL
AS
BEGIN
DECLARE #ExistingQuantity Int = Null
IF EXISTS (SELECT * FROM ForTest_Campaign_Voucher WHERE VoucherCode=#VoucherCode)
BEGIN
SET #ExistingQuantity = (SELECT Quantity from ForTest_Campaign_Voucher Where VoucherCode=#VoucherCode)
SET #ExistingQuantity = (#ExistingQuantity + #Quantity)
UPDATE ForTest_Campaign_Voucher SET VoucherCode=#VoucherCode, Quantity=#ExistingQuantity Where VoucherCode=#VoucherCode
END
ELSE
INSERT INTO ForTest_Campaign_Voucher(VoucherCode, Quantity) VALUES(#VoucherCode, #Quantity)
END
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
#VoucherCode nvarchar(50) =NULL,
#Quantity int = NULL
AS
BEGIN
DECLARE #ExistingQuantity Int
SET #ExistingQuantity = (SELECT xmlFieldName.value('(/CampaignVoucher/#Quantity)[1]', 'int')
FROM ForTest_Campaign_Voucher
WHERE xmlFieldName.value('(/CampaignVoucher/#VoucherCode)[1]', 'nvarchar(50)') = #VoucherCode)
IF #ExistingQuantity IS NULL
BEGIN
INSERT INTO ForTest_Campaign_Voucher
(
xmlFieldName
)
VALUES
(
'<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + #VoucherCode + '" Quantity="' + CAST(#Quantity AS NVARCHAR(16)) + '" />'
)
END
ELSE
DECLARE #NewQuantity INT
SET #NewQuantity = #ExistingQuantity + #Quantity
UPDATE ForTest_Campaign_Voucher
SET xmlFieldName='<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + #VoucherCode + '" Quantity="' + CAST(#NewQuantity AS NVARCHAR(16)) + '" />'
WHERE xmlFieldName.value('(/CampaignVoucher/#VoucherCode)[1]', 'nvarchar(50)') = #VoucherCode
END
GO
Honest, I am really trying to learn this stuff. I've been using Classic ASP for years and just switching over to .net. So far, I'm not having much fun, but I'm trying and I'm not going to quit. One of the small pieces I am struggling with is running a query then, updating the record. Even googling for examples, I having a tough time figuring out how to do something simple like:
Set objRS = Server.CreateObject ("ADODB.RecordSet")
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=G:\Inetpub\wwwroot\TestPage\TheData\TestData.mdb;" & _
"Persist Security Info=False"
SqlStr = "SELECT * " & _
"FROM Techs " & _
"WHERE UserID = " & UserID & " "
objrs.Open SqlStr, ConStr, adOpenStatic, adLockOptimistic,adCmdText
If Objrs.recordCount <> 0 Then
TechUserName = Objrs("TechUserName")
Objrs.Update
Objrs("LastLogin") = Now()
Objrs.Update
Else
Objrs.AddNew
Objrs("UserID") = UserID
Objrs.Update
End If
Objrs.Close
Set objRS = Nothing
Is it even possible? Can someone please help me do the above code in ASP.net (VB) or point me to a really good thorough tutorial on how to do this.
Thanks in advance.
ah.. first off - you are trying to do classic vb stuff with .net.
Scrap it. There are no more cursors. Its client side data you basically get back in a dataset or a data reader (or a single value)
See roughly:
http://msdn.microsoft.com/en-us/library/bh8kx08z%28v=VS.100%29.aspx
They miss the spot where they get a connection, which is basically
Dim connection as New SqlConnection("server=localhost;uid=username;pwd=whatver;")
make sure you dispose of everything when done
connection.Dispose()
once you have your dataset back - just (c# syntax)
foreach(DataRow row in yourDataSet.Tables[0].Rows)
{
Debug.WriteLine(row["YourFieldName"])
}
For a data reader, see:
http://www.developerfusion.com/article/4278/using-adonet-with-sql-server/2/
The difference is a dataset has ALL data loaded on the client side. Quite a bit different than the server side cursor stuff with ado.
A DataReader will stream the results as you scroll through them - the overhead of forming this large dataset in memory isn't there so its a bit faster.
hope this gets you started - remember SCRAP the ADO stuff. Its not used anymore.
Woo Hoo I got it!
Dim SqlStr As String
Dim ConStr As String = ConfigurationManager.ConnectionStrings("TCConStr").ConnectionString
SqlStr = "SELECT * " & _
"FROM TechUsers " & _
"WHERE TechWWID = " & Chr(34) & TechWWID & Chr(34) & " " & _
"AND TechEmplNum = " & TechEmplNum & " "
Dim CN As OleDbConnection = New OleDbConnection(ConStr)
CN.Open()
Dim DA As OleDbDataAdapter = New OleDbDataAdapter(SqlStr, CN)
Dim DS As New DataSet
DA.Fill(DS, "TechUsers")
Dim DT As DataTable = DS.Tables("TechUsers")
Dim RecCount As Integer = DT.Rows.Count
Dim CB As OleDbCommandBuilder = New OleDbCommandBuilder(DA)
If RecCount = 0 Then
DA.InsertCommand = CB.GetInsertCommand()
Dim DR As DataRow = DT.NewRow()
DR("TechName") = TechName
DR("TechWWID") = TechWWID
DR("TechEmplNum") = TechEmplNum
DR("FirstLogin") = Date.Now()
DR("LastLogin") = Date.Now()
DR("LoginCount") = 1
DT.Rows.Add(DR)
DA.Update(DS, "TechUsers")
Else
Dim DR As DataRow = DT.Rows(0)
Dim LoginCount As Integer = DR("LoginCount")
TestStuff.InnerHtml = TestStuff.InnerHtml & "<br > " & LoginCount
DA.UpdateCommand = CB.GetUpdateCommand()
DR("LastLogin") = Date.Now()
DR("LoginCount") = LoginCount + 1
DA.Update(DS, "TechUsers")
End If
CN.Close()
Thanks everyone for the clues to get this done.
Do as NoAlias told you, but watch out not make a false start.
Forget about inserting text into your SQL, remember that quotes have to doubled, etc.
Try the parameterized sql statements, like in this sample:
I have a table with 4 colunms, CollCode and CollSeq are the key, TermType and TermText are the modifiable data
The code explains how to insert, update or delete a row with parameters instaed if textvalues in the SQL.
The code is valid only for ACCESS, SQL SERVER or MYSQL require different code for the template and have different DbTypes
in the first part of the program:
' select
Dim SQLaxSelect As String = "SELECT DISTINCT CollSeq FROM SearchTerms WHERE CollCode = ? ORDER BY CollSeq"
Dim DRaxSelect As OleDbDataReader = Nothing
Dim DCaxSelect As OleDbCommand
Dim axSelP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
DCaxSelect = New OleDbCommand(SQLaxSelect, DbConn)
DCaxSelect.Parameters.Add(axSelP1)
' Insert
Dim DbConn As New OleDbConnection(SqlProv)
Dim SQLTwInsert As String = "INSERT INTO SearchTerms (CollCode, CollSeq, TermType, TermText) VALUES (?, ?, ?, ?)"
Dim DRTwInsert As OleDbDataReader = Nothing
Dim DCCTwInsert As OleDbCommand
Dim TwInsP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwInsP2 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwInsP3 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwInsP4 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
DCCTwInsert = New OleDbCommand(SQLTwInsert, DbConn)
DCCTwInsert.Parameters.Add(TwInsP1)
DCCTwInsert.Parameters.Add(TwInsP2)
DCCTwInsert.Parameters.Add(TwInsP3)
DCCTwInsert.Parameters.Add(TwInsP4)
' Delete
Dim SQLTwDelete As String = "DELETE FROM SearchTerms WHERE CollCode = ? AND CollSeq = ? AND TermType = ? AND TermText = ?"
Dim DRTwDelete As OleDbDataReader = Nothing
Dim DCCTwDelete As OleDbCommand
Dim TwDelP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwDelP2 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwDelP3 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwDelP4 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
DCCTwDelete = New OleDbCommand(SQLTwDelete, DbConn)
DCCTwDelete.Parameters.Add(TwDelP1)
DCCTwDelete.Parameters.Add(TwDelP2)
DCCTwDelete.Parameters.Add(TwDelP3)
DCCTwDelete.Parameters.Add(TwDelP4)
' Update
Dim SQLTwUpdate As String = "UPDATE SearchTerms SET TermType = ?, TermText = ? WHERE CollCode = ? AND CollSeq = ? AND TermType = ? AND TermText = ?"
Dim DRTwUpdate As OleDbDataReader = Nothing
Dim DCCTwUpdate As OleDbCommand
Dim TwUpdP1 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwUpdP2 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
Dim TwUpdP3 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwUpdP4 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwUpdP5 As New OleDbParameter("#oldTermType", OleDbType.VarChar, 4)
Dim TwUpdP6 As New OleDbParameter("#oldTermText", OleDbType.VarChar, 255)
DCCTwUpdate = New OleDbCommand(SQLTwUpdate, DbConn)
DCCTwUpdate.Parameters.Add(TwUpdP1)
DCCTwUpdate.Parameters.Add(TwUpdP2)
DCCTwUpdate.Parameters.Add(TwUpdP3)
DCCTwUpdate.Parameters.Add(TwUpdP4)
DCCTwUpdate.Parameters.Add(TwUpdP5)
DCCTwUpdate.Parameters.Add(TwUpdP6)
in the processing part of the program:
'select
axSelP1.Value = requested key value CollCode
Try
DRaxSelect = DCaxSelect.ExecuteReader()
Do While (DRaxSelect.Read())
'get value, first SELECTed value has index 0
CollSeq = GetDbIntegerValue(DRaxSelect, 0) ' routine to convert NULL in 0
Loop
Catch ex As Exception
your type of report exception
Finally
If Not (DRaxSelect Is Nothing) Then
DRaxSelect.Dispose()
DRaxSelect.Close()
End If
End Try
' Update
TwUpdP1.Value = new value TermType
TwUpdP2.Value = new value TermText
TwUpdP3.Value = key value CollCode
TwUpdP4.Value = key value CollSeq
TwUpdP5.Value = old value TermType to avoid updating a row that 1 millisecond earlier was modified by someone else
TwUpdP6.Value = old value TermText
Try
DRTwUpdate = DCCTwUpdate.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwUpdate Is Nothing) Then
DRTwUpdate.Dispose()
DRTwUpdate.Close()
End If
End Try
' Insert
TwInsP1.Value = new key value CollCode
TwInsP2.Value = new key value CollSeq
TwInsP3.Value = value TermType
TwInsP4.Value = value TermText
Try
DRTwInsert = DCCTwInsert.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwInsert Is Nothing) Then
DRTwInsert.Dispose()
DRTwInsert.Close()
End If
End Try
' Delete
TwDelP1.Value = key value CollCode
TwDelP2.Value = key value CollSeq
TwDelP3.Value = old value TermType to avoid deleting a row that 1 millisecond earlier was modified by someone else
TwDelP4.Value = old value TermText
Try
DRTwDelete = DCCTwDelete.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwDelete Is Nothing) Then
DRTwDelete.Dispose()
DRTwDelete.Close()
End If
End Try
my routine (in a Module)
Friend Function GetDbIntegerValue(ByVal Dr As OleDbDataReader, ByVal nr As Integer) As Integer
If IsDBNull(Dr.Item(nr)) Then
Return 0
Else
Return Dr.GetInt32(nr)
End If
End Function
'Add items to db'
Function recordOrder()
Dim objDT As System.Data.DataTable
Dim objDR As System.Data.DataRow
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
Dim sql As String
myCommand2.Connection = con2
con2.Open()
'variables'
Dim order_date As String
Dim coupon_ID As String
Dim customer_id As String
Dim quantity As String
'variables'
Try
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
order_date = System.DateTime.Now.Date
coupon_ID = objDR("ID")
quantity = objDR("quantity")
myCommand2.Parameters.Add("#order_date", SqlDbType.VarChar).Value = order_date
myCommand2.Parameters.Add("#coupon_ID", SqlDbType.VarChar).Value = coupon_ID
myCommand2.Parameters.Add("#customer_id", SqlDbType.VarChar).Value = custID
myCommand2.Parameters.Add("#quantity", SqlDbType.VarChar).Value = quantity
myCommand2.CommandText = "INSERT INTO orders(order_date, coupon_id, customer_id, quantity) VALUES ( #order_date ,#coupon_ID,#customer_id,#quantity)"
myCommand2.ExecuteNonQuery()
Next
Catch ex As Exception
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
The loop is not incrementing (intCounter). Please HELP...
Would you not be better to use:
For Each objDR In objDT.Rows
order_date = System.DateTime.Now.Date
coupon_ID = objDR("ID")
quantity = objDR("quantity")
myCommand2.Parameters.Add("#order_date", SqlDbType.VarChar).Value = order_date
myCommand2.Parameters.Add("#coupon_ID", SqlDbType.VarChar).Value = coupon_ID
myCommand2.Parameters.Add("#customer_id", SqlDbType.VarChar).Value = custID
myCommand2.Parameters.Add("#quantity", SqlDbType.VarChar).Value = quantity
myCommand2.CommandText = "INSERT INTO orders(order_date, coupon_id, customer_id, quantity) VALUES ( #order_date ,#coupon_ID,#customer_id,#quantity)"
myCommand2.ExecuteNonQuery()
Next
'custID' is not defined anywhere ..
anyway you should insert a break point and step in with the debugger. Then watch the data to catch which statement is causing the exception. Then modify the code accordingly to handle it.
Where you have:
For intCounter = 0 To objDT.Rows.Count - 1
Replace with:
For intCounter = 0 To objDT.Rows.Count - 1 Step 1
that will increment intCounter by 1 each loop.