nested select statements taking too long to load on SQL server - asp.net

I have a page that displays reports on a grid. The grid uses an Object data source which is bound to a class that returns data. The class itself uses standard SQL query to return a count of records and binds to a dataview. The issue we are having is that it takes about 10 minutes sometimes to load and I know there has to be a better way but cannot for the life of me, figure out what. Hoping to get some insights from anyone on how to optimize this for performance. The data class is shown below: any feedback would be appreciated. There are about 650 attorneys returned by the attorney view which is bound to 2 tables: attorneys and locations table. The view on which the counts are performed on is bound to 2 tables also: current cases and previous cases tables and that returns about 125,000 cases total. Caching is out of the question because the end user will be able to supply any start and end dates to generate the report.
Dim PendingStringBuilder As String = "((dbo.cases.attorney_id = dbo.attorneys.att_id) AND (dbo.cases.date_assigned <= #StartDate) AND (dbo.cases.closing_date >= #StartDate OR dbo.cases.closing_date IS NULL)) OR ((dbo.casepreviousattorneys.attorney_id =
dbo.attorneys.att_id) AND (dbo.casepreviousattorneys.previous_assignment_date <= #StartDate) AND (dbo.casepreviousattorneys.unassignment_date >= #StartDate OR dbo.casepreviousattorneys.unassignment_date IS NULL))"
Dim AssignedStringBuilder As String = "((dbo.cases.attorney_id = dbo.attorneys.att_id) AND (dbo.cases.date_assigned >= #StartDate) AND (dbo.cases.date_assigned <= #EndDate)) OR ((dbo.casepreviousattorneys.attorney_id = dbo.attorneys.att_id) AND (dbo.casepreviousattorneys.previous_assignment_date
>= #StartDate) AND (dbo.casepreviousattorneys.previous_assignment_date <= #EndDate))"
Dim CountTable As String = " dbo.cases WITH (NOLOCK) INNER JOIN dbo.tlkpcasetype ON dbo.cases.case_type_id = dbo.tlkpcasetype.case_type_id FULL OUTER JOIN dbo.casepreviousattorneys ON dbo.cases.case_no = dbo.casepreviousattorneys.case_no"
Dim dt As New DataTable("ReportTable")
Dim dr As DataRow
dt.Columns.Add("CasesPending", Type.[GetType]("System.Int32"))
dt.Columns.Add("CasesAssigned", Type.[GetType]("System.Int32"))
dt.Columns.Add("ProbationViolation", Type.[GetType]("System.Int32"))
dt.Columns.Add("BailOnly", Type.[GetType]("System.Int32"))
dt.Columns.Add("TotalCases", Type.[GetType]("System.Int32"))
dt.Columns.Add("AttorneyID", Type.[GetType]("System.Int32"))
dt.Columns.Add("AttorneyName", Type.[GetType]("System.String"))
dt.Columns.Add("AttorneyFirstName", Type.[GetType]("System.String"))
dt.Columns.Add("AttorneyLastName", Type.[GetType]("System.String"))
dt.Columns.Add("UnitID", Type.[GetType]("System.Int32"))
dt.Columns.Add("UnitName", Type.[GetType]("System.String"))
dt.Columns.Add("UnitType", Type.[GetType]("System.String"))
dt.Columns.Add("OfficeID", Type.[GetType]("System.Int32"))
dt.Columns.Add("Office", Type.[GetType]("System.String"))
If cn.State = ConnectionState.Closed Then cn.Open()
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
strSQL = "SELECT DISTINCT dbo.attorneys.user_id, dbo.attorneys.att_id AS AttorneyID, dbo.attorneys.first_name +' '+ dbo.attorneys.last_name AS AttorneyName, dbo.attorneys.unit_id AS UnitID, dbo.tlkpunit.unit AS UnitName, dbo.tlkpunit.unit_type AS UnitType,
dbo.tlkpunit.office_id AS OfficeID, dbo.tlkpoffice.office AS Office, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprCasesPending FROM " & CountTable & " WHERE (" & PendingStringBuilder & ")) As CasesPending, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprCasesAssigned FROM " & CountTable & " WHERE (dbo.tlkpcasetype.case_type <> 'Probation Violation') AND (dbo.tlkpcasetype.case_type <> 'Bail Only') AND (" & AssignedStringBuilder & ")) As CasesAssigned,
"
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprProbationViolation FROM " & CountTable & " WHERE (dbo.tlkpcasetype.case_type = 'Probation Violation') AND (" & AssignedStringBuilder & ")) As ProbationViolation, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprBailOnly FROM " & CountTable & " WHERE (dbo.tlkpcasetype.case_type = 'Bail Only') AND (" & AssignedStringBuilder & ")) As BailOnly, "
strSQL += "(SELECT COUNT(DISTINCT dbo.cases.case_no) AS ExprTotalCases FROM " & CountTable & " WHERE (" & AssignedStringBuilder & ")) As TotalCases "
strSQL += " FROM dbo.attorneys WITH (NOLOCK) LEFT OUTER JOIN dbo.tlkpunit ON dbo.attorneys.unit_id = dbo.tlkpunit.unit_id LEFT OUTER JOIN dbo.tlkpdivision ON dbo.tlkpunit.division_id = dbo.tlkpdivision.division_id LEFT OUTER JOIN dbo.tlkpoffice ON dbo.tlkpunit.office_id
= dbo.tlkpoffice.office_id WHERE (dbo.tlkpunit.unit <> 'test-unit') "
cmd = New SqlCommand(strSQL, cn)
cmd.Parameters.AddWithValue("#StartDate", DateAStart)
cmd.Parameters.AddWithValue("#EndDate", DateAEnd)
rdr = cmd.ExecuteReader()
While rdr.Read
If rdr("CasesPending").ToString = 0 And rdr("CasesAssigned") = 0 And rdr("ProbationViolation").ToString = 0 And rdr("BailOnly") = 0 Then
'Do not add record
Else
dr = dt.NewRow()
dr("CasesPending") = CInt(rdr("CasesPending"))
dr("CasesAssigned") = CInt(rdr("CasesAssigned"))
dr("ProbationViolation") = CInt(rdr("ProbationViolation"))
dr("BailOnly") = CInt(rdr("BailOnly"))
dr("TotalCases") = CInt(rdr("TotalCases"))
dr("AttorneyID") = rdr("AttorneyID")
dr("AttorneyName") = rdr("AttorneyName")
dr("UnitID") = rdr("UnitID")
dr("UnitName") = rdr("UnitName")
dr("UnitType") = rdr("UnitType")
dr("OfficeID") = rdr("OfficeID")
dr("Office") = rdr("Office")
dt.Rows.Add(dr)
End If
End While
rdr.Close()
cmd.Dispose()
If cn.State = ConnectionState.Open Then cn.Close()
Dim dv As New DataView(dt)
dv.Sort = "AttorneyName ASC"
Return dv

Read up on "sql execution plans" and you may want to review your table indexes. It is likely that these things will yield the greatest results. See this SQL Server Optimization MSDN article for more information.
I also notice in your VB code you are not parameterizing your SQL string. You should consider doing this after the above for additional performance benefit.
For more information on using SQL parameters see:
http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
http://technet.microsoft.com/en-us/library/ms186219.aspx

Try using a stored procedure. This will have the code compiled in the Sql Server already and the execution plan stored ahead of time. John

Related

Is there any chance on IIS or ASP.NET Web page that doesn't handle downloading a file completely?

I was reported from an user regarding a web page which I made on an ASP.NET Web site.
And still am not sure whether it's true or not.
Although the Web page was created to download data from an Oracle Database,
it seems not to download data entiley sometime, according to her.
The code which is related to what I mentioned is below,
Private Function makeCSVData() As String
Dim sb As New StringBuilder
sb.AppendLine("検索値, 検索値名称, 親品目コード, 親品名, 親単位, 子品目コード, 子品名, 子単位")
Dim strSQL As String
If RadioButtonList2.SelectedValue = 0 Then
strSQL = "SELECT Q.*, M0.品名 検索値名称 FROM (SELECT CONNECT_BY_ROOT Z.親品目コード 検索値, Z.親品目コード, M1.品名 親品名, M1.単位コード 親単位, Z.子品目コード, M2.品名 子品名, M2.単位コード 子単位 "
strSQL = strSQL & "FROM (SELECT * FROM M_BOM WHERE 使用開始日<=SYSDATE AND 使用停止日>SYSDATE) Z "
strSQL = strSQL & "LEFT OUTER JOIN M_HINMO M1 ON M1.品目コード=Z.親品目コード "
strSQL = strSQL & "LEFT OUTER JOIN M_HINMO M2 ON M2.品目コード=Z.子品目コード "
strSQL = strSQL & "START WITH Z.親品目コード IN (SELECT H.FIELD_S1 FROM SMD_GEN.T_PARAMH H WHERE H.HOSTID='" & CL_Hsn & "') "
strSQL = strSQL & "CONNECT BY PRIOR Z.子品目コード = Z.親品目コード ORDER BY 検索値, 親品目コード, 子品目コード) Q LEFT OUTER JOIN M_HINMO M0 ON M0.品目コード=Q.検索値"
Else
strSQL = "SELECT Q.*, M0.品名 検索値名称 FROM (SELECT CONNECT_BY_ROOT Z.子品目コード 検索値, Z.親品目コード, M1.品名 親品名, M1.単位コード 親単位, Z.子品目コード, M2.品名 子品名, M2.単位コード 子単位 "
strSQL = strSQL & "FROM(SELECT * FROM M_BOM WHERE 使用開始日<=SYSDATE And 使用停止日>SYSDATE) Z "
strSQL = strSQL & "LEFT OUTER JOIN M_HINMO M1 ON M1.品目コード=Z.親品目コード "
strSQL = strSQL & "LEFT OUTER JOIN M_HINMO M2 ON M2.品目コード=Z.子品目コード "
strSQL = strSQL & "START WITH Z.子品目コード IN (SELECT H.FIELD_S1 FROM SMD_GEN.T_PARAMH H WHERE H.HOSTID='" & CL_Hsn & "') "
strSQL = strSQL & "CONNECT BY PRIOR Z.親品目コード=子品目コード ORDER BY 検索値, 親品目コード, 子品目コード) Q LEFT OUTER JOIN M_HINMO M0 ON M0.品目コード=Q.検索値"
End If
System.Diagnostics.Debug.Print("###" & strSQL & "###")
Dim conn As New OracleConnection(CnStringP)
Dim cmd As New OracleCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
Try ' Open the connection
conn.Open()
Dim dr As OracleDataReader = cmd.ExecuteReader()
Do While dr.Read
sb.Append("""" & replaceDoubleQuotes(dr("検索値")) & """,")
sb.Append("""" & replaceDoubleQuotes(dr("検索値名称")) & """,")
sb.Append("""" & replaceDoubleQuotes(dr("親品目コード")) & """,")
sb.Append("""" & replaceDoubleQuotes(dr("親品名")) & """,")
sb.Append("""" & replaceDoubleQuotes(dr("親単位")) & """,")
sb.Append("""" & replaceDoubleQuotes(dr("子品目コード")) & """,")
sb.Append("""" & replaceDoubleQuotes(dr("子品名")) & """,")
sb.Append("""" & replaceDoubleQuotes(dr("子単位")) & """,")
sb.Append(vbCrLf)
Loop
conn.Close()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return sb.ToString()
End Function
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim startupScript As String
Dim dtNow As DateTime = DateTime.Now
Dim csvString As String = makeCSVData()
Dim csvFile As String
csvFile = "BOMSERCH_" & dtNow.ToString("yyyyMMddHHmmss")
Response.Clear()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=" & csvFile & ".csv")
Response.BinaryWrite(Encoding.GetEncoding("Shift-JIS").GetBytes(csvString))
Response.End()
End Sub
could you tell me the reason or what I should try, if you know?
Thank you.
Ok, so while Response write (BinaryWrite) does and should work?
I suggest using transmit file.
eg:
strFile = Server.MapPath(#"~/UpLoadFiles/" + strFileOnly);
string sMineType = MimeMapping.GetMimeMapping(strFileOnly);
Response.ContentType = sMineType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileOnly);
Response.TransmitFile(strFile);
Response.End();
However, you posted code does have response.End, and should work, but as a general rule, TransmitFile does produce better results, and for one, it does not read the whole file into memory first - but streams it out, and thus can reduce the memory load on the server. And since it streams out better, then the data stream tends to work better.
And failures can be the result of less than ideal internet connection, but TransmitFile I find tends to produce better results.
So, try code similar to above - see if this reduces the failure rates.

Can't UPDATE a large image size that was INSERTed in the database in asp.net

Here is the problem, when I insert an image (let's call it Data A) which is 1.32MB, it will be inserted successfully. But if I will insert again Data A(but it will update now because i used UPSERT, see my code), it will not be updated and it will result to connection time out.
But when i insert another data (Data B) which is only 4KB, it will also be inserted successfully and if I will insert again into it(which is update), it will be updated successfully. What can I do? I cannot understand the problem. I already made my command timeout for 2 mins but nothing happened and it just loaded forever. I also used sql transaction but it did nothing.
Here is my code:
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim strConnString As String = DataSource.ConnectionString
Using con As New SqlConnection(strConnString)
Dim SQLStr As String
Dim base64String = TextArea1.Value
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim FileSizeOfIMG As String
FileSizeOfIMG = imageBytes.Length
Dim ImageTypeDataOfImage As New SqlParameter("#Data", SqlDbType.Image)
ImageTypeDataOfImage.Value = imageBytes
SQLStr = "SELECT 1 FROM [Patient_Data].[dbo].[tbPatientImage] where HospNum='" & Session.Item("HospNum") & "'" & _
" and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Dim cmd As New SqlCommand(SQLStr, con)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
SQLStr = "UPDATE [Patient_Data].[dbo].[tbPatientImage] SET PatImage= #Data, FileSize= '" & FileSizeOfIMG.ToString & "' , TransDate = GetDate() where HospNum='" & Session.Item("HospNum") & "' and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Else
SQLStr = "INSERT INTO [Patient_Data].[dbo].[tbPatientImage](HospNum,IDNum, DoctorID, PatImage , FileType, FileName, FileSize , TransDATE) " & _
" VALUES (#HospNum,#IDNum, #DoctorID, #Data, #FileType, 'Patient Photo' , #FileSize, GETDATE())"
End If
reader.Close()
cmd.CommandText = SQLStr
cmd.Parameters.AddWithValue("#HospNum", Session.Item("HospNum"))
cmd.Parameters.AddWithValue("#IDNum", Session.Item("IDNum"))
cmd.Parameters.AddWithValue("#DoctorID", Session.Item("DoctorID"))
cmd.Parameters.AddWithValue("#FileType", lblHeader.Text)
cmd.Parameters.AddWithValue("#FileSize", FileSizeOfIMG.ToString)
cmd.Parameters.Add(ImageTypeDataOfImage)
cmd.ExecuteNonQuery()
con.Close()
GetData()
End Using
End Sub
I haven't figured out what causes this but i have figured out a remedy by having a delete query first then insert data.
SQLStr = "delete FROM [Patient_Data].[dbo].[tbPatientImage] where HospNum='" & Session.Item("HospNum") & "'" & _
" and IDNum='" & Session.Item("IDNum") & "' and FileType= '" & lblHeader.Text & "'"
Dim cmd As New SqlCommand(SQLStr, con)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
SQLStr = " INSERT INTO [Patient_Data].[dbo].[tbPatientImage](HospNum,IDNum, DoctorID, PatImage , FileType, FileName, FileSize , TransDATE) " & _
" VALUES (#HospNum,#IDNum, #DoctorID, #Data, #FileType, 'Patient Photo' , #FileSize, GETDATE())"
cmd.CommandText = SQLStr
'cmd.CommandTimeout = 120
cmd.Parameters.AddWithValue("#HospNum", Session.Item("HospNum"))
cmd.Parameters.AddWithValue("#IDNum", Session.Item("IDNum"))
cmd.Parameters.AddWithValue("#DoctorID", Session.Item("DoctorID"))
cmd.Parameters.AddWithValue("#FileType", lblHeader.Text)
cmd.Parameters.AddWithValue("#FileSize", FileSizeOfIMG)
cmd.Parameters.Add(ImageTypeDataOfImage)
cmd.ExecuteNonQuery()
con.Close()
GetData()
lblMessage.Text = "Saved."
End Using
End Sub

Customized ToolTip on MSChart Data

I'm trying to show a 'customized' ToolTip on an MSChart on an asp.net page, using vb.net
The chart displays OK, but I'm trying to get it to show the 'YEAR' as part of the tooltip, as well as the XY values.
I can't figure out how to do it.
Here's the code that I'm using to build the chart:
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
Sql = "SELECT att_Topic, att_Value, att_Year from Att "
Sql += " WHERE att_Year = '" & t_YEARS(i) & "' "
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
dt.Rows.Add(dr(0), dr(1), dr(2))
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
Chart1.DataSource = dt
Chart1.Series("Series1").XValueMember = "Topic"
Chart1.Series("Series1").YValueMembers = "Value"
Chart1.Series("Series1").ToolTip = "#VALX - #VALY"
Chart1.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
Chart1.DataBind()
Well, there may be a better answer, but I figured out a work-around anyhow ... I'm adding the YEAR to the axislabel. Then, in chart1_customize, changing the color of the bar, based on different axislabel. Seems to work.
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
showDATA = False
Sql = "SELECT att_Topic, att_Value, att_Year, att_Data from BWS_Att "
If (RBL_LIMIT.SelectedValue = 1) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Location' "
Sql += " AND att_Data IN ('" & String.Join("','", t_LOCS) & "')"
ElseIf (RBL_LIMIT.SelectedValue = 2) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Department' "
Sql += " AND att_Data IN ('" & String.Join("','", t_DEPTS) & "')"
Else
Sql += " WHERE att_Attrib = 'Company' "
End If
Sql += " AND att_Year = '" & t_YEARS(i) & "' "
Sql += " AND att_Topic IN ('" & String.Join("','", t_CATS) & "')"
Sql += " Order By att_ind"
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
'dt.Rows.Add(dr(0), dr(1), dr(2))
thisYR = dr(2).ToString
If (lastYR <> thisYR) Then
Chart1.Series("Series1").Points.Add(vbEmpty)
Chart1.Series("Series1").Points.Add(vbEmpty)
lastYR = thisYR
End If
If (showDATA = True) Then
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & "|" & dr(3).ToString & ":" & dr(0).ToString, dr(1))
Else
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & ":" & dr(0).ToString, dr(1))
End If
Chart1.Series("Series1").ToolTip = " #AXISLABEL | #VALY"
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
~~~~~~~~~~
Private Sub Chart1_Customize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Chart1.Customize
Dim C() As Drawing.Color = { _
Drawing.Color.Khaki, _
Drawing.Color.DarkSalmon, _
Drawing.Color.Goldenrod, _
Drawing.Color.MediumAquamarine, _
Drawing.Color.Tan _
}
Dim CN As Int16 = 0
Dim thisC As Int16 = 0
Dim LAST As String = String.Empty
For Each dp As System.Web.UI.DataVisualization.Charting.DataPoint In Chart1.Series("Series1").Points
Dim x As Array = dp.AxisLabel.Split(":")
If (x(0) <> "") Then
Dim H As String = x(0)
If (LAST <> H) Then
CN += 1
LAST = H
thisC = (CN Mod 5)
End If
dp.Color = C(thisC)
End If
Next
End Sub

How to do I send an email a target group based on stored procedure #Error message?

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()

Insert into Access DB (loop)

I have this code and its coming up with an INSERT INTO statement error...
Its probably something but I have been at it for a while... please help.
'Add items to db'
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
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
myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')"
myCommand2.Connection = con2
con2.Open()
myCommand2.ExecuteReader()
con2.Close()
test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" "
Next
End Function
I think you are getting an error by not enclosing the Date inside Pound signs. You have to do this in Jet (Access) when using variables not parameters.
VALUES('#" & DateTime.Now.Date & "#',...
I also took the liberty of refactoring this code for you since you are creating a new connection for each record which is bad news. Use a Try Catch Finally block and move all that stuff outside the For Loop (please see below)
Function recordOrder()
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;" <-- etc
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.Connection = con2
con2.Open()
Try
For intCounter = 0 To obDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _
& "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _
& "','" & Int32.Parse(objDR("quantity")) & "')"
myCommand2.ExecuteReader()
Next
Catch ex As Exception
'handle errors here
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
Remember to mark as answered if this helps.
I've sorted it out by removing the single quotes. Thanks everybody to contributed to this.

Resources