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)
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
Am using Telerik RadGantt chart. i need to insert the event to the data base for that am using the code as given:
Private Sub RadGantt1_TaskUpdate(ByVal sender As Object, ByVal e As Telerik.Web.UI.Gantt.TaskEventArgs) Handles RadGantt1.TaskUpdate
mssql = "insert into project " & _
" (ParentID, OrderID, Title, Start, End, PercentComplete, Expanded, Summary)" & _
" values('E1','" & e.Tasks.GetEnumerator.Current.ID & "', " & _
" '" & e.Tasks.GetEnumerator.Current.Title & "'," & _
" '" & e.Tasks.GetEnumerator.Current.Start & "'," & _
" '" & e.Tasks.GetEnumerator.Current.End & "'," & _
" '" & e.Tasks.GetEnumerator.Current.PercentComplete & "'," & _
" '" & e.Tasks.GetEnumerator.Current.Expanded & "'," & _
" '" & e.Tasks.GetEnumerator.Current.Summary & "')"
Dim mycommand As OdbcCommand
mycommand = New OdbcCommand(mssql, dbcon)
dbcon.Open()
Dim mnresult As Integer = mycommand.ExecuteNonQuery()
If mnresult = 1 Then
EventAdd = False
End If
End Sub
But it gives an object reference error in e.Tasks.GetEnumerator.Current.ID. then how can i take the value from this event?
e.Tasks is a collection so you should iterate through it (e.g., in a for..each loop).
To get a single tasks whose properties you can read you should use the enumerator of the collection, for example e.Tasks(1).GetEnumerator.Current.ID
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
My Gridview won't page or sort. By this I mean that the data in the GridView doesn't change when I try to sort by a column or when I try to page through the GridView.
I have it inside an UpdatePanel on a user control (.ascx). The code below works fine when I try it outside of the user control.
Here's my code:
<asp:GridView runat="server" ID="grdStats" AutoGenerateColumns="false" Width="100%" AllowSorting="true"
AllowPaging="true" PageSize="20" PagerSettings-Mode="NumericFirstLast" PagerSettings-Position="TopAndBottom">
<Columns>
<asp:BoundField DataField="campaignname" HeaderText="Campaign Name" SortExpression="campaignname" />
<asp:BoundField DataField="site_name" HeaderText="Outlet" SortExpression="site_name" />
<asp:BoundField DataField="filename" HeaderText="Media" SortExpression="filename" />
<asp:BoundField DataField="playinterval" HeaderText="Play Interval" SortExpression="playinterval" />
</Columns>
</asp:GridView>
Here's the backend:
Protected Sub grdStats_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdStats.PageIndexChanging
grdStats.PageIndex = e.NewPageIndex
GetCampaignData()
End Sub
Protected Sub grdStats_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdStats.Sorting
If e.SortExpression = ViewState("sortExpr") Then
ViewState("sortExpr") = e.SortExpression & " desc"
Else
ViewState("sortExpr") = e.SortExpression
End If
GetCampaignData()
End Sub
' ######## POPULATE DATA #########
Private Sub GetCampaignData(Optional ByVal CompanyID As Integer = 0)
Dim sql As String = Nothing
' Check user access level.
If Session("userlevel") = 1 Then
' Current user is admin.
' If a company has been filtered, get it's data, else, get all campaign data.
If CompanyID <> 0 Then
sql = "SELECT" & vbCrLf & _
" a.campaignid," & vbCrLf & _
" a.companyid," & vbCrLf & _
" a.campaignname," & vbCrLf & _
" a.filename," & vbCrLf & _
" startdate," & vbCrLf & _
" enddate," & vbCrLf & _
" a.playinterval," & vbCrLf & _
" a.ActiveStatus," & vbCrLf & _
" b.*," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS c" & vbCrLf & _
" WHERE DAY(date_played) = DAY(CURRENT_DATE)" & vbCrLf & _
" AND c.campaignid = a.campaignid" & vbCrLf & _
" ) AS today," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS d" & vbCrLf & _
" WHERE date_played > CURRENT_DATE - INTERVAL 7 DAY" & vbCrLf & _
" AND d.campaignid = a.campaignid" & vbCrLf & _
" ) AS past_week," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS e" & vbCrLf & _
" WHERE e.campaignid = a.campaignid" & vbCrLf & _
" ) AS playcount" & vbCrLf & _
"FROM campaigns AS a" & vbCrLf & _
"INNER JOIN companies AS b ON a.companyid = b.companyid" & vbCrLf & _
"WHERE a.ActiveStatus = 1" & vbCrLf & _
"AND a.companyid = " & CompanyID
Else
sql = "SELECT" & vbCrLf & _
" a.campaignid," & vbCrLf & _
" a.companyid," & vbCrLf & _
" a.campaignname," & vbCrLf & _
" a.filename," & vbCrLf & _
" startdate," & vbCrLf & _
" enddate," & vbCrLf & _
" a.playinterval," & vbCrLf & _
" a.ActiveStatus," & vbCrLf & _
" b.*," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS c" & vbCrLf & _
" WHERE DAY(date_played) = DAY(CURRENT_DATE)" & vbCrLf & _
" AND c.campaignid = a.campaignid" & vbCrLf & _
" ) AS today," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS d" & vbCrLf & _
" WHERE date_played > CURRENT_DATE - INTERVAL 7 DAY" & vbCrLf & _
" AND d.campaignid = a.campaignid" & vbCrLf & _
" ) AS past_week," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS e" & vbCrLf & _
" WHERE e.campaignid = a.campaignid" & vbCrLf & _
" ) AS playcount" & vbCrLf & _
"FROM campaigns AS a" & vbCrLf & _
"INNER JOIN companies AS b ON a.companyid = b.companyid" & vbCrLf & _
"WHERE a.ActiveStatus = 1"
End If
Else
' User is not an admin.
sql = "SELECT" & vbCrLf & _
" a.campaignid," & vbCrLf & _
" a.companyid," & vbCrLf & _
" a.campaignname," & vbCrLf & _
" a.filename," & vbCrLf & _
" startdate," & vbCrLf & _
" enddate," & vbCrLf & _
" a.playinterval," & vbCrLf & _
" a.ActiveStatus," & vbCrLf & _
" b.*," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS c" & vbCrLf & _
" WHERE DAY(date_played) = DAY(CURRENT_DATE)" & vbCrLf & _
" AND c.campaignid = a.campaignid" & vbCrLf & _
" ) AS today," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS d" & vbCrLf & _
" WHERE date_played > CURRENT_DATE - INTERVAL 7 DAY" & vbCrLf & _
" AND d.campaignid = a.campaignid" & vbCrLf & _
" ) AS past_week," & vbCrLf & _
" (SELECT COUNT(*)" & vbCrLf & _
" FROM campaignstats AS e" & vbCrLf & _
" WHERE e.campaignid = a.campaignid" & vbCrLf & _
" ) AS playcount" & vbCrLf & _
"FROM campaigns AS a" & vbCrLf & _
"INNER JOIN companies AS b ON a.companyid = b.companyid" & vbCrLf & _
"WHERE a.ActiveStatus = 1" & vbCrLf & _
"AND a.companyid = " & CInt(Session("companyid"))
End If
grdCampaigns.DataSource = get_data(sql)
grdCampaigns.DataBind()
For i As Integer = 0 To grdCampaigns.Rows.Count - 1
grdCampaigns.Rows(i).Cells(2).Text = Microsoft.VisualBasic.Left(grdCampaigns.Rows(i).Cells(2).Text, 10)
grdCampaigns.Rows(i).Cells(3).Text = Microsoft.VisualBasic.Left(grdCampaigns.Rows(i).Cells(3).Text, 10)
Next
End Sub
Public Function get_data(ByVal SQLStatement As String) As DataView
'Populates the datatable
Dim dt As Data.DataTable
dt = db.GetDataTable(SQLStatement)
Dim dv As System.Data.DataView = New System.Data.DataView(dt)
If Not ViewState("sortExpr") Is Nothing Then
dv.Sort = ViewState("sortExpr")
Else
dv = dt.DefaultView
End If
Session("dv5") = dv
Return dv
End Function
Any help would be greatly appreciated.
My apologies the code I pasted in the question, although correct for it's purpose, was not the right code relevant to this question. That said, I'd like to thank you Icarus for taking the time to look over my code.
The paging/sorting works. What I did to fix it was to replace the call to GetCampaignData() within the PageIndexChanging and Sorting event handlers to the SQL code and data binding methods required to give me the results I needed.
I can't seem to figure out why the below code is giving me the following error:
Object reference not set to an instance of an object.
Line 47: objSQLCommand.Connection.Open()
This is the problem code:
Function getTabContent() As String
Dim strUserInitials() As String = Request.ServerVariables("LOGON_USER").Split(CChar("\"))
strUser = LCase(Trim(strUserInitials(strUserInitials.GetUpperBound(0)))).ToString()
objStringBuilder = New StringBuilder()
For intColumn As Integer = 1 To 3
objSQLCommand = New SqlCommand("select c.*, w.* " & _
"from intranet.dbo.tabs t " & _
"inner join intranet.dbo.columns c on t.id = c.tabs_id " & _
"inner join intranet.dbo.widgets w on c.widgets_id = w.widget_id " & _
"where t.is_default = 0 " & _
"and t.cms_initials = #user " & _
"and t.id = #tab " & _
"and c.sort_column = #column " & _
"and w.inactive = 0 " & _
"order by c.tabs_id, c.sort_column, c.sort_row", objSQLConnection)
objSQLCommand.Parameters.Add("#user", SqlDbType.VarChar, 3).Value = strUser
objSQLCommand.Parameters.Add("#tab", SqlDbType.Int, 4).Value = Request.QueryString("tab")
objSQLCommand.Parameters.Add("#column", SqlDbType.Int, 4).Value = intColumn
objStringBuilder.Append("<div class=""column"" id=""column_" & intColumn & """>")
objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()
While objSQLDataReader.Read()
objStringBuilder.Append("<div class=""portlet"" id=""portlet_" & objSQLDataReader("widget_id") & """>")
objStringBuilder.Append("<div class=""portlet-header"">" & objSQLDataReader("widget_name") & "</div>")
objStringBuilder.Append("<div class=""portlet-content"">" & objSQLDataReader("widget_description") & "</div>")
objStringBuilder.Append("</div>")
End While
objSQLDataReader.Close()
objSQLCommand.Connection.Close()
objStringBuilder.Append("</div>")
Next intColumn
Return objStringBuilder.ToString
End Function
The problem appears to be that the Connection property on objSqlCommand is Nothing and hence you get a NullReferenceException when you access it. This means in all likely hood that objSqlConnection is also Nothing and that is likely the root cause of your problem.
Connection is an object of type SqlConnection. You need to create an instance of this object before you can interact with it. Something like this:
Dim connection As New SqlConnection("your_connection_string")
objSQLCommand.Connection = connection
objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()
Instead of doing this
objSQLCommand.Connection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()
While objSQLDataReader.Read()
objStringBuilder.Append("<div class=""portlet"" id=""portlet_" & objSQLDataReader("widget_id") & """>")
objStringBuilder.Append("<div class=""portlet-header"">" & objSQLDataReader("widget_name") & "</div>")
objStringBuilder.Append("<div class=""portlet-content"">" & objSQLDataReader("widget_description") & "</div>")
objStringBuilder.Append("</div>")
End While
objSQLDataReader.Close()
objSQLCommand.Connection.Close()
just do
objSQLConnection.Open()
objSQLDataReader = objSQLCommand.ExecuteReader()
While objSQLDataReader.Read()
objStringBuilder.Append("<div class=""portlet"" id=""portlet_" & objSQLDataReader("widget_id") & """>")
objStringBuilder.Append("<div class=""portlet-header"">" & objSQLDataReader("widget_name") & "</div>")
objStringBuilder.Append("<div class=""portlet-content"">" & objSQLDataReader("widget_description") & "</div>")
objStringBuilder.Append("</div>")
End While
objSQLConnection.Close()