I am having problem wrapping my head around this problem.
If you run the query embedded in code below, it shows Total Questions (TotalQuestions) asked, Total Correct (TotalCorrect2) and percentage correct (PercentCorrect2).
We have students who participate in video tutorials.
After each lesson, they are given quizzes, a total of 30 questions.
To pass through each segment of the tutorials, a student must score at least 80% of the quizzes.
The code below is calculating Total questions, total correct and percentage correct.
Here is where I am having issues.
If a student answers all 30 questions AND gets 80% or more of the questions correct, a certificate is exposed to the student so s/he can print his or her certificate.
If both criteria is not met, the certificate stays hidden from the student.
I am having difficulty with the IF portion of this task.
For instance,
if totalQuestions = 30 and percentCorrect2 >= 80 then
btnGetUser.Visible = True
else
btnGetUser.Visible = False
end if
This above is not working.
When I run the code, and a particular user meets the condition of the IF statement, the certificate is supposed to be exposed. It does so when I run it in SSMS.
So far, the certificate has remained hidden even though I am testing with users who have taken and passed the tests and have made the conditions.
When I debug the code, I can see that totalQuestions shows 30 which is correct but the rest show 0.
Any ideas what I could be doing wrong?
Dim s As String = ";WITH Questions AS " & _
" ( SELECT SQ.QuestionID, " & _
" CorrectChoices = COUNT(NULLIF(SC.IsCorrect, 0)), " & _
" ChoicesGiven = COUNT(SA.ChoiceID), " & _
" CorrectChoicesGiven = COUNT(CASE WHEN SA.ChoiceID IS NOT NULL AND SC.IsCorrect = 1 THEN 1 END), " & _
" ExtraChoicesGiven = CASE WHEN COUNT(SA.ChoiceID) > COUNT(NULLIF(SC.IsCorrect, 0)) THEN COUNT(SA.ChoiceID) - COUNT(NULLIF(SC.IsCorrect, 0)) ELSE 0 END " & _
" FROM SurveyQuestions SQ " & _
" INNER JOIN SurveyChoices SC " & _
" ON SQ.QuestionId = SC.QuestionID " & _
" LEFT JOIN SurveyAnswers SA " & _
" ON SA.QuestionId = SC.QuestionID " & _
" AND SA.ChoiceID = SC.ChoiceID " & _
" AND SA.UserName = #username " & _
" GROUP BY SQ.QuestionID " & _
" ), QuestionScores AS " & _
" (SELECT QuestionID, " & _
" Score = CASE WHEN CorrectChoicesGiven - ExtraChoicesGiven < 0 THEN 0 " & _
" ELSE CAST(CorrectChoicesGiven - ExtraChoicesGiven AS FLOAT) / CorrectChoices " & _
" END, " & _
" Score2 = ISNULL(CAST(CorrectChoicesGiven AS FLOAT) / NULLIF(CASE WHEN ChoicesGiven > CorrectChoices THEN ChoicesGiven ELSE CorrectChoices END, 0), 0) " & _
" FROM Questions " & _
" )
" SELECT TotalQuestions = COUNT(*), " & _
" TotalCorrect = SUM(Score), " & _
" PercentCorrect = CAST(100.0 * SUM(Score) / COUNT(*) AS DECIMAL(5, 2)), " & _
" TotalCorrect2 = SUM(Score2), " & _
" PercentCorrect2 = CAST(100.0 * SUM(Score2) / COUNT(*) AS DECIMAL(5, 2)) " & _
" FROM QuestionScores;"
Dim connStr As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand(s, conn)
Dim TotalQuestions As Integer
Dim TotalCorrect As Double
Dim TotalPercent As Decimal
Dim TotalCorrect2 As Double
Dim TotalPercent2 As Decimal
conn.Open()
cmd.Parameters.AddWithValue("#username", username.Text)
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
TotalQuestions = reader.GetInt32(0)
TotalCorrect = reader.GetDouble(1)
TotalPercent = reader.GetDecimal(2)
TotalCorrect2 = reader.GetDouble(3)
TotalPercent2 = reader.GetDecimal(4)
End If
reader.Close()
conn.Close()
If TotalQuestions = 30 and TotalPercent2 >= 80 Then
btnGetUser.Visible = True
Else
btnGetUser.Visible = False
End If
Related
Im getting this error :
System.InvalidCastException: Conversion from string "" to type 'Double' is not valid. ---> System.FormatException: Input string was not in a correct format.
at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value, NumberFormatInfo NumberFormat)
--- End of inner exception stack trace ---
at Microsoft.VisualBasic.CompilerServices.Conversions.ToDouble(String Value, NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObject2(Object Left, Object Right, Boolean TextCompare)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object Left, Object Right, Boolean TextCompare)
I have already tried SQL statement and its already working properly .Fields "goals1" and "goals2" are defined as int and "tipp1" and "tipp2" defined varchar(50) . I have tried to convert goals to string didnt work , also tried to convert tipps to int and also it didn't work .And that is the code :
Private Sub mdlCalculate()
Try
Dim _sql As String = "SELECT DISTINCT username FROM fly_tippspiel_tipps"
Dim _dt As DataTable = cData.getDataTable(_sql, 5, GetCurrentMethod.Name, ControlName)
If _dt.Rows.Count < 1 Then Exit Sub
_sql = "DELETE FROM fly_tippspiel_ranking"
cData.exeNonQuery(_sql, 5, GetCurrentMethod.Name, ControlName)
For Each _row As DataRow In _dt.Rows
_sql = "SELECT Table1.goals1, Table1.goals2, Table1.result1, Table1.tipp1, Table1.tipp2, Table1.result2," & _
" ISNULL(Table2.iCount,0) AS iCount" & _
" FROM (" & _
" SELECT fly_tippspiel_games.id, fly_tippspiel_games.goals1, fly_tippspiel_games.goals2, fly_tippspiel_games.result AS result1," & _
" fly_tippspiel_tipps.tipp1, fly_tippspiel_tipps.tipp2, fly_tippspiel_tipps.result AS result2" & _
" FROM fly_tippspiel_games" & _
" INNER JOIN fly_tippspiel_tipps ON fly_tippspiel_games.id = fly_tippspiel_tipps.games_id" & _
" WHERE (fly_tippspiel_tipps.username = '" & _row("username") & "')" & _
" AND (NOT (fly_tippspiel_games.goals1 IS NULL))) AS Table1" & _
" FULL JOIN" & _
" (SELECT fly_tippspiel_games.id, COUNT(fly_tippspiel_games.id) AS iCount" & _
" FROM fly_tippspiel_games" & _
" INNER JOIN fly_tippspiel_tipps ON fly_tippspiel_games.id = fly_tippspiel_tipps.games_id" & _
" WHERE goals1 = tipp1 AND goals2 = tipp2" & _
" GROUP BY fly_tippspiel_games.id) AS Table2" & _
" ON Table1.id = Table2.id" & _
" WHERE NOT Table1.goals1 IS NULL"
Dim _dt1 As DataTable = cData.getDataTable(_sql, 5, GetCurrentMethod.Name, ControlName)
Dim _sum As Integer = 0
For Each _row1 As DataRow In _dt1.Rows
If _row1("goals1") = _row1("tipp1") And _row1("goals2") = _row1("tipp2") And _row1("iCount") = "1" Then
_sum = _sum + 5 ' alleiniges genaues Ergebnis
ElseIf _row1("goals1") = _row1("tipp1") And _row1("goals2") = _row1("tipp2") Then
_sum = _sum + 3 ' genaues Ergebnis
ElseIf _row1("result1") = _row1("result2") Then
_sum = _sum + 1 ' Trend
End If
Next
_sql = "INSERT INTO fly_tippspiel_ranking (username, points) " & _
"VALUES ('" & _row("username") & "', " & _sum & ")"
cData.exeNonQuery(_sql, 5, GetCurrentMethod.Name, ControlName)
Next
Catch ex As Exception
cData.exMessage(ex.ToString, GetCurrentMethod.Name, ControlName)
End Try
End Sub
I'm trying to find a match in a column, return the range of that match, then display a message box with values derived from cells offset from that match's range. But I get error code 91 when I run this. I'm not a great coder, so any extra details you can provide would be really appreciated, as sometimes I struggle to understand the answers provided if it's too jargony.
I was using the find function, but occasionally, the match I want to find is hidden via filters in the spreadsheet, and I read somewhere that the match function won't be affected by whether the cells are filtered or not.
Sub GetInfo2()
Dim Item As String
Dim FindRng As Range
Item = InputBox("What is the item number?", "Item Number")
FindRng = Application.Match(Item, Worksheets("Current Week Summary").Columns(1), 0)
If Not FindRng Is Nothing Then
MsgBox ("Description: " & FindRng.Offset(0, 4).Value & vbCrLf & _
"Flyer/FEM: " & FindRng.Offset(0, 1).Value & vbCrLf & _
"Margin Maker: " & FindRng.Offset(0, 2).Value & vbCrLf & _
"ISR Week: " & FindRng.Offset(0, 3).Value & vbCrLf & _
"Amount To Sell: " & Round(FindRng.Offset(0, 7).Value, 0) & vbCrLf & _
"Cost: $" & FindRng.Offset(0, 18).Value & vbCrLf & _
"Months of Supply: " & Round(FindRng.Offset(0, 35).Value, 0) & vbCrLf & _
"E&O Qty: " & FindRng.Offset(0, 17)), vbOKOnly, Item
End If
End Sub
I did overcome the issue of not being able to search in filtered rows. I ended up using the VLookup Function to find my matches. It apparently searches whether it's filtered or not. I'm still stumped on how to use the match function, so I'd love to know how to do that. But this solved my problem in the interim.
Sub GetInfo()
Dim Item As String
Dim Description As String
Dim FlyerFEM As String
Dim MargMak As String
Dim ISR As String
Dim ATS As String
Dim Cost As String
Dim Supply As String
Dim EAO As String
Item = InputBox("What is the item number?", "Item Number")
Description = WorksheetFunction.VLookup(Item, Range("A:AJ"), 5, False)
FlyerFEM = WorksheetFunction.VLookup(Item, Range("A:AJ"), 2, False)
MargMak = WorksheetFunction.VLookup(Item, Range("A:AJ"), 3, False)
ISR = WorksheetFunction.VLookup(Item, Range("A:AJ"), 4, False)
ATC = WorksheetFunction.VLookup(Item, Range("A:AJ"), 8, False)
Cost = WorksheetFunction.VLookup(Item, Range("A:AJ"), 19, False)
Supply = WorksheetFunction.VLookup(Item, Range("A:AJ"), 36, False)
EAO = WorksheetFunction.VLookup(Item, Range("A:AJ"), 18, False)
MsgBox ("Description: " & Description & vbCrLf & _
"Flyer/FEM: " & FlyerFEM & _
"Margin Maker: " & MargMak & vbCrLf & _
"ISR Week: " & ISR & vbCrLf & _
"Amount To Sell: " & Round(ATC, 0) & vbCrLf & _
"Cost: $" & Cost & vbCrLf & _
"Months of Supply: " & Supply & vbCrLf & _
"E&O Qty: " & Round(EAO, 0)), vbOKOnly, Item
End Sub
I have the following VB.net code that updates the row from Boundedfields using the identifying the cell number.
Protected Sub grvPos_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles grvPos.RowUpdating
Dim cs As String
Dim con As iDB2Connection
Dim sql As String
Dim cmd As iDB2Command
Dim valDate As Integer
Dim portCode As String
Dim secCode As String
Dim valType As String
Dim portName As String
Dim ISINno As String
Dim secName As String
Dim secCcyAbbr As String
Dim trxBccy As Decimal
Dim quantity As Integer
Dim mktPrice As Integer
Dim avgCost As Integer
Dim avgBvalSc As Integer
Dim avgBvalBc As Integer
Dim intAmtSc As Integer
Dim intAmtBc As Integer
Dim gr As GridViewRow
gr = grvPos.Rows(e.RowIndex)
valDate = grvPos.DataKeys(gr.RowIndex).Values("VALN_DATE")
portCode = grvPos.DataKeys(gr.RowIndex).Values("PORT_CODE").ToString()
secCode = grvPos.DataKeys(gr.RowIndex).Values("SEC_CODE").ToString()
valType = grvPos.Rows(gr.RowIndex).Cells(2).ToString()
portName = grvPos.Rows(gr.RowIndex).Cells(4).ToString()
ISINno = grvPos.Rows(gr.RowIndex).Cells(6).ToString()
secName = grvPos.Rows(gr.RowIndex).Cells(7).ToString()
secCcyAbbr = grvPos.Rows(gr.RowIndex).Cells(8).ToString()
trxBccy = grvPos.Rows(gr.RowIndex).Cells(9).ToString()
quantity = CInt(grvPos.Rows(gr.RowIndex).Cells(10).ToString())
mktPrice = CInt(grvPos.Rows(gr.RowIndex).Cells(11).ToString())
avgCost = CInt(grvPos.Rows(gr.RowIndex).Cells(14).ToString())
avgBvalSc = CInt(grvPos.Rows(gr.RowIndex).Cells(15).ToString())
avgBvalBc = CInt(grvPos.Rows(gr.RowIndex).Cells(16).ToString())
intAmtSc = CInt(grvPos.Rows(gr.RowIndex).Cells(17).ToString())
intAmtBc = CInt(grvPos.Rows(gr.RowIndex).Cells(18).ToString())
cs = ConfigurationManager.ConnectionStrings("ConnectionStringDB2").ConnectionString
con = New iDB2Connection(cs)
sql = "MERGE INTO GICPFDTA.OPTR_POS_FIX O " &
"USING OLYFPRO.FDBVAL F ON O.SEC_CODE = F.VLVALR " &
"AND (O.VALN_DATE = #VALN_DATE) " &
"AND (O.PORT_CODE = #PORT_CODE) " &
"AND (O.SEC_CODE = #SEC_CODE) " &
"WHEN MATCHED THEN UPDATE SET " &
"O.VAL_TYPE = #VAL_TYPE " &
",O.PORT_SNAME = #PORT_SNAME " &
",O.ISIN_NO = #ISIN_NO " &
",O.SEC_SNAME = #SEC_SNAME " &
",O.SEC_CCY_ABBR = #SEC_CCY_ABBR " &
",O.TRX_BCCY_EX_RATE = #TRX_BCCY_EX_RATE " &
",O.QUANTITY = #QUANTITY " &
",O.MKT_PRICE = #MKT_PRICE " &
",O.AVG_COST = #AVG_COST " &
",O.AVG_BVAL_SC = #AVG_BVAL_SC " &
",O.AVG_BVAL_BC = #AVG_BVAL_BC " &
",O.INT_AMT_SC = #INT_AMT_SC " &
",O.INT_AMT_BC = #INT_AMT_BC " &
",O.MVAL_AMT_SC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
"), 3) " &
",O.MVAL_AMT_BC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
") / #TRX_BCCY_EX_RATE, 3)"
cmd = New iDB2Command(sql, con)
cmd.Parameters.AddWithValue("#VALN_DATE", valDate)
cmd.Parameters.AddWithValue("#PORT_CODE", portCode)
cmd.Parameters.AddWithValue("#SEC_CODE", secCode)
cmd.Parameters.AddWithValue("#VAL_TYPE", valType)
cmd.Parameters.AddWithValue("#PORT_SNAME", portName)
cmd.Parameters.AddWithValue("#ISIN_NO", ISINno)
cmd.Parameters.AddWithValue("#SEC_SNAME", secName)
cmd.Parameters.AddWithValue("#SEC_CCY_ABBR", secCcyAbbr)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#AVG_COST", avgCost)
cmd.Parameters.AddWithValue("#AVG_BVAL_SC", avgBvalSc)
cmd.Parameters.AddWithValue("#AVG_BVAL_BC", avgBvalBc)
cmd.Parameters.AddWithValue("#INT_AMT_SC", intAmtSc)
cmd.Parameters.AddWithValue("#INT_AMT_BC", intAmtBc)
Try
lblError.Text = ""
Using con
con.Open()
cmd.ExecuteNonQuery()
gridLoad()
End Using
Catch ex As Exception
Throw
End Try
End Sub
The trxBccy variable is Numeric data type, but I specified it as Decimal, I also tried Integer data type.
When I try to update a row I get the following error:
Conversion from string "System.Web.UI.WebControls.DataCo" to type 'Decimal' is not valid.
I appreciate any help.
Thanks in advance
I was able to capture the values from the bounded fields using the below code.
Protected Sub grvPos_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles grvPos.RowUpdating
Dim cs As String
Dim con As iDB2Connection
Dim sql As String
Dim cmd As iDB2Command
Dim valDate As Integer
Dim portCode As String
Dim secCode As String
Dim valType As String
Dim portName As String
Dim ISINno As String
Dim secName As String
Dim secCcyAbbr As String
Dim trxBccy As Decimal
Dim quantity As Decimal
Dim mktPrice As Decimal
Dim avgCost As Decimal
Dim avgBvalSc As Decimal
Dim avgBvalBc As Decimal
Dim intAmtSc As Decimal
Dim intAmtBc As Decimal
Dim gr As GridViewRow
gr = grvPos.Rows(e.RowIndex)
valDate = grvPos.DataKeys(gr.RowIndex).Values("VALN_DATE")
portCode = grvPos.DataKeys(gr.RowIndex).Values("PORT_CODE").ToString()
secCode = grvPos.DataKeys(gr.RowIndex).Values("SEC_CODE").ToString()
valType = e.NewValues("VAL_TYPE").ToString()
portName = e.NewValues("PORT_SNAME").ToString()
ISINno = e.NewValues("ISIN_NO").ToString()
secName = e.NewValues("SEC_SNAME").ToString()
secCcyAbbr = e.NewValues("SEC_CCY_ABBR").ToString()
trxBccy = e.NewValues("TRX_BCCY_EX_RATE").ToString()
quantity = e.NewValues("QUANTITY").ToString()
mktPrice = e.NewValues("MKT_PRICE").ToString()
avgCost = e.NewValues("AVG_COST").ToString()
avgBvalSc = e.NewValues("AVG_BVAL_SC").ToString()
avgBvalBc = e.NewValues("AVG_BVAL_BC").ToString()
intAmtSc = e.NewValues("INT_AMT_SC").ToString()
intAmtBc = e.NewValues("INT_AMT_BC").ToString()
cs = ConfigurationManager.ConnectionStrings("ConnectionStringDB2").ConnectionString
con = New iDB2Connection(cs)
sql = "MERGE INTO GICPFDTA.OPTR_POS_FIX O " &
"USING OLYFPRO.FDBVAL F ON O.SEC_CODE = F.VLVALR " &
"AND (O.VALN_DATE = #VALN_DATE) " &
"AND (O.PORT_CODE = #PORT_CODE) " &
"AND (O.SEC_CODE = #SEC_CODE) " &
"WHEN MATCHED THEN UPDATE SET " &
"O.VAL_TYPE = #VAL_TYPE " &
",O.PORT_SNAME = #PORT_SNAME " &
",O.ISIN_NO = #ISIN_NO " &
",O.SEC_SNAME = #SEC_SNAME " &
",O.SEC_CCY_ABBR = #SEC_CCY_ABBR " &
",O.TRX_BCCY_EX_RATE = #TRX_BCCY_EX_RATE " &
",O.QUANTITY = #QUANTITY " &
",O.MKT_PRICE = #MKT_PRICE " &
",O.AVG_COST = #AVG_COST " &
",O.AVG_BVAL_SC = #AVG_BVAL_SC " &
",O.AVG_BVAL_BC = #AVG_BVAL_BC " &
",O.INT_AMT_SC = #INT_AMT_SC " &
",O.INT_AMT_BC = #INT_AMT_BC " &
",O.MVAL_AMT_SC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
"), 3) " &
",O.MVAL_AMT_BC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
") / #TRX_BCCY_EX_RATE, 3)"
cmd = New iDB2Command(sql, con)
cmd.Parameters.AddWithValue("#VALN_DATE", valDate)
cmd.Parameters.AddWithValue("#PORT_CODE", portCode)
cmd.Parameters.AddWithValue("#SEC_CODE", secCode)
cmd.Parameters.AddWithValue("#VAL_TYPE", valType)
cmd.Parameters.AddWithValue("#PORT_SNAME", portName)
cmd.Parameters.AddWithValue("#ISIN_NO", ISINno)
cmd.Parameters.AddWithValue("#SEC_SNAME", secName)
cmd.Parameters.AddWithValue("#SEC_CCY_ABBR", secCcyAbbr)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#AVG_COST", avgCost)
cmd.Parameters.AddWithValue("#AVG_BVAL_SC", avgBvalSc)
cmd.Parameters.AddWithValue("#AVG_BVAL_BC", avgBvalBc)
cmd.Parameters.AddWithValue("#INT_AMT_SC", intAmtSc)
cmd.Parameters.AddWithValue("#INT_AMT_BC", intAmtBc)
Try
lblError.Text = ""
Using con
con.Open()
cmd.ExecuteNonQuery()
grvPos.EditIndex = -1
gridLoad()
End Using
Catch ex As Exception
Throw
End Try
End Sub
The solution that works for me is:
sqlstr = "declare "
sqlstr &= "#returnId int "
sqlstr &= " BEGIN TRANSACTION " & _
" INSERT INTO sales ([user_name],[password],[full_Name],[email]) " & _
" VALUES (#user_name,#password,#full_Name,#email) " & _
" set #returnId = (select SCOPE_IDENTITY()) " & _
" INSERT INTO Sales_trade ([id_s],[trade]) " & _
" VALUES (#returnId,#trade) " & _
"IF (##error <> 0) " & _
" ROLLBACK TRANSACTION " & _
" ELSE COMMIT TRANSACTION "
cmd = New SqlCommand(sqlstr, myConn)
Dim par1 As New SqlParameter
par1.ParameterName = "#user_name"
par1.Value = unam
cmd.Parameters.Add(par1)
'Do the same for all other parameters
cmd.ExecuteNonQuery()
myConn.Close()
This is how it worked for me, the code I did for parameter (par1) is the same all for the rest..
Initially i suggest you to parametrized your query to avoid sql injection.
Create a transaction and use the sql statement something like the above:
sqlstr = " BEGIN TRANSACTION " & _
" INSERT INTO sales ([user_name],[password],[full_Name],[email]) " & _
" VALUES (#user_name,#password,#full_Name,#email) " & _
" set #returnId = (select SCOPE_IDENTITY()) " & _
" INSERT INTO Sales_trade ([id_s],[trade]) " & _
" VALUES (#returnId,#trade) " & _
"IF (##error <> 0) " & _
" ROLLBACK TRANSACTION " & _
" ELSE COMMIT TRANSACTION "
dim par as new SqlParameter
par.Name = "#user_name"
par.Value = "test"
.... do this for all parameters
cmd.Parameters.Add(par)
Please forgive me for asking too many questions.
I have been working on this all day and can't take it anymore.
I have a stored proc called sp_signup()
The stored proc first checks to see if the user has already signed up. If yes, then inform the user that s/he has already signed up for this class.
SET #ERROR = 'You have already signed up for this training'
This works a treat.
If no, then check to see if there are still available seats.
If seats are still available, sign the user up by inserting into training table and inform the user s/her has been signed up.
SET #ERROR = 'You have been registered for this class'
This works a treat.
If no seats remain, then put the user on waiting list by inserting the user's registration info into waitingList table and inform the user s/he has been placed on waiting list.
SET #ERROR = 'Sorry, but this class is full. However, you have been placed on waiting list.'
This works a treat as well.
So, the stored proc, when tested, works great.
However, on our .net app that calls the stored proc, we are sending users emails informing them that they have either been signed up for the class or have been placed on waiting list depending on what the #Error message says.
This is where we are having problem because the email is not going out.
Here are the conditionals for sending email:
If Label1.Text = "You have been registered for this class" Then
'Email code goes here and is sent to inform users they have been registered for class
ElseIf Label1.Text = "Sorry, but this class is full. However, you have been placed on waiting list." Then
'Email code goes here and is sent inform to users they have been placed on waiting list
Else
End If
below is where the stored procedure call is made:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username = Session("Username")
Try
Dim s As String
s = "sp_signup"
Dim connStr As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim conn As New SqlConnection(connStr)
Dim cmd = New SqlCommand(s, conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#cosID", Request.QueryString("cosId"))
cmd.Parameters.AddWithValue("#locID", Request.QueryString("locid"))
cmd.Parameters.AddWithValue("#dat", Request.QueryString("iddate"))
cmd.Parameters.AddWithValue("#UserName", username)
cmd.Parameters.Add("#ERROR", SqlDbType.[Char], 500)
cmd.Parameters("#ERROR").Direction = ParameterDirection.Output
conn.Open()
cmd.ExecuteNonQuery()
message = DirectCast(cmd.Parameters("#ERROR").Value, String)
Dim cmdGetKey As New SqlCommand("SELECT ##IDENTITY", conn)
Dim skey As Integer = cmdGetKey.ExecuteScalar()
Session("TrainingId") = skey
conn.Close()
btnSendEmail_Click()
'Display some feedback to the user to let them know it was processed
Label1.ForeColor = System.Drawing.Color.Green
Label1.Text = message
Catch
'If the message failed at some point, let the user know
Label1.ForeColor = System.Drawing.Color.Red
Label1.Text = message
End Try
End Sub
The email code has been tested and works without the stored proc and is below:
Protected Sub btnSendEmail_Click()
Dim skey As Integer = Session("TrainingId")
'Response.Write(skey)
'Response.End()
Dim Conn As SqlConnection
'Dim param As SqlParameter
'Dim cmdcommand As SqlCommand
Conn = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString)
Conn.Open()
If Label1.Text = "You have been registered for this class" Then
Dim emailcmd As New SqlCommand("select distinct lg.Email, lg.fullname, c.CourseName, l.location, d.trainingDates, d.trainingTime, i.instructorName from tblTrainings t Inner Join tblCourses c on t.courseId = c.courseId " & _
" Inner Join tblLocations l on t.locationId = l.LocationId " & _
" Inner Join tblTrainingDates d on t.dateid=d.dateid " & _
" Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
" Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
" Inner Join tblLogin lg on t.username = lg.username where lg.username = '" & Session("username") & "' AND t.CourseID = " & Request.QueryString("cosId") & " AND t.LocationID = " & Request.QueryString("locid") & " AND t.dateId = " & Request.QueryString("iddate") & " AND TrainingId = " & skey & ";", Conn)
Dim dr = emailcmd.ExecuteReader()
If dr.Read() Then
email = dr.GetString(0)
fullname = dr.GetString(1)
courses = dr.GetString(2)
Loc = dr.GetString(3)
tdates = dr.GetDateTime(4)
ttime = dr.GetString(5)
End If
'code for other email requests
Dim objSmtpClient As SmtpClient = New SmtpClient("relay.smtp", 25)
Dim objSender As MailAddress = New MailAddress("name.emailadd.com", "name.emailadd.com")
Dim objMail As MailMessage = New MailMessage("name.emailadd.com", "name.emailadd.com")
objMail.Bcc.Add("name.emailadd.com")
objMail.To.Add(email)
'objMail.CC.Add("name.emailadd.com")
objMail.Subject = "About Your Training: " & courses & ""
objMail.Body = " Dear " & fullname & " <br>You have just signed up for <b>" & courses & "</b> training. <br><br>This training will be held at <b>" & Loc & "</b> on <b>" & tdates & "</b> starting from <b>" & ttime & "</b>.<br><br> For more details about this training, please visit <a href='Training/'> Training/</a>. "
objMail.IsBodyHtml = True
objSmtpClient.Send(objMail)
dr.Close()
ElseIf Label1.Text = "Sorry, but this class is full. However, you have been placed on waiting list." Then
Dim waitcmd As New SqlCommand("select distinct lg.Email, lg.fullname, c.CourseName, wl.location, d.trainingDates, d.trainingTime, i.instructorName from tblWaitingList wl Inner Join tblCourses c on wl.courseId = c.courseId " & _
" Inner Join tblLocations l on wl.locationId = l.LocationId " & _
" Inner Join tblTrainingDates d on wl.dateid=d.dateid " & _
" Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
" Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
" Inner Join tblLogin lg on wl.username = lg.username where lg.username = '" & Session("username") & "' AND wl.CourseID = " & Request.QueryString("cosId") & " AND wl.LocationID = " & Request.QueryString("locid") & " AND wl.dateId = " & Request.QueryString("iddate") & " AND TrainingId = " & skey & ";", Conn)
Dim dr = waitcmd.ExecuteReader()
If dr.Read() Then
email = dr.GetString(0)
fullname = dr.GetString(1)
courses = dr.GetString(2)
Loc = dr.GetString(3)
tdates = dr.GetDateTime(4)
ttime = dr.GetString(5)
End If
'code for other email requests
Dim objSmtpClient As SmtpClient = New SmtpClient("relay.smtp", 25)
Dim objSender As MailAddress = New MailAddress("name.emailadd.com", "name.emailadd.com")
Dim objMail As MailMessage = New MailMessage("name.emailadd.com", "name.emailadd.com")
objMail.Bcc.Add("name.emailadd.com")
objMail.To.Add(email)
'objMail.CC.Add("name.emailadd.com")
objMail.Subject = "About Your Training: " & courses & ""
objMail.Body = " Dear " & fullname & " <br>You have been placed on the waiting list for <b>" & courses & "</b> training. <br><br>This training will be held at <b>" & Loc & "</b> on <b>" & tdates & "</b> starting from <b>" & ttime & "</b>.<br><br> Should a seat become available, notification will be based on first-come, first-served bases.<br>For more details about this training, please visit <a href='http://#/'> http://Training/</a>. "
objMail.IsBodyHtml = True
objSmtpClient.Send(objMail)
dr.Close()
Else
End If
End Sub
I guess you have the order of the following statements wrong:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
...
btnSendEmail_Click()
...
Label1.Text = message
I think you should set Label1.Text before calling btnSendEmail_Click(). It should be the other way round:
Label1.Text = message
...
btnSendEmail_Click()