I currently have code that will generate a CSV from a database call, but I've been asked to create two separate CSV files with two different database calls from one click event. Here is an example of my current code:
'Global variable
Dim Include As List(Of String) = New List(Of String)
'Click event sub
Dim tempID As String = ""
'This gets the value of a checkbox (7th of 7 columns)
' and only adds checked rows to the query.
For Each row In GridView.Rows
If row.Cells(6).Controls(1).Checked Then
tempID = Regex.Replace(row.Cells(0).Controls(0).Text.Trim, "<(?:[^>=]|='[^']*'|=""[^""]*""|=[^'""][^\s>]*)*>", "", RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace Or RegexOptions.Multiline Or RegexOptions.Singleline)
Include.Add(tempID)
End If
Next
Dim Chosen As String = String.Join(",", Include)
SQLQuery = "SET ANSI_NULLS, ANSI_WARNINGS, ARITHABORT ON; "
SQLQuery += "SELECT * FROM ( " &
SQLQuery += "SELECT EXP.Account, " &
"EXP.Amount, " &
"EXP.DebitCredit, " &
"EXP.Description, " &
"EXP.BudgetCenter "
SQLQuery += "FROM [DB].[TBL] EXP " &
"INNER JOIN [DB2].[TBL2] REIM " &
"ON EXP.ID = REIM.ID " &
"WHERE EXP.ID IN ( " + Chosen + " ) " &
"AND REIM.StatusCode = 'APPROVED' "
SQLQuery += ") AS ResultTable "
ResultsDataSet = RunQuery(SQLQuery) 'THIS IS WHERE I CALL THE DATABASE
ResultsTable = ResultsDataSet.Tables(0)
For Each row As DataRow In ResultsTable.Rows
Dim item As String
For Each item In row.ItemArray
sb.Append(item.ToString + ","c)
Next
Next
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=JournalReport_" + Date.Today.Month.ToString + "_" + Date.Today.Day.ToString + "_" + Date.Today.Year.ToString + ".csv")
Response.Charset = ""
Response.ContentType = "application/text"
Response.Output.Write(sb.ToString())
Response.Flush()
I have another click event that does the same thing, but with a different query and a different file name in the Response.AddHeader() call.
What I'm trying to do is to, in a way, merge those two click events to create both files in one action. Is there a way I can do this with the code I have? Is there a different way I should be creating these files?
I've written this code with the help of research on GridViews and DataSets over the last few days. So, if it isn't pretty, it's only because it's been a bit rushed and has little knowledge behind it.
Related
I have a Search Form which have a sub form in it.
I keep getting Run-time error '3075': Syntax error(missing operator) in query expression '[MC_No] like '' [Customer] like '' [Date_Recorded] = #23/11/2016# AND [Product] like '*".
Can anybody identify my error? I have checked every single line. Maybe I missed out on something.
These are my codes
Private Sub Search_Click()
Dim strDatePicker As String
Dim cboMC As String
Dim strProduct As String
Dim cboCustomer As String
Dim sql As String
sql = "select * FROM 3_OEE WHERE "
If IsDate(Me.DatePicker) Then
strDatePicker = " [Date_Recorded] = #" & DateValue(Me.DatePicker) & "#"
Else
strDatePicker = " [Date_Recorded] like '*'"
End If
If IsNull(Me.MC_No) Then
cboMC = " [MC_No] like '*'"
Else
cboMC = " [MC_No] like '" & Me.MC_No & "'"
If IsNull(Me.Customer) Then
cboCustomer = " [Customer] like '*'"
Else
cboCustomer = " [Customer] = '" & Me.Customer & "'"
End If
Me.subfrmOEE.Form.RecordSource = sql (*Error highlights this code*)
Me.subfrmOEE.Form.Requery
On the line with the error, your variable sql is the same as it was when you first declared it, i.e.: "select * FROM 3_OEE WHERE ".
This is not a valid query. You need to either remove WHERE from the end of that query or append to the sql variable the rest of the query statement (in other words, add the WHERE conditions to the end of the query).
I'm programming an education website using asp.net vb.net and SQL Server. I have 4 stackholders, if any body log in in his profile he will see his information
If he wants to update them he just change the textboxes then click update
My problem is how to update.
I wrote a method to update but it always show me a syntax error in the query. I made sure there is no problem. I'm updating two tables and I made to sql statements!
My qustion is can I Insert instead of update?
If not: how to upade one record based on the session I have?
please help me
this my code
' Private Sub UpdateInfo(ByVal USER_ID As Integer)
'Dim User As Integer = USER_ID
'Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET MobileNumber =" + tbmobile.Text + ", HomeNumber=" + tbhome.Text + ", AltRelation = " + DDLRelationShip.SelectedValue + ", AlTitle = " + DDLTitle.SelectedValue + ", AltName = " + tbemname.Text + ", AltMobile = " + tbemmobile.Text + " WHERE USER_ID = User)"
'Dim sql2 As String = "UPDATE DIP_USERS SET USER_Email=" + tbEmail.Text.Trim + " WHERE USER_ID = User)"
' Try
' Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("mydbConnectionString").ConnectionString)
' Dim cmd1 As New SqlCommand(sql1, conn)
' Dim cmd2 As New SqlCommand(sql2, conn)
' cmd2.Parameters.AddWithValue("#FirstName", tbname.Text)
' cmd2.Parameters.AddWithValue("#USER_PASSWORD", tbnewpassword.Text)
' cmd2.Parameters.AddWithValue("#USER_Email", tbEmail.Text)
' cmd1.Parameters.AddWithValue("#MobileNumber", tbmobile.Text)
' cmd1.Parameters.AddWithValue("#HomeNumber", tbhome.Text)
' cmd1.Parameters.AddWithValue("#AltRelation", DDLRelationShip.SelectedValue)
' cmd1.Parameters.AddWithValue("#AlTitle", DDLTitle.SelectedValue)
' cmd1.Parameters.AddWithValue("#AltName", tbemname.Text)
' cmd1.Parameters.AddWithValue("#AltMobile", tbemmobile.Text)
' conn.Open()
'Dim ra As Integer = cmd1.ExecuteNonQuery()
'Dim ra1 As Integer = cmd2.ExecuteNonQuery()
'cmd1.Dispose()
'cmd2.Dispose()
' conn.Close()
' Catch ex As Exception
' MsgBox(ex.Message)
' End Try
'End Sub
you have not specified your parameters in your query, you're directly concatenating the values of controls inside your query. And still you have added parameters.
Firstly, do not concatenate your sql query like that, its prone to SQL Injection.
construct your query like this:
Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET
MobileNumber =#MobileNumber,
HomeNumber=#HomeNumber,
AltRelation = #AltRelation,
AlTitle = #AlTitle,
AltName =#AltName,
AltMobile = #AltMobile
WHERE USER_ID = #User"
Dim sql2 As String = "UPDATE DIP_USERS SET
USER_Email=#USER_Email
WHERE USER_ID = #User"
and also, add this parameter too
cmd1.Parameters.AddWithValue("#User", USER_ID)
cmd2.Parameters.AddWithValue("#User", USER_ID)
And one very important thing. you need to assign proper datatype to your columns in the query i.e.
remember these things.
txtBox.Text returns String value, you might need to convert it to Int32 using Convert.Int32 or you need to wrap it in single quote, based totally upon datatype of your column
Put parameters which you declare in your SQL Command query:
"UPDATE AdminCoordinatorInformation SET MobileNumber=#MobileNumber,HomeNumber=#homeNumber...
You get syntax error because your string data in sql query must be wrapped with "'".
"UPDATE AdminCoordinatorInformation SET MobileNumber='0987654321',....
Note: creating sql queries by concating query with user inputs ("...SET MobileNumber='" + txtbox.Text + "',...") is not good/dangerous practice because of SQL Injection
I'm trying to store a list of table items in a Session variable to keep track of the last state (CHECKED or UNCHECKED) of the item's checkbox.
I start out by setting all values to UNCHECKED the first time the users loads the page. This part of the code seems to work:
model = Request.querystring("model")
If IsEmpty(Session(model)) Then
Set dicX = CreateObject("Scripting.Dictionary")
sqlStr = "SELECT DISTINCT level FROM IFPDB WHERE IFPDB.model='"
sqlStr = sqlStr & model
sqlStr = sqlStr & "'"
Set objRS = objConn.Execute(sqlStr)
' For each unique level get all of that levels menu names
Do While (Not objRS.EOF)
level = objRS("level")
dicX.Add level, CreateObject("Scripting.Dictionary")
' for each menu name set the initial state to OFF
sqlStr2 = "SELECT * FROM IFPDB WHERE IFPDB.model='"
sqlStr2 = sqlStr2 & model
sqlStr2 = sqlStr2 & "' AND IFPDB.level='"
sqlStr2 = sqlStr2 & level_name
sqlStr2 = sqlStr2 & "'"
Set objRS2 = objConn.Execute(sqlStr2)
Do While (Not objRS2.EOF)
menu_item = objRS2("menu_names")
dicX(level).Add menu_item, CreateObject("Scripting.Dictionary")
' add a dictionary item
dicX(level)(menu_item).Add "menu_state", "UNCHECKED"
objRS2.MoveNext
Loop
objRS.MoveNext
Loop
Set Session(model) = dicX
End If
The problem now comes when I try to read any of these values. No matter how I've tried to access them I get "Object_required:_'[undefined]'"
I've tried
' Check the last state of this option
menu_name = objResult("menu_names")
response.write(menu_name & "<br>") ' writes correctly
If Not IsEmpty(Session(model))
my_state = Session(model)(current_level)(menu_name).Item("menu_state") ' dies here
response.write(my_state & "<br>")
End If
' tried these as well
my_state = Session(model)(current_level)(menu_name)("menu_state")
'and
my_state = Session(model)(current_level).Item(menu_name).Item("menu_state")
'and others
I guess I just don't know how to read that Session variable that I made. Any ideas?
See:
Can I store a Scripting Dictionary in a session variable?
You have to extract the dictionary from the session and put in into a fresh variable.
dim state
set state = Session(model)
You are also missing the 'item' part:
my_state = state.item(current_level).item(menu_name).item("menu_state")
Use Session("model") instead of Session(model).
I am interfacing with Quality Centre via Open Test Architecture API.
I would like to determined the allowed values of bug Fields that are linked to a lookup table.
These are available via drop downs in the standard frontend.
Thanks
Edit: A more Detailed explanation
We have some fields which will only allow specific values to placed in them.
For example:
NextAction can be one of the following { "1. Specify", "2. Analysis", "3. Design" }
But I have been unable to find a way to determine these allowed values programmatically.
Using the BugFactory object you can access the fields and their attributes. This is a direct copy / paste of Visual Basic from the OTA API Reference help file. If you want more help, try providing a more focused question, such as what you're trying to accomplish, which fields, and which language you're trying to access with.
Public Sub CheckValidValue(Optional TableName As String = "BUG")
Dim BugFact As BugFactory
Dim BugList As list
Dim aField As TDField
Dim fieldList As list
Dim rc, ErrCode As Long
Dim aBug As Bug
Dim msg$
Dim okCnt%, noNodeCnt%, errorCnt%, unknownCnt%
Dim dataType As Long
'------------------------------------------------
' User BugFactory.Fields to get a list of TDField
' objects in the bug table.
' This example uses the BugFactory, but this can
' be done with any class that implements IBaseFactory
'tdc is the global TDConnection object.
Set BugFact = tdc.BugFactory
Set fieldList = BugFact.Fields
'------------------------------------------
' Use List.Count to check how many items.
Debug.Print: Debug.Print
Debug.Print "There are " & fieldList.Count & _
" fields in this table."
Debug.Print "----------------------------------"
'Get any bug. To look at field attributes we
' need a valid object and since this example is
' not interested in the particular values of the object,
' it doesn't matter which bug.
Set BugList = BugFact.NewList("")
Set aBug = BugList(0)
'Walk through the list
For Each aField In fieldList
With aField
'Quit when we have enough for this example
If InStr(aField.Name, "BG_USER_10") > 0 Then Exit For
' For the DataTypeString() code,
' see example "Convert data types to string"
Debug.Print .Name & ", " & .Property & ", Data type is " _
& DataTypeString(.Type)
On Error Resume Next
'----------------------------------------------------
'Use TDField.IsValidValue to confirm that a value can
'be used for a field.
' Get the correct data type and check validity of an
' arbitrary value.
' Save the error code immediately after IsValidValue call
' before another call can change the err object.
dataType = aField.Type
Select Case dataType
Case TDOLE_LONG, TDOLE_ULONG
aField.IsValidValue 5, aBug
ErrCode = err.Number
Case TDOLE_FLOAT
aField.IsValidValue 5.5, aBug
ErrCode = err.Number
Case TDOLE_STRING
aField.IsValidValue "Joe", aBug
ErrCode = err.Number
Case Else
'These will be errors:
aField.IsValidValue _
"String to non-string value", aBug
ErrCode = err.Number
End Select
'Output an error code message
If ErrCode = 0 Then 'S_OK
msg = "Valid Value"
okCnt = okCnt + 1
Else
rc = ErrCode - vbObjectError
Select Case rc
Case FIELD_E_VERIFIED
msg = "Error: Invalid value for field"
errorCnt = errorCnt + 1
Case TDOLE_NONODE
msg = "Error: Field can not be set to this value"
noNodeCnt = noNodeCnt + 1
Case Else
msg = "Unrecognized error: " & rc _
& " , HRESULT = " & ErrCode
unknownCnt = unknownCnt + 1
End Select
End If
Debug.Print vbTab & msg
'
End With 'aField
Next aField
Debug.Print "----------------------------------"
Debug.Print "Number of fields with valid value = " & okCnt
Debug.Print "Number of fields with invalid type = " & errorCnt
Debug.Print "Number of fields with invalid value= " & noNodeCnt
Debug.Print "Number of fields with unknown error = " & unknownCnt
Debug.Print "----------------------------------"
End Sub
You can do this by looking up the list from the 'Customization' object. Here's how I'd do it using ruby:
qc = WIN32OLE.new('TDApiOle80.TDConnection')
qcserver = 'http://testdirector/qcbin/'
qc.InitConnectionEx(qcserver)
qc.Login($username, $password)
qc.Connect("$domain", "$project")
customization = #qc.Customization
list = custom.Lists.List("NextAction")
node = list.RootNode
children = node.Children
children.each do |child|
puts "#{child.Name} \n"
end
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