I want to include multiple messages in one MsgBox using \n. I need to remove this string when the MsgBox is shown.
This is my code.
Dim Msg As String = ""
Dim EmployeeFirstName As String
Dim EmployeeLastName As String
EmployeeFirstName = txtFirstName.Text.Trim
EmployeeLastName = txtLastName.Text.Trim
If EmployeeFirstName = "" Then
Msg = "Please enter First Name!"
Msg += "/n"
End If
If EmployeeLastName = "" Then
Msg += "Please enter Last Name!"
Msg += "/n"
End If
If ddlGender.SelectedItem.Value = -1 Then
Msg += "Plrase Select department"
Msg += "/n"
End If
MsgBox(Msg)
StringBuilder is usually a good choice when you need to build a string dynamically. It often performs better, and generally makes for cleaner, more maintainable code than doing a bunch of string concatenation.
Dim msgBuilder As New StringBuilder()
'...
If EmployeeFirstName = "" Then
msgBuilder.AppendLine("Please enter First Name!")
End If
'And so forth
MsgBox(msgBuilder.ToString())
But, as Matt Wilko points out, if this is ASP.NET, you don't want to use MsgBox at all.
Like this ...
Msg = "Please enter First Name!" & vbCrlf
Msg &= "Please enter Last Name!" & vbCrlf
Msg &= "Please Select department"
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
I am using the code below to generate a popup box. Where is says "The information is ready to be submitted" I would like to add "Your reference number is 12345" I am getting that reference number using a session i.e. Session("ID"). Is there a way I can add this to the string?
Try
Dim msg As String = "Hello!"
Dim script As String = "if(confirm('The information is ready to be submitted')) {window.location.href ='frmMain.aspx'; }"
ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "Test", script, True)
Catch ex As Exception
End Try
Yep. Just add the information to your script string (I switched the string to stringbuilder for slight efficiency gain):
Dim sbScript As New System.Text.StringBuilder(200)
sbScript.Append("if(confirm('The information is ready to be submitted. Your reference number is ").Append(Session("ID"))
sbScript.Append("')) {window.location.href ='frmMain.aspx'; }")
ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "Test", sbScript.ToString(), True)
Try this:
Try
Dim msg As String = "Hello!"
Dim idValue As String = CType(Session("ID"), String)
Dim script As String = "if(confirm('The information is ready to be submitted. Your reference number is " & idValue & "')) {window.location.href ='frmMain.aspx'; }"
ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "Test", script, True)
Catch ex As Exception
End Try
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
How do I make my own word wrap function for strings? I want each line to be no longer than 50 characters and respect existing CRLFs.
Something like this, it will get you started (just a quick samle i mashed together):
Private Sub Doit()
Dim Source As String = ""
Source &= "How to make my own word wrap function for string, I want each line to be no longer than 50chars and take respect existing CRLFs" & vbCrLf & vbCrLf
Source &= "So this will be a new row."
Dim wrappedtext As String = wrap(Source, 20, vbNewLine)
MsgBox(wrappedtext)
End Sub
Function wrap(ByVal text As String, ByVal maxlength As Integer, ByVal newline As String) As String
Dim tmp() As String = Split(text.Replace(vbCrLf, " | "), " ")
Dim ret As String = ""
Dim wrk As String = ""
For Each word As String In tmp
If word = "|" Then
ret &= newline
wrk = ""
ElseIf word = "" Then
Else
If Len(wrk & word) <= maxlength Then
wrk &= " " & word
Else
ret &= wrk & newline
wrk = word & " "
End If
End If
Next
If wrk <> "" Then ret &= wrk
Return ret
End Function
From which point of view? SW architecture?
Take a look at the decorator pattern. If you like to work with streams, in the book "Heads First: Design Patterns" a string modifier is proposed. It's in Java, but the general programming concept is described in a good way. Some pages are missing but you can find many infos here.
The algorithm itself is trivial, isn't it?