I would like to be able to take a string such as the following and put in in MySettings and have the application dynamically parse the expression. Is that possible?
Name: ClientName
Type: String
Scope: Application
Value: MyData(i).FirstName & " " & MyData(i).LastName
Dim name As String = My.Settings.ClientName
It's not really possible to do if using just the simple String class. You'll either have to create a method to parse it out or create your own object type that will do the parsing. Either way, it requires that you write code to parse out that data.
If you need some help with parsing of the data, using your above example, it's simple enough to parse.
Dim s As String = "First Last"
Dim names() As String = s.Split(" "c)
Dim firstName As String = names(0)
Dim lastName As String = names(1)
I'm also not sure what your MyData object is. You could put a parsing routine in that object to automatically parse the name and set the properties as needed. It could even be part of the constructor.
Public Sub DoWhateverINeedToDo()
Dim md As New MyData(My.Settings.ClientName)
Console.WriteLine("First Name: " & md.FirstName)
Console.WriteLine("Last Name: " & md.LastName)
End Sub
Public Class MyData
Public Property FirstName As String
Public Property LastName As String
Public Sub New(ByVal fullName As String)
Dim names() As String = fullName.Split(" "c)
Me.FirstName = names(0)
Me.LastName = names(1)
End Sub
End Class
Related
I want to make a Message, using formatting, multiple lines and adding 3 arguments. But I'm having some trouble
Public Class vbList
'Declare
Dim users As IList(Of User) = New List(Of User)()
Public Sub New()
InitializeComponent()
users.Add(New User With {
.Id = 1,
.Name = "Suresh Dasari",
.Location = "Hyderabad"
})
MsgBox("Id: {0}", users.Item(0).Id.ToString() & vbCrLf & "Name: {0}", users.Item(0).Name) & vbCrLf & "Location: {0}", users.Item(0).Location)
End Sub
I don't get this message below. Don't I need to convert the Id to a string to put it in a message?
System.InvalidCastException: 'Conversion from string "1
Name: {0}" to type 'Integer' is not valid.'
And whats up with this one, I can't have more than 2 arguments?
Too many arguments to 'Public Function MsgBox(Prompt As Object, [Buttons As MsgBoxStyle = ApplicationModal], [Title As Object = Nothing]) As MsgBoxResult'. VSBasics C:\Users\ljhha\Documents\it\vb\VSBasics\VSBasics\vbList.vb 33 Active
Use String.Format or string interpolation to insert the variables. You can insert line breaks that way too or use a multiline literal in the first place.
Dim str1 = String.Format("Date: {0}{1}Time: {2}", Date.Now.ToShortDateString(), Environment.NewLine, Date.Now.ToShortTimeString())
Dim str2 = $"Date: {Date.Now.ToShortDateString()}{Environment.NewLine}Time: {Date.Now.ToShortTimeString()}"
Dim str3 = $"Date: {Date.Now.ToShortDateString()}
Time: {Date.Now.ToShortTimeString()}"
MessageBox.Show(str1)
MessageBox.Show(str2)
MessageBox.Show(str3)
I have this structure:
Module Global_Variables
Public myrecords(10) As myDatabase
Public counter As Integer = 0
Public Structure myDatabase
'creates database Structure For input data
<VBFixedString(30)> _
Dim Driver As String '30 bytes
Dim Car As Integer '4 bytes
<VBFixedString(15)> _
Dim Team As String '15 bytes
Dim Grid As Integer '4 bytes
Dim FastestLap As Double '8 bytes
Dim RaceTime As Double '4 bytes
Dim Points As Double '4 bytes
End Structure
End Module
The program receives data from the user and then displays the data in a text box called txtOutput in another form:
myrecords(counter).Driver = driver_box.Text
myrecords(counter).Car = car_box.Text
myrecords(counter).Team = team_box.Text
myrecords(counter).Grid = grid_box.Text
myrecords(counter).FastestLap = fl_box.Text
myrecords(counter).RaceTime = rt_box.Text
myrecords(counter).Points = points_box.Text
Form_Display.txtDisplay.AppendText(myrecords(counter).Driver & " " &
myrecords(counter).Car & " " & myrecords(counter).Team & " " &
myrecords(counter).Grid & " " & myrecords(counter).FastestLap & " " &
myrecords(counter).RaceTime & " " & myrecords(counter).Points & vbCrLf)
counter = counter + 1
MsgBox("Submit success!")
Call input_box_clear()
The user can then click a button to sort the records in ascending order by fastest lap. How do I do this?
I have tried algorithms such as bubble sort and selection sort but neither worked.
Thank you
Declaring type (class, not structure)
Public class RaceData
Public Property Driver As String
Public Property Car As Integer
Public Property Team As String
Public Property Grid As Integer
Public Property FastestLap As Double
Public Property RaceTime As Double
Public Property Points As Double
End Class
In-memory database (look what is in System.Collections)
Private _raceDb As New List(Of RaceData)()
Add user input
Dim newItem As New RaceData()
newItem.Driver = driver_box.Text
newItem.Car = Integer.Parse(car_box.Text)
newItem.Team = team_box.Text
newItem.Grid = Integer.Parse(grid_box.Text)
newItem.FastestLap = Double.Parse(fl_box.Text)
newItem.RaceTime = Double.Parse(rt_box.Text)
newItem.Points = Double.Parse(points_box.Text)
_raceDb.Add(newItem)
Sorting for the grid (Read about LINQ)
// sort by fastest race time
Dim sortedDb As List(Of RaceData) = _raceDb.OrderBy(Function(x) x.RaceTime).ToList()
Pick one fastest race
Dim fastest As RaceData = _raceDb.OrderBy(Function(x) x.RaceTime).FirstOrDefault()
If fastest IsNot Nothing Then ...
Build a string for each item to add to multi-line textbox
Dim lines() As String = _raceDb.Select(Function(x) x.Driver & " --- " & x.Team).ToArray()
' Using some tips from the comments
Dim lines() As String = _raceDb.
Select(Function(x) string.Format("{0,-30} --- {1,15}", x.Driver, x.Team)).ToArray()
Domain\X_User|X_User,Domain\Y_User|Y_User,
I'm using a SSRS report and I'm receiving the above value, I want to write visual basic function in the report ( Custom code) to split the above string and return the following value:
X_User,Y_User
I tried to write this code inside a custom code of the report body:
Public Function SubString_Owner(X As String) As String
Dim OwnerArray() As String = Split(X, ",")
Dim Names As String
Dim i As Integer = 0
While i <= OwnerArray.Length - 1
Dim NamesArr As String() = Split(OwnerArray(0), "|")
Names = NamesArr(1) + ","
i += 1
End While
Return Names
End Function
The problem is when trying to split OwnerArray(i), it gives an error but when using a fixed value, like zero, it builds fine. Can anyone figure out why this is?
Here is a more generic solution that will work with any number of items:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s))
Dim usersWithoutDomains As IEnumerable(Of String) = domainsAndUsers.Select(Function(s) s.Remove(0, s.IndexOf("\") + 1))
Dim users As IEnumerable(Of String) = usersWithoutDomains.Select(Function(s) s.Remove(s.IndexOf("|")))
Dim result As String = users.Aggregate(Function(s, d) s & "," & d)
Or if you want it as a single-line function, here:
Function Foo(sourceString As String) As String
Return sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s)).Select(Function(s) s.Remove(0, s.IndexOf("\") + 1)).Select(Function(s) s.Remove(s.IndexOf("|"))).Aggregate(Function(s, d) s & "," & d)
End Function
EDIT:
You may have to add Imports System.Linq to the top. Not sure if SSRS can use LINQ or not. If not, then here is a similar solution without LINQ:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c)
Dim usersWithoutDomains As String = String.Empty
For Each domainUser As String In domainsAndUsers
usersWithoutDomains &= domainUser.Remove(0, domainUser.IndexOf("\") + 1) & ","
Next
Dim strTest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User"
MsgBox(strTest.Split("|")(0).Split("\")(1) & " " & strTest.Split("|")(1).Split("\")(1))
Here's a simple way that will work with variable data as long as the pattern you've shown is strongly followed:
Imports System.Linq
Dim strtest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
'This splits the string according to "|" and ",". Now any string without _
a "\" is the user and Join adds them together with `,` as a delimiter
Dim result As String = Join((From s In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Where Not s.Contains("\")
Select s).ToArray, ",")
Just in case LINQ is unavailable to you here's a different way to the same results without LINQ:
Dim result As String = ""
For Each s As String In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
If Not s.Contains("\") Then
result += s & ","
End If
Next
result = result.TrimEnd(",".ToCharArray)
I am working on my first website and need help with a loop. I have a database table containing food items named Menu with 8 categories (such as Burgers, Appetizers). I also have a menu page on website with 8 different pics to display items from each category. I need to loop through rows of database. What is happening is it's only looping through columns and repeating first line over and over. I'm aware I need a loop but for some reason cannot get that right.
This is code behind:
Partial Class Burger
Inherits System.Web.UI.Page
'String Used to build the necessary markup and product information
Dim str As String = ""
'Var used to interact with SQL database
Dim db As New Interaction
'Adds the necessary markup for each menu item, using its productName
Protected Sub printMenuBlock(ByVal productName As String)
'Set up variable storing the product
Dim product As Product
'Pull the product in from our database using the productName
product = db.ReadProduct(productName)
'Add necessary markup to str variable, with products information within
str += "<div class='storeItem'>"
' str += " <img alt='Item Picture' class='itemPicture' src='" + product.ImagePath.Substring(3).Replace("\", "/") + "' />"
' str += " <div class='itemInfo'>"
str += " <h1 class='itemName'>"
str += " " + product.Name + "</h1>"
str += " <h3 class='itemDescription'>"
str += " " + product.Description + "</h3>"
str += " <p class='itemPrice'>"
str += " " + product.Price.ToString("c") + "</p>"
str += " "
str += " </div>"
str += " </div>"
End Sub
'Uses
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim productNames As New List(Of String)
'Pull the product names using the database
productNames = db.getProductNames
'Loop through all product names
For Each name As String In productNames
'Add necessary markup and product info to str variable
printMenuBlock(name)
Next
'Print the str variable in our menuPlace div
menuPlace.InnerHtml = str
End Sub
End Class
This is functions from interaction class:
Private Sub GetProduct(ByVal CatIn As String)
' SQL String
Dim strSelect As String
strSelect = "SELECT * "
strSelect &= " FROM Menu "
' strSelect &= " WHERE (ProductCat = 'Burgers')"
' Set up the connection to the datebase
cmdSelect.Connection = conIn.Connect
' Add the SQL string to the connection
cmdSelect.CommandText = strSelect
' Add the parameters to the connection
cmdSelect.Parameters.Add("#CatIn", SqlDbType.NVarChar).Value = CatIn
End Sub
'Executes the SQL statement to find a Product by ProductId
Public Function ReadProduct(ByVal CatIn As String) As Product
' Product object initalized to nothing
Dim prod As Product = Nothing
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
Dim strCat As String
Dim strName As String
Dim strDesc As String
Dim decPrice As Decimal
Dim strPath As String
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
dbr.Read()
' Check if there are any returned values
If dbr.HasRows Then
' Assign the value in column two to strName
strCat = dbr.GetString(1)
' Assign the value in column two to strName
strName = dbr.GetString(2)
' Assign the value in column three to strDesc
strDesc = dbr.GetString(3)
' Assing the value in column four to intPrice
decPrice = ToDecimal(dbr.GetValue(4))
'Assign the value in column five to strPath
'strPath = dbr.GetString(3)
' Create the new Product object from the returned values
prod = New Product(strName, strDesc, decPrice, strCat, strPath)
End If
' Clear the SQL parameters and close the connection
cmdSelect.Parameters.Clear()
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return prod
End Function
'Returns a list of Product Names
Public Function getProductNames() As List(Of String)
Dim list As New List(Of String)
Dim sql As String = "SELECT ProductName FROM Menu " +
"WHERE (ProductCat) = 'Burgers'"
'"DISTINCT 'ProductName'"
cmdSelect.CommandText = sql
cmdSelect.Connection = conIn.Connect
Dim dbr As SqlDataReader
dbr = cmdSelect.ExecuteReader
If dbr.HasRows Then
Do While dbr.Read()
list.Add(dbr.GetString(0))
Loop
End If
dbr.Close()
Return list
End Function
There is obviously a Product Class but don't think that is necessary to show on here.
Also, ignore the string path, that will be for images later. Thanks for any help. I'm pretty sure instead of do while I need a for each somewhere but just can't get her done. Thanks in advance.
Products Class:
Public Class Product
Private pName As String
Private pDescription As String
Private pPrice As Integer
Private pPath As String
Private pCat As String
'Constructor, uses database to populate properties based on productName
Public Sub New(ByVal productName As String)
Dim data As New Interaction
Dim work As Product
work = data.ReadProduct(productName)
pCat = work.Cat
pName = work.Name
pDescription = work.Description
pPrice = work.Price
End Sub
'Constructor, populates properties from passed in values
Public Sub New(ByVal NameIn As String,
ByVal DescriptionIn As String, ByVal PriceIn As Integer, ByVal CatIn As String, ByVal ImagePathIn As String)
pName = NameIn
pDescription = DescriptionIn
pPrice = PriceIn
pPath = ImagePathIn
pCat = CatIn
End Sub
'Stores name of product
Public ReadOnly Property Name() As String
Get
Return pName
End Get
End Property
'Stores a description of the product
Public ReadOnly Property Description() As String
Get
Return pDescription
End Get
End Property
'Stores the price of the product
Public ReadOnly Property Price() As Integer
Get
Return pPrice
End Get
End Property
'Stores the path to the image associated with this product
Public ReadOnly Property ImagePath() As String
Get
Return pPath
End Get
End Property
'Stores name of product
Public ReadOnly Property Cat() As String
Get
Return pCat
End Get
End Property
End Class
Use this instead
Public Function ReadProduct(ByVal CatIn As String) As List(Of Dictionary(String, Of String))
Dim ReturnProducts As New List(Of Dictionary(String, Of String))
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
Dim FieldCount = dbr.FieldCount()
Dim ColumnList as New List(Of String)
For i as Integer = 0 to FieldCount - 1
ColumnList.Add(dbr.GetName(i))
Next
While dbr.Read()
Dim ReturnProduct As New Dictionary(String, Of String)
For i as Integer = 0 to FieldCount - 1
ReturnProduct.Add(ColumnList(i), dbr.GetValue(i).toString())
Next
ReturnProducts.Add(ReturnProduct)
End While
cmdSelect.Parameters.Clear()
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return ReturnProducts
End Function
then, inside printMenuBlock, you declare product with
Dim product = db.ReadProduct(productName)
and later, you access it like so
For i as Integer = 0 to product.Count - 1
'do everything normally for building str except, for example, if you want
'to acccess product.Name as before, access it with product(i).Item("Name"),
'assuming that your column name/alias for "Name" is in fact "Name"
'i personally like to align column names to variable names for laziness's sake
'bad obfuscation practice tho if you don't use aliases
Next
Very odd issue. When trying to register a new user on the server, the server will post back messages such as "OK" and "usernameTaken". Upon comparing this returned string with another string (to perform an action based on the returned value), the compare isn't working.
Dim backupX As New CBackup
backupX.startSocket("127.0.0.1", 8888)
Dim str1 As String = backupX.registerUser("user1", "testpass")
Dim str2 As String = "usernameTaken"
If String.Equals(str1, str2) Then
MsgBox("Strings are Equal() ")
Else
MsgBox("Strings are not Equal() - " & str1 & " vs " & str2)
End If
This results in:
So what this shows is that even though the strings are equal, it sais they aren't. And the MsgBox should be saying Strings are not Equal() - usernameTaken vs usernameTaken, it left the vs usernameTaken part out completely.
What's going on here?
Extra info on CBackup class:
backupX.registerUser function:
Public Function registerUser(ByVal name As String, ByVal password As String) As String
Dim md5 As New CMD5
If name.Contains(",") Then
Return "0-commaInName"
Else
Return SocketSendAndReceiveMSG("registerUser," & name & "," & md5.GenerateStringHash(password))
End If
End Function
SocketSendAndReceiveMSG function:
Private Function SocketSendAndReceiveMSG(ByVal msg As String) As String
Return socket.sendAndReceiveMSG(msg)
End Function
socket.sendAndReceiveMSG function:
Public Function sendAndReceiveMSG(ByVal msg As String) As String
Dim serverStream As NetworkStream = clientSocket.GetStream()
sendMSG(msg & "$", serverStream)
Return receiveMSG(serverStream)
End Function
receiveMSG function
Public Function receiveMSG(ByVal serverStream As NetworkStream) As String
Dim inStream(10024) As Byte
Dim buffSize As Integer = clientSocket.ReceiveBufferSize
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream)
Form1.msg("Data from Server : " & returndata)
Return returndata
End Function
Looks to be like the socket code is working just fine.. each Function returns the corresponding Functions' Return value (registerUser -> SocketSendAndReceiveMSG -> sendAndReceiveMSG -> receiveMSG). I don't see how this could be messing the str1 string variable up like this..
Set a breakpoint on the line If String.Equals(str1, str2) Then and inspect both strings. Are they of the same length? Is the program stopping at your breakpoint or is another code part running?