Function checkIsAuthorized(ByVal users As String) As Boolean
Dim UserJobCode As String = dcChris.getJobCode(users)
Dim values As String = My.Settings.canResendJobcode
Dim usersCode As String() = values.Split(",")
Return usersCode.Contains(UserJobCode)
'If usersCode.Contains(UserJobCode) Then
' canResend = True
' Return True
'End If
'canResend = False
'Return False
End Function
The commented portion of the function works, I was just trying to make the code more efficient with the return statement. But it does not return a bool because the global is still reading false. Doing it the old way worked.
Any ideas?
Dim canResend As Boolean
Function checkIsAuthorized(ByVal users As String) As Boolean
Dim UserJobCode As String = dcChris.getJobCode(users)
Dim values As String = My.Settings.canResendJobcode
Dim usersCode As String() = values.Split(",")
Return usersCode.Contains(UserJobCode)
End Function
This is what I settled on. It works great for my needs. Thanks everyone.
Related
How to know if a dictionary with multiple values contains specific value?
'Create dictionary
Dim testDictionary As New Dictionary(Of String, Items)
'Code to fill dictionary
'.......................
'.......................
'.......................
'Test if a specific value is contained in dictionary
Dim testValue as String = "TEST"
testDictionary.ContainsValue(testValue) 'This doesn't work
Public Class Items
Public Property Property1 As String
Public Property Property2 As String
Public Sub New()
End Sub
End Class
If you can define how to determine whether the dictionary contains that string, pass that logic into Enumerable.Any
Dim testValue As String = "TEST"
Dim contains = testDictionary.Any(Function(kvp) kvp.Value.Property1 = testValue OrElse kvp.Value.Property2 = testValue)
If contains Then
Dim containsEntries = testDictionary.Where(Function(kvp) kvp.Value.Property1 = testValue OrElse kvp.Value.Property2 = testValue)
End If
Since you reuse it for Any and Where, you can declare the predicate once
Dim predicate =
Function(kvp As KeyValuePair(Of String, Items))
Return kvp.Value.Property1 = testValue OrElse kvp.Value.Property2 = testValue
End Function
Dim contains = testDictionary.Any(predicate)
If contains Then
Dim containsEntries = testDictionary.Where(predicate)
End If
This is hard-coded to just these properties Property1 and Property2.
(you really don't need the Any if you want the entities; I just figured the Any answered your question "How to know if..." with a boolean)
If you want to check all public instance string properties, you can use reflection
Dim predicate =
Function(kvp As KeyValuePair(Of String, Items))
Return GetType(Items).
GetProperties(Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance).
Where(Function(pi) pi.PropertyType Is GetType(String)).
Aggregate(False, Function(pi1, pi2) pi1 Or (pi2.GetValue(kvp.Value) = testValue))
End Function
Dim containsWith = testDictionary.Any(predicate)
If containsWith Then
Dim containsEntries = testDictionary.Where(predicate)
End If
so..
I have a txt file with hundreds of sentences or strings.
I also have 4 comboboxes with options that a user can select from and
each combobox is part of a different selection criteria. They may or may not use all the comboboxes.
When a user selects an option from any combobox I use a For..Next statement to run through the txt file and pick out all the strings that contain or match whatever the user selected. It then displays those strings for the user to see, so that if they wanted to they could further narrow down the search from that point by using the 3 remaining comboboxes making it easier to find what they want.
I can achieve this by using lots of IF statements within the for loop but is that the only way?
No, there are other ways. You can leverage LINQ to get rid of some of those if statements:
Private _lstLinesInFile As List(Of String) = New List(Of String)
Private Function AddClause(ByVal qryTarget As IEnumerable(Of String), ByVal strToken As String) As IEnumerable(Of String)
If Not String.IsNullOrWhiteSpace(strToken) Then
qryTarget = qryTarget.Where(Function(ByVal strLine As String) strLine.Contains(strToken))
End If
Return qryTarget
End Function
Public Sub YourEventHandler()
'Start Mock
Dim strComboBox1Value As String = "Test"
Dim strComboBox2Value As String = "Stack"
Dim strComboBox3Value As String = String.Empty
Dim strComboBox4Value As String = Nothing
'End Mock
If _lstLinesInFile.Count = 0 Then
'Only load from the file once.
_lstLinesInFile = IO.File.ReadAllLines("C:\Temp\Test.txt").ToList()
End If
Dim qryTarget As IEnumerable(Of String) = (From strTarget In _lstLinesInFile)
'Assumes you don't have to match tokens that are split by line breaks.
qryTarget = AddClause(qryTarget, strComboBox1Value)
qryTarget = AddClause(qryTarget, strComboBox2Value)
qryTarget = AddClause(qryTarget, strComboBox3Value)
qryTarget = AddClause(qryTarget, strComboBox4Value)
Dim lstResults As List(Of String) = qryTarget.ToList()
End Sub
Keep in mind this is case sensitive so you may want to throw in some .ToLower() calls in there:
qryTarget = qryTarget.Where(Function(ByVal strLine As String) strLine.ToLower().Contains(strToken.ToLower()))
I think a compound If statement is the simplest:
Dim strLines() As String = IO.File.ReadAllText(strFilename).Split(vbCrLf)
Dim strSearchTerm1 As String = "Foo"
Dim strSearchTerm2 As String = "Bar"
Dim strSearchTerm3 As String = "Two"
Dim strSearchTerm4 As String = ""
Dim lstOutput As New List(Of String)
For Each s As String In strLines
If s.Contains(strSearchTerm1) AndAlso
s.Contains(strSearchTerm2) AndAlso
s.Contains(strSearchTerm3) AndAlso
s.Contains(strSearchTerm4) Then
lstOutput.Add(s)
End If
Next
What I want is to return 2 values from the database with a function and then store the values in variables so I can work with them. This is my code.
Function Buscar_Registro(ByVal xId As Integer) As String
Dim a, b As String
'convertir cadena
Dim Id As Integer
Id = xId
'conexión
Dim Conexion As OleDbConnection = New OleDbConnection
Conexion.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Visual\2000Phrases\2000 Phrases.accdb"
'cadena SQL
Dim CadenaSQL As String = "SELECT * FROM Data WHERE Id = " & Id
'Adaptador
Dim Adaptador As New OleDbDataAdapter(CadenaSQL, Conexion)
'Data set
Dim Ds As New DataSet
'Llenar el Data set
Conexion.Open()
Adaptador.Fill(Ds)
Conexion.Close()
'Contar registro
If (Ds.Tables(0).Rows.Count = 0) Then
Return False
Else
a = Ds.Tables(0).Rows(0)("Nombre").ToString()
b = Ds.Tables(0).Rows(0)("Apellido").ToString()
Ds.Dispose()
Return a
Return b
Return True
End If
End Function
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Randomize()
Dim value As Integer = CInt(Int((20 * Rnd()) + 1))
TextBox3.Text = Buscar_Registro(value)
TextBox4.Text =
End Sub
I dont' know how to do it. The function returns only the value of "a"
Thanks
To return more values you need to change your function "as object"
Function Buscar_Registro(ByVal xId As Integer) As Object
and then you can put your return values into an object this way:
Return{a, b, true}
You'll get your values this way:
Dim mObj as object = Buscar_Registro(yourInteger)
you'll have:
a in mObj(0)
b in mObj(1)
True in mObj(2)
adapt it to your needs
EDIT (message to those that downvoted):
Creating a class an using a specific Object (the one created) to make a Function able to return multiple elements is surely the best choice.
Anyway, if someone doesn't know that it's possible to use the method that I showed in my answer, he is probably not (yet) able to create a class. So I think it's better give an usable (but not perfect) answer instead of a perfect (but unusable for the one who asked) answer.
This is what I think. Anyone can think differently.
Your best option here is to create your own class with the data you need and return that.
Public Class Data
Public Property Nombre As String
Public Property Apellido As String
End Class
And then do:
Function Buscar_Registro(ByVal xId As Integer) As Data
....
If (Ds.Tables(0).Rows.Count = 0) Then
Return Nothing
Else
a = Ds.Tables(0).Rows(0)("Nombre").ToString()
b = Ds.Tables(0).Rows(0)("Apellido").ToString()
Ds.Dispose()
return new Data() With {.Nombre = a, .Apellido = b}
End If
End Function
As of VB 15 you can use ValueTuple
Function Buscar_Registro(ByVal xId As Integer) As (Nombre As String, Apellido As String)
....
If (Ds.Tables(0).Rows.Count = 0) Then
Return (Nothing, Nothing)
Else
a = Ds.Tables(0).Rows(0)("Nombre").ToString()
b = Ds.Tables(0).Rows(0)("Apellido").ToString()
Ds.Dispose()
Return (a, b)
End If
End Function
I'm new to .net but wouldn't "ByRef" be the easiest way?
Function Buscar_Registro(ByVal xId As Integer, ByRef a As String, ByRef b As String)
I've seen some questions similar to this on here, but none of them seem to help me. I don't really care what API is used, be it Google, Yahoo!, The Weather Channel, or any other. I've got code that will get the high and low of the current day, based on the location given by the user, but I can't seem to get the hourly predictions for temperature or weather condition, which is what I'm really looking for. I don't really care for wind speeds, humidity, or the "feels like" temperature, though I'll add them if I can figure out how to. I'm trying to get data that will look something like what is here. (www.weather.com/...)
I'm pretty new to parsing XML so that may be part of my problem, too. Thanks in advance for any help. I greatly appreciate it.
I have something you might enjoy:
<Runtime.CompilerServices.Extension()>
Module Weather
Public Structure WeatherInfo_Forecast
Dim DayOfWeek As String
Dim low As Double
Dim high As Double
Dim icon As String
End Structure
Public Structure WeatherInfo_Wind
Dim direction As String
Dim speed As Double
Dim unit As String
End Structure
Public Structure WeatherInfo_Typed
Dim Failed As Boolean
Dim errormessage As Exception
Dim location As String
Dim forcast_date As DateTime
Dim checked_time_date As DateTime
Dim humidity As Double
Dim highf As Double
Dim lowf As Double
Dim highc As Double
Dim lowc As Double
Dim currenttempC As Double
Dim currenttempF As Double
Dim predicted_icon As String
Dim current_icon As String
Dim current_condition As String
Dim predicted_condition As IEnumerable(Of WeatherInfo_Forecast)
Dim wind_condition As WeatherInfo_Wind
Dim day As String
End Structure
<Runtime.CompilerServices.Extension()> _
Public Function ToC(ByVal F As Double) As Double
Return ((F - 32) / 9) * 5
End Function
<Runtime.CompilerServices.Extension()> _
Public Function TryParseAsDouble(ByVal s As String) As Double
Dim rv As Double
If Double.TryParse(s, rv) = False Then rv = Double.NaN
Return rv
End Function
<Runtime.CompilerServices.Extension()> _
Public Function TryParseAsDate(ByVal s As String) As DateTime
Dim rv As DateTime
If DateTime.TryParse(s, rv) = False Then rv = Nothing
Return rv
End Function
Private Function ParseHumidity(ByVal s As String) As Double
If Not s Is Nothing Then
Dim humRegEx As New System.Text.RegularExpressions.Regex("Humidity: (?<Value>\d+)\w*\%")
Dim m = humRegEx.Match(s)
If m.Length = 0 Then Return Double.NaN
Return Double.Parse(m.Groups("Value").Value)
End If
End Function
Private Function ParseWind(ByVal s As String) As WeatherInfo_Wind
Dim rv As New WeatherInfo_Wind
If Not s Is Nothing Then
Dim humRegEx As New System.Text.RegularExpressions.Regex("Wind\:\s+(?<Direction>[NEWSnews]{1,2})\s+at\s+(?<speed>(?<value>\d+)\s(?<units>\w+)){1}")
Dim m = humRegEx.Match(s)
rv.speed = Double.NaN
If m.Length = 0 Then Return rv
With rv
.direction = m.Groups("Direction").Value
If Double.TryParse(m.Groups("value").Value, .speed) = False Then .speed = Double.NaN
.unit = m.Groups("units").Value
End With
End If
Return rv
End Function
<DebuggerHidden()>
Public Function Grab_Weather(ByVal Location As String) As WeatherInfo_Typed
Dim GrabWeather As New WeatherInfo_Typed
With GrabWeather
.Failed = True
Try
Dim xml As XDocument = XDocument.Load("http://www.google.com/ig/api?weather=" & Location)
Dim xp = xml.<problem_cause>
If xp.Any Then Return GrabWeather
.location = xml...<city>.#data
.forcast_date = xml...<forecast_date>.#data.TryParseAsDate
.checked_time_date = xml...<current_date_time>.#data.TryParseAsDate
.humidity = ParseHumidity(xml...<humidity>.#data)
.highf = xml...<high>.#data.TryParseAsDouble
.lowf = xml...<low>.#data.TryParseAsDouble
.highc = GrabWeather.highf.ToC
.lowc = GrabWeather.highc.ToC
.currenttempC = xml...<temp_c>.#data.TryParseAsDouble
.currenttempF = xml...<temp_f>.#data.TryParseAsDouble
'.current_icon = "http://www.google.com" & xml...<icon>.#data
'.predicted_icon = "http://www.google.com" & xml...<high>.#data
.current_condition = xml...<condition>.#data
.predicted_condition = From f In xml...<forecast_conditions> _
Select New WeatherInfo_Forecast With { _
.DayOfWeek = f.<day_of_week>.Value, _
.high = f.<high>.#data.TryParseAsDouble, _
.low = f.<low>.#data.TryParseAsDouble}
'.icon = "http://www.google.com" & f.<icon>.#data}
.wind_condition = ParseWind(xml...<wind_condition>.#data)
.day = xml...<day_of_week>.#data
.Failed = False
Return GrabWeather
Catch ex As Exception
.errormessage = ex
Return GrabWeather
End Try
End With
End Function
End Module
I finally found what I was looking for from Weather Underground. They have three APIs, and, starting with the middle one, gives hourly forecasts for 36 hours. You get English and Metric predicted statistics for temperature, "feels like" temperature, dew point, wind speed, and wind direction. There's also wind chill and heat index, but every result for both in English and Metric was -9998, so I'm pretty sure those results are a bit off! Also there are qpf, snow, pop, and mslp. Unfortunately qpf and snow have not results and I'm not sure what pop and mslp are. All results are available in JSON and XML. They have some image requests, too, but I haven't looked into them yet.
Update:
Link Updated
I need to find obsolute occurrence of a string in a file.
If a string "I_LOVE_INDIA" in a file.
If the input string is "I_LOVE" then search status should be false.
If the input string is "I_LOVE_INDIA" then search status should be true.
I am not able to get using below one:
System.IO.File.ReadAllText("D:\asdf\def.txt").IndexOf("string_to_search")
This will work:
System.IO.File.ReadAllText("D:\asdf\def.txt").IndexOf("I_LOVE_INDIA")
If you want it to fail when you look for "I_LOVE_INDIA_TOO" then you'll need to check for that, eg:
Dim s as String = System.IO.File.ReadAllText("D:\asdf\def.txt")
Dim success as Boolean = CheckStringContainsILoveIndia(s)
Public Function CheckStringContainsILoveIndia(Byval s as String) as Boolean
Dim success as Boolean = False
If s.IndexOf("I_LOVE_INDIA_TOO") == -1 AND s.IndexOf("I_LOVE_INDIA") > -1 Then
success = True
End If
return success
End Sub