I ave a contact form (VS 2010 / VB / .net4), and when the client fills out the form, I get an email -- which I like, but ....
For instance, here's an e-mail I got:
Email: ivy_league_alum-at-yahoo.com
Subject: Do you guys integrate PPT?
Message: I'm looking for a PPT integrator in the Michigan area.
First_Name: Tim
Last_Name: Dewar
Organization: American Axle
Browser: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.7 (KHTML, like
Gecko) Chrome/16.0.912.75 Safari/535.7
IP Address: 184.60.79.96
Server Date & Time: 1/13/2012 11:28:59 AM
This is just a lead-generating company, so we're gonna get a lot of emails and we're gonna want them organized.
It was suggested by Jon P that I use a database to gather all these emails I'm getting, instead of MS Excel (which I wouldn't know how to do anyway). So I downloaded SQL Server Express. So now what do I do? Can someone please tell me what I have to add to the code, specifically, or what I have to do, so I can gather these emails in an organized manner? Thanks!
Addendum (I know this is long):
Specifically, my email code is:
<%# Page Title="Contact Health Nutts" Language="VB"
MasterPageFile="~/Site.master" AutoEventWireup="false"
CodeFile="contact.aspx.vb" Inherits="contact" %>
Protected Sub SubmitForm_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsValid Then Exit Sub
Dim SendResultsTo As String = "jason.weber-at-healthynutts.com"
Dim smtpMailServer As String = "smtp.healthynutts.com"
Dim smtpUsername As String = "jason.weber-at-healthynutts.com"
Dim smtpPassword As String = "********"
Dim MailSubject As String = "Form Results"
Try
Dim txtQ As TextBox = Me.FormContent.FindControl("TextBoxQ")
If txtQ IsNot Nothing Then
Dim ans As String = ViewState("hf1")
If ans.ToLower <> txtQ.Text.ToLower Or ans.ToUpper <> txtQ.Text.ToUpper Then
Me.YourForm.ActiveViewIndex = 3
Exit Sub
End If
End If
Dim FromEmail As String = SendResultsTo
Dim msgBody As StringBuilder = New StringBuilder()
Dim sendCC As Boolean = False
For Each c As Control In Me.FormContent.Controls
Select Case c.GetType.ToString
Case "System.Web.UI.WebControls.TextBox"
Dim txt As TextBox = CType(c, TextBox)
If txt.ID.ToLower <> "textboxq" Then
msgBody.Append(txt.ID & ": " & txt.Text & vbCrLf & vbCrLf)
End If
If txt.ID.ToLower = "email" Then
FromEmail = txt.Text
End If
If txt.ID.ToLower = "subject" Then
MailSubject = txt.Text
End If
Case "System.Web.UI.WebControls.CheckBox"
Dim chk As CheckBox = CType(c, CheckBox)
If chk.ID.ToLower = "checkboxcc" Then
If chk.Checked Then sendCC = True
Else
msgBody.Append(chk.ID & ": " & chk.Checked & vbCrLf & vbCrLf)
End If
Case "System.Web.UI.WebControls.RadioButton"
Dim rad As RadioButton = CType(c, RadioButton)
msgBody.Append(rad.ID & ": " & rad.Checked & vbCrLf & vbCrLf)
Case "System.Web.UI.WebControls.DropDownList"
Dim ddl As DropDownList = CType(c, DropDownList)
msgBody.Append(ddl.ID & ": " & ddl.SelectedValue & vbCrLf & vbCrLf)
End Select
Next
msgBody.AppendLine()
msgBody.Append("Browser: " & Request.UserAgent & vbCrLf & vbCrLf)
msgBody.Append("IP Address: " & Request.UserHostAddress & vbCrLf & vbCrLf)
msgBody.Append("Server Date & Time: " & DateTime.Now & vbCrLf & vbCrLf)
Dim myMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
myMessage.To.Add(SendResultsTo)
myMessage.From = New System.Net.Mail.MailAddress(FromEmail)
myMessage.Subject = MailSubject
myMessage.Body = msgBody.ToString
myMessage.IsBodyHtml = False
If sendCC Then myMessage.CC.Add(FromEmail)
Dim basicAuthenticationInfo As New System.Net.NetworkCredential(smtpUsername, smtpPassword)
Dim MailObj As New System.Net.Mail.SmtpClient(smtpMailServer)
MailObj.Credentials = basicAuthenticationInfo
MailObj.Send(myMessage)
Me.YourForm.ActiveViewIndex = 1
Catch
Me.YourForm.ActiveViewIndex = 2
End Try
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
Dim lbl As Label = Me.FormContent.FindControl("labelq")
If lbl IsNot Nothing Then
Dim rq(3) As String
rq(0) = "Is fire hot or cold?"
rq(1) = "Is ice hot or cold?"
rq(2) = "Is water wet or dry?"
Dim ra(3) As String
ra(0) = "hot"
ra(1) = "cold"
ra(2) = "wet"
Dim rnd As New Random
Dim rn As Integer = rnd.Next(0, 3)
lbl.Text = rq(rn)
ViewState("hf1") = ra(rn)
End If
End If
End Sub
</script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> <h1>CONTACT HEALTH
NUTTS AND WORK FROM THE COMFORT OF YOUR OWN HOME!
Enter your Email Address:
* Required
* Please enter a valid email address.
Subject:
* Required
Please type your message below:
* Required
First Name:
* Required
Last Name:
* Required
Phone Number:
* Required
* Please enter a valid U.S. phone number (including dashes).
City:
* Required
State/Province:
* Required
Your message has been sent. Thank you for contacting us.
Due to technical difficulty, your message may NOT have been sent.
You did not correctly answer the anti-spam question. Please go back and try again.
Don't take this the wrong way, but judging by what you've said about your lack of coding abilities, it may work out cheaper for you to get someone else to do the work for you. A competent coder should be able to knock something out for you in about an hour, probably less if he doesn't stop for coffee.
If you do really really want to do it yourself, then first off, you're going to have to find out if the hosting packing for the website includes a database or not.
Assuming you don't host the website on your local machine, then having a version of SQL Express on your machine will help you develop the code, but you won't be able to deploy it.
Completely ignoring that though, steps you want to go through are:
Create the database in SQL, then create the relevant database
table
Create a connection from the website to the database using ADO.Net
Create the code to insert the contact form data into the database table
You then need to think about how you're going to view the data once it's been collected, so you're either going to have to write something or learn SQL.
If you want some code samples to help you get going, then we need to know what language you're using (it should be C# or VB.Net) and posting the code for the contact form would help as well (obviously deleting any sensitive details, such as usernames and passwords).
EDIT:
Once you've created the database, this script should give you a basic table structure in SQL Express:
CREATE TABLE [dbo].[tblEmails](
[EmailID] [int] IDENTITY(1,1) NOT NULL,
[EmailAddress] [nvarchar](200) NOT NULL,
[Subject] [nvarchar](200) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[PhoneNumber] [nvarchar](20) NOT NULL,
[City] [nvarchar](50) NOT NULL,
[State] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_tblEmails2] PRIMARY KEY CLUSTERED
(
[EmailID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
To use it, right click on the database in SQL Express, click New Query, paste the above into the window, then hit the Execute button, refresh the database and you shouldn't see the table.
Here is a good tutorial if you're using ajax too.
http://dotnetslackers.com/articles/aspnet/Developing-an-AJAX-and-ASP-NET-4-0-Based-Online-E-mail-System-Part1.aspx
Related
I am running Windows 7 Professional. I have an MS Access frontend to an MS Access backend. The form that opens at the start of opening the frontend causes the app to crash.
Here is the code:
Private Sub Form_Open(Cancel As Integer)
Dim strMyDir As String
Dim intPos As Integer
Dim rst As dao.Recordset
Dim strSQL As String
Dim rstWhatsNew As dao.Recordset
DoCmd.ShowToolbar "Database", acToolbarNo
DoCmd.ShowToolbar "Toolbox", acToolbarNo
DoCmd.ShowToolbar "Form View", acToolbarNo
If Application.GetOption("ShowWindowsInTaskbar") = -1 Then
Application.SetOption "ShowWindowsInTaskbar", 0
End If
If DLookup("Locked", "luLockOut") <> 0 Then
MsgBox "Database is being worked on. Please try back in a couple minutes.", vbInformation, " "
DoCmd.Quit
Else
strSQL = "Select * From tblLastLogins Where UserName = '" & GetCurrentUserName() & "'"
This is where I have traced the error to: GetCurrentUserName()
Set rst = CurrentDb.OpenRecordset(strSQL)
With rst
If Not .EOF Then
.Edit
strSQL = "Select WhatsNewID From tblWhatsNew Where DateAdded >= #" & !LastLoginDate & "#"
Set rstWhatsNew = CurrentDb.OpenRecordset(strSQL)
While Not rstWhatsNew.EOF
DoCmd.OpenForm "frmWhatsNew", , , , , acDialog, rstWhatsNew!WhatsNewID
rstWhatsNew.MoveNext
Wend
rstWhatsNew.Close
Set rstWhatsNew = Nothing
Else
.AddNew
!UserName = GetCurrentUserName()
End If
!LastLoginDate = Now()
!IsLoggedIn = -1
Me.txtLastLoginID = !LastLoginID
.Update
.Close
End With
Set rst = Nothing
DoCmd.OpenForm "frmPrivacyNote"
Debug.Print Me.txtLastLoginID
End If
I need to track the username, so if GetCurrentUserName() is outdated, what is the current syntax?
Further follow up. I could not find data on Bing for GetCurrentUserName(), for good reason. It is a function within a MOD, so I need to figure out why the MOD is not getting called, or is malfunctioning.
After further delving, I found a Referenced MDB that has another function created by one of our users that is the cause of this error.
This is currently not an issue of MS Access working incorrectly. It is an issue with user created code.
GetCurrentUserName() is not defined by Access, so you should have looked at (and posted) its code.
If you are looking for the Windows user name, use this function:
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Environ("USERNAME") is easily spoofed, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
Source
The link below would suggest that
CurrentUser()
is the function
CurrentUser()
Andre, thank you very much for the insight! I found this link:
http://www.codeproject.com/Articles/1422/Getting-User-Information-Using-WSH-and-VBScript
Dim objNet
On Error Resume Next
'In case we fail to create object then display our custom error
Set objNet = CreateObject("WScript.NetWork")
If Err.Number <> 0 Then 'If error occured then display notice
MsgBox "Don't be Shy." & vbCRLF &_
"Do not press ""No"" If your browser warns you."
Document.Location = "UserInfo.html"
'Place the Name of the document.
'It will display again
End If
Dim strInfo
strInfo = "User Name is " & objNet.UserName & vbCrLf & _
"Computer Name is " & objNet.ComputerName & vbCrLf & _
"Domain Name is " & objNet.UserDomain
MsgBox strInfo
Set objNet = Nothing 'Destroy the Object to free the Memory
Inherited a SQL database with an MS Access .adp front end which is being converted to ASP.net VB. Using a conversion tool which has done a good job on most of it after debugging. It however could not convert DLookup functions used in combo boxes as it is not supported. Being relativley new to .net am unclear how to convert the DLookup function to a SQL statement. The table name: dbo.Contact
The main form name: Contact_Edit
The sub form name: Contact_Edit_Sub
There are a number of combo boxes with many Dlookup functions. Once I have one I can rework the balance. Any help with converting the statement is appreciated.
The current code is listed below:
*If Not IsDBNull(Me.Contact_Edit.Contact_Edit_Sub.Intake_Worker_Code) Then
Intake_Worker_Code_Desc.Text = DLookup("[Name]", "Staff", "Code ='" & Intake_Worker_Code.SelectedValue & "'")
Else
Intake_Worker_Code_Desc.Text = ""
End If*
Try this, where [Name] is the field and Staff is the table
SELECT [Name] FROM Staff WHERE Code = '" & Intake_Worker_Code.SelectedValue & "';
Here you can read more about what DLookup does:
http://www.techonthenet.com/access/functions/domain/dlookup.php
https://support.office.com/en-us/article/DLookup-Function-8896cb03-e31f-45d1-86db-bed10dca5937
Update based on comment
VB.Net SQL code sample
If Not IsDBNull(Me.Intake_Worker_Code) Then
Dim conn_str As String = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString
Dim myconn As New SqlConnection(conn_str)
Dim sc As New SqlCommand()
sc.CommandText = "Select [Name] FROM [Staff] WHERE (Code = '") & (Intake_Worker_Code.SelectedValue & "')"
sc.Connection = myconn
myconn.Open()
Intake_Worker_Code_Desc.Text = sc.ExecuteScalar().ToString()
myconn.Close()
Else
Intake_Worker_Code_Desc.Text = ""
End If
I am working on a site thath has to also support Danish characters (the supported languages will increase in the future).
I am using a database table - lets call it Strings - where I create a record for each string I display on my site. For example, the greeting message in the login page is entered in the database like this:
ID | Description | Text | Lang_code
1 | login | Log In | en
This is the code that pulls the lang_code from the database:
Public Shared Function GetLanguageCodeFromBrowser()
Dim language_code As String
Dim databaseConnection As New DBConnectionAdapter
Dim DataReader, DataReader1 As MySqlDataReader
Dim serverVar As String = HttpContext.Current.Request.ServerVariables("HTTP_ACCEPT_LANGUAGE")
language_code = LCase(serverVar)
Dim Query As String = "SELECT language_code FROM languages WHERE language_code = '" & LCase(language_code) & "' AND disabled = 0"
Dim Query1 As String = "SELECT language_code FROM languages WHERE language_code = '" & LCase(Left(language_code, 2)) & "' AND disabled = 0"
Dim cmdSelect As New MySqlCommand(Query, databaseConnection.connectionWebServices)
Dim cmdSelect1 As New MySqlCommand(Query1, databaseConnection.connectionWebServices)
Try
databaseConnection.OpenWebServices()
DataReader = cmdSelect.ExecuteReader
If Not DataReader.Read Then
DataReader.Dispose()
DataReader1 = cmdSelect1.ExecuteReader
If Not DataReader1.Read Then
DataReader1.Dispose()
Return language_code = "en"
Else
Return DataReader1("language_code")
End If
DataReader1 = Nothing
DataReader1.Dispose()
Else
Return DataReader("language_code")
End If
DataReader = Nothing
DataReader.Dispose()
Catch ex As Exception
' TODO Error handling
HttpContext.Current.Response.Write(ex.Message)
Finally
databaseConnection.CloseWebServices()
End Try
databaseConnection = Nothing
End Function
And I use it in the MasterPage's Page_Init event like this:
Session("language_code") = Language_from_Browser.GetLanguageCodeFromBrowser
Everything works fine in English, but when it comes to Danish, some characters are mangled.
I have tried changing this in web.config:
<globalization
fileEncoding="ISO-8859-1"
requestEncoding="ISO-8859-1"
responseEncoding="ISO-8859-1"
culture="auto"
/>
Still not working properly.
Please note that I have a default.aspx page in each one of my folders, so I dont have to bother with URL rewriting (that's how I see it a least)
The issue that i'm having is that trhough a button1 upon click shall save the data entered in the textboxes (see code) however when the page is postback the data is not saved (no confirmation message appears) then if i click again it does saves the record, sometimes takes more than 3 times until the data is stored per confirmation message.
Is this a Con.Dispose Issue??? Shall i use con.close?
Note: in the code i have Con.CLOSE however the page is deployed under Con.Dispose()
Note2: i'm planning to fix more "novice" issues found in the code but urgent question remains in the postback issue.
' *--------Empty Text Validation-------*
If TextBox10_AddData_LabInvest.Text <> "" AndAlso TextBox3_AddData_LabInvest.Text <> "" AndAlso TextBox4_AddData_LabInvest.Text <> "" AndAlso TextBox5_AddData_LabInvest.Text <> "" AndAlso TextBox6_AddData_LabInvest.Text <> "" AndAlso TextBox7_AddData_LabInvest.Text <> "" Then
' *--------SQL Insert command-------*
SqlDataSource_AddData_LabInvest.InsertCommand = "INSERT INTO [LabInvest] (ID_LabInvest, LabInvest_Load, LabInvest_SeqRef_CH, LabInvest_SeqRef_Year, LabInvest_Owner, LabInvest_Subject, LabInvest_DueDate, LabInvest_Code, LabInvest_QSNCCode, LabInvest_OpenByOwner, LabInvest_OpenDateOwner, Status_Text, Status_Int ) VALUES(#ID_LabInvest, #LabInvest_Load, #LabInvest_SeqRef_CH, #LabInvest_SeqRef_Year, #LabInvest_Owner, #LabInvest_Subject, #LabInvest_DueDate, #LabInvest_Code, #LabInvest_QSNCCode, #LabInvest_OpenByOwner, #LabInvest_OpenDateOwner, #Status_Text, #Status_Int)"
SqlDataSource_AddData_LabInvest.InsertParameters.Add("ID_LabInvest", TextBox10_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Load", "N/A")
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_SeqRef_CH", TextBox1_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_SeqRef_Year", TextBox2_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Owner", TextBox3_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Subject", TextBox4_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_DueDate", TextBox5_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_Code", TextBox6_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_QSNCCode", TextBox7_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_OpenByOwner", TextBox8_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("LabInvest_OpenDateOwner", TextBox9_AddData_LabInvest.Text)
SqlDataSource_AddData_LabInvest.InsertParameters.Add("Status_Text", "Stage 1 - Just Added")
SqlDataSource_AddData_LabInvest.InsertParameters.Add("Status_Int", "1")
Try
SqlDataSource_AddData_LabInvest.Insert()
' *--------Get Unique ID-------*
Dim Con As New SqlConnection
Dim SQL As String
Dim com As SqlCommand = Con.CreateCommand
Con.ConnectionString = "removed"
Con.Open()
SQL = "SELECT ID_LabInvest FROM LabInvest WHERE ID_LabInvest=" + TextBox10_AddData_LabInvest.Text
Dim cmd As New SqlCommand(SQL, Con)
Dim obj = cmd.ExecuteScalar()
Label1_AddData_LabInvest.Text = "Your record ID is: " + obj.ToString()
' *--------Get Stage-------*
Dim SQL2 As String
SQL2 = "SELECT Status_Text from LabInvest WHERE ID_LabInvest=" & obj
Dim cmd2 As New SqlCommand(SQL2, Con)
Dim obj2 = cmd2.ExecuteScalar()
Label2_AddData_LabInvest.Text = "Record Stage: " + obj2.ToString()
con.close()
Button4_AddData_LabInvest.Enabled = False
' *--------SQL Audit Insert command-------*
Dim Usercheck As String
Usercheck = Request.ServerVariables("LOGON_USER")
SqlDataSource_LabInvest_Audit.InsertCommand = "INSERT INTO [AuditTrial] (ID_Table, AuditTableName, AuditAction, AuditUser, AuditValue1Before, AuditValue2Before, AuditValue1After, AuditValue2After, AuditMasterReason, AuditMasterChange) VALUES(#ID_Table, #AuditTableName, #AuditAction, #AuditUser, #AuditValue1Before, #AuditValue2Before, #AuditValue1After, #AuditValue2After, #AuditMasterReason, #AuditMasterChange)"
SqlDataSource_LabInvest_Audit.InsertParameters.Add("ID_Table", obj)
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditTableName", "LaboratoryInvestigations_Add")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditAction", "Added New Record")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditUser", Usercheck)
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue1Before", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue2Before", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue1After", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditValue2After", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditMasterReason", "N/A")
SqlDataSource_LabInvest_Audit.InsertParameters.Add("AuditMasterChange", "N/A")
SqlDataSource_LabInvest_Audit.Insert()
Catch ex As Exception
Label1_AddData_LabInvest.Text = "Duplicate NumberID, Please Review Data"
End Try
Else
Label1_AddData_LabInvest.Text = "Please Fill All Options"
End If
The issue was found as the application was residing in a Web Servers Farm with NLB, therefore the blank post-back was due to the NBL redirecting the user to another server from the original connection. (different solutions may apply link NO Cache, Connection Affinity,etc) hope it helps someone in the future.
im looking for an example script. I saw one yesterday but for the life of me I can't find it again today.
The task I have is to allow the user to search 1 database table via input controls on an aspx page where they can select and , or , equals to combine fields, generating the sql on the fly with concat/stringbuilder or similar. (it runs behind the corp firewall)
Please can someone point me in the right direction of an example or tutorial
I've been working on the page, but have run into problems. Here is the Page_load;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = ("Select * From Table Where ")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty Then
sql += "Surname LIKE '%" & name & "%' "
End If
If EmailSearch.Text IsNot String.Empty Then
sql += andor1v & " Email LIKE '%" & email & "%' "
End If
If CitySearchBox.Text IsNot String.Empty Then
sql += andor2v & " City LIKE '%" & city & "%' "
End If
If QualificationsObtained.Text IsNot String.Empty Then
sql += andor3v & " (institutionquals1 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals2 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals3 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals4 LIKE '%" & qualifications & "%') "
End If
Dim selectedrow As String = CompetenciesDD.SelectedValue.ToString
Dim selectedquals As String = NQFlevel.SelectedValue.ToString
If CompetenciesDD.SelectedValue.ToString IsNot "0" And selectedquals = 0 Then
sql += (selectedrow & " = 1 ")
ElseIf selectedrow = "assessortrue" And selectedquals IsNot "0" Then
sql += andor4v & (" assessortrue=1 and assessorlvl=" & selectedquals)
ElseIf selectedrow = "coordinatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("coordinatortrue=1 and coordinatorlvl=" & selectedquals)
ElseIf selectedrow = "facilitatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("facilitatortrue=1 and facilitatorlvl=" & selectedquals)
ElseIf selectedrow = "moderatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("moderatortrue=1 and moderatorlvl=" & selectedquals)
ElseIf selectedrow = "productdevelopertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("productdevelopertrue=1 and productdeveloperlvl=" & selectedquals)
ElseIf selectedrow = "projectmanagertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("projectmanagertrue=1 and projectmanagerlvl=" & selectedquals)
End If
Response.Write(sql)
End Sub
After an hours tinkering the code is now looking as it does above ^
Now the problem im faced with is if a user does not enter a value for surname (the first field) but does enter a value for email (or any subsequent fields), the sql produced has an extra and like this;
Select * From Table Where And Email LIKE '%test%'
I'm also looking for a way to take the OR option into account. Do you think this should be done as Martin says where the whole query is either an and or an or and not a mix of the 2? Then I should be able to take out all the and/or drop downs?
Thanks.
NB: I'm not really looking for comments on how I should parameterise or about sql injection.
Regarding your issue with users not selecting an option you could just remove the "please select" and have it default to "and"
Also what is the desired behaviour if they select a mix of ANDs and ORs?
By default the ANDs will be evaluated first in the absence of any brackets
http://msdn.microsoft.com/en-us/library/ms186992.aspx
So if they enter
name="Fred" or email="blah" and
city="london" and province="xyz" or
qualifications="Degree"
I'm not really sure what the desired semantics would be?
Is it
(name="Fred" or email="blah") and
city="london" and (province="xyz" or
qualifications="Degree")
or
(name="Fred" or (email="blah" and
city="london") and province="xyz") or
qualifications="Degree"
Or something different? Maybe you should restrict them to AND or OR for the whole query or allow them to disambiguate either by typing in advanced search syntax with brackets or by providing a query builder UI.
To avoid sql injection and allow a dynamic search I would probably write a stored procedure something like this. If nothing is selected send DBNull.Value in the ado.net parameters collection as the parameter value. With this approach you can check any columns you want and if they are not selected by the user they will be ignored.
EDIT: I just saw that you are not allowed to use stored procedures. I changed my answer below to show a parameterized sql statement
SELECT * FROM TABLE
WHERE ([name] = #name OR #name IS NULL)
AND (email = #email OR #email IS NULL)
AND (city = #city OR #city IS NULL)
AND (province = #province OR #province IS NULL)
AND (qualifications = #qualifications OR #qualifications IS NULL)
AND (competencies = #competencies OR #competencies IS NULL)
AND (expertise = #expertise OR #expertise IS NULL)
Concat strings to build a query is never a good idea. You should use a stored procedure or parametrized queries
I have done this "dynamic" type query interface on classic asp.
The advice that I give to you is that you are trying to do the whole query in one page load so...
Look to "building" the query via a "wizard" type interface - either ajax for the newness or simple multiple pages for each part of the query building.
This is essence gives you "persitance" via what ever means you have (session, dbstore, cookie etc) for each part of the query and you have can sanity check each part of the query as you build.
Dim sql As String = ("Select * From Table Where **1=1**")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty And andor1v IsNot "0" Then
sql += "**and** Surname LIKE '%" & name & "%' "
ElseIf NameSearch.Text IsNot String.Empty And andor1v Is "0" Then
sql += "**or** Surname LIKE '%" & name & "%' "
End If
....additional logic here.....
Response.Write(sql)
End Sub
note the ** parts. 1=1 evaluates to true on most DBMS. This allows you to just start concatenating your or / ands on to it without worrying about ()'s