Using & and + in asp.net with vb - asp.net

I have some confusion as to the use of + and & in ASP.NET and VB.NET. See the following code:
Dim dtUser As DataTable = GetDetails()
Dim serverPath As String = Nothing
Dim virtualServerPath As String = Nothing
Dim parentDir As DirectoryInfo = Nothing
Dim childDir As DirectoryInfo = Nothing
serverPath = Page.Server.MapPath(".") + "\"
virtualServerPath = serverPath.Substring(0, serverPath.LastIndexOf("\"))
virtualServerPath = virtualServerPath + "\SiteImages\" + dtUser.Rows(0)("Name")
parentDir = Directory.CreateDirectory(virtualServerPath)
childDir = parentDir.CreateSubdirectory(Session("RegID"))
Dim strUserName as String=dtUser.Rows(0)("Name")
If flUpload.HasFile Then
flUpload.SaveAs(Server.MapPath("~/SiteImages/" & dtUser.Rows(0)("Name") & "/" & childDir + "/" + flUpload.FileName))
I am getting error concerned with usage of + and & in
flUpload.SaveAs(Server.MapPath("~/SiteImages/" & strUserName & "/" & childDir + "/" + flUpload.FileName))
Can anybody help to remove the error

Use "&" for concatenation, "+" will work until you have a value that a mathematical operation can be performed on in the concatenation. It will attempt to perform the addition rather than concatenation.
eg.
"blah" & "blah" works
"blah" + "blah" works
"blah" & 5 works
"blah" + 5 fails
The last one does not work as it will try to "add" 5 and a string

change
flUpload.SaveAs(Server.MapPath("~/SiteImages/" &
dtUser.Rows(0)("Name") &
"/" &
childDir +
"/" +
flUpload.FileName))
to
flUpload.SaveAs(Server.MapPath("~/SiteImages/" &
dtUser.Rows(0)("Name") &
"/" &
childDir &
"/" &
flUpload.FileName))
and pay heed to #CodeWiki's comment on this answer that is not to mix + and & in one statement.

In VB, the & is for string concatenation. You should only use + for addition operations.
The problem with + is that it tries to do implicit conversion so you can do
2.5 + 5
C# would give you an error because 2.5 would be a float and 5 would be an int. You would need to cast them. VB does the casting implicitly which can hide some bugs.

As far as I know VB string concatenation uses &, don't use +
"A" & "B" & "C" = "ABC"
"A" + "B" + "C" = hmmm error? (Edit) apparently this works...
(More Edit)...
Possible answer to your error:
I don't think the error is anything to do with & or + now.
It might be your childDir which is of type DirectoryInfo. You might want to get the name of the directory in it instead of just plopping childDir in the string concat.
try change it to & childDir.Name in that concat.

Related

how to find the max id from a generic list

i m getting a collection of data in list's object. And from this list i want to get the maximum id.`
Dim objinfo As List(Of AlbumInfo) = objPhotos.GetPhotos_Alb_ID(Me.ModuleId, hdd_AlbID.Value)
Dim Photo_Image As String = ""
Dim str As String = Photo_Image & fu_Photo.PostedFile.FileName.Substring(fu_Photo.PostedFile.FileName.LastIndexOf("."))
If objinfo.Count >= 1 Then
Photo_Image = Convert.ToString(hdd_AlbID.Value) + "_" + Convert.ToString(objinfo.Item("0").Photo_Id + 1)
Else
Photo_Image = Convert.ToString(hdd_AlbID.Value) + "_" + Convert.ToString("1")
End If
this returns the "0"th positions id from Convert.ToString(objinfo.Item("0").Photo_Id + 1)
but i want to get the last item's id.
Well, you specify max in the title, and last in the question, so here's both:
Max:
Photo_Image = hdd_AlbID.Value.ToString() & "_" & _
objinfo.Max(Function(o) o.Photo_Id) _
.Photo_Id.ToString()
Last:
Photo_Image = hdd_AlbID.Value.ToString() & "_" & _
objinfo.Last().Photo_Id.ToString()
Use Max extension method. For example,
...
maxPhotoId = objInfo.Max(Function(photo) photo.Photo_Id).Photo_Id
...

Stripping data out of a string in Vbscript

I currently have a variable called databaseinformation in a script that I am writing. I want to seperate this into two variables called Instance_Name and Database_Name
The string in question:
[MSSQLSERVER]BESMgmt.BAK
In this instance the Instance_Name is MSSQLSERVER and the Database_Name is BESMgmt. The string will not necessarily end in .BAK but stripping the last four characters off the variable would be fine. The Instance_Name and Database_Name will change values and length.
Thanks for any help in advance
#Trinitrotoluene: Working sample code --
Option Explicit
Dim ToBeSplit, Instance_Name, Database_Name
Dim SplitMe
Dim Position
ToBeSplit = "[MSSQLSERVER]BESMgmt.BAK"
SplitMe = Split(ToBeSplit, "]")
If IsArray(SplitMe) Then
Instance_Name = SplitMe(0)
Database_Name = SplitMe(1)
End If
Instance_Name = Replace(Instance_Name, "[", "")
If InStr(Database_Name, ".") > 0 Then
Database_Name = Left(Database_Name, Len(Database_Name) - 4)
End If
Response.Write "Instance_Name = " & Instance_Name & "<br>"
Response.Write "Database_Name = " & Database_Name
Or do it with a regular expression object, this makes you more flexible, allthough some will say that you have two problems now:
Option Explicit
Dim regEx, matches
Dim myString : myString = "[MSSQLSERVER]BESMgmt.BAK"
set regEx = new RegExp
regEx.pattern = "\[(.*)\](.*).{4}"
set matches = regEx.Execute(myString)
msgbox "Instance_name: " & matches(0).subMatches(0) & vbNewLine & "Database_name: " & matches(0).subMatches(1)

sending email in from asp.net page

I want to add this to my email body and i want it to look like this but it doesnt work.
Tour: lotour.text
Date: loddate.text
Party: lolnumparty.text
first name: locfname.text
last name: loclname.text
as you see i want them right after another and it doesnt work when i use a </br>
this is my email body.
objEmail.Body = "There was a booking rquest made by " & Request.QueryString("comp") & " to see more details click the link " + x
this is my full code
If Page.IsValid And ValidateCCNumber(cardnumber.Text) = True Then
SqlDataSource1.Insert()
Dim x As String
x = "http://www.clubabc.com/bookingrequest/confirm.aspx?date=" & HttpUtility.UrlEncode(now.Text) & "&tfname=" & HttpUtility.UrlEncode(p1fname.Text) & "&tlname=" & HttpUtility.UrlEncode(p1lname.Text) & "&comp=" & HttpUtility.UrlEncode(Request.QueryString("comp") & "&land=" & HttpUtility.UrlEncode(land.Text))
Dim objEmail As New MailMessage()
objEmail.To = "cnna#BC.com"
objEmail.From = "page#bc.com"
objEmail.Cc = memail.Text
objEmail.Subject = "Booking for " + p1fname.Text + " " + p1lname.Text + " made by " & Request.QueryString("comp")
objEmail.Body = "There was a booking rquest made by " & Request.QueryString("comp") & " to see more details click the link " + x
SmtpMail.SmtpServer = "mail.bc.com"
Try
SmtpMail.Send(objEmail)
Catch exc As Exception
Response.Write("Send failure: " + exc.ToString())
End Try
Response.Redirect("http://www.clubabc.com/bookingrequest/confirm.aspx?date=" + now.Text + "&tfname=" + p1fname.Text + "&tlname=" + p1lname.Text + "&comp=" + Request.QueryString("comp") & "&land=" & HttpUtility.UrlEncode(land.Text))
ElseIf ValidateCCNumber(cardnumber.Text) = False Then
invalidcard.Visible = True
End If
I guess you are searching for (MSDN):
Environment.NewLine
The <br> tag will only work in HTML Emails.
Update
This would be a very simple example, how you could use Environment.NewLine:
Imports System
Class Sample
Public Shared Sub Main()
Dim firstName As String = "John"
Dim lastName As String = "Doe"
Dim city As String = "Brooklyn"
Console.WriteLine("First name: " + firstName + Environment.NewLine + "Last name: " + lastName + Environment.NewLine + "City: " + city + Environment.NewLine)
End Sub
End Class
Try to set IsHtml property for objEmail variable to get some more formatting possibilities.
Do not use Enviornment.NewLine, instead use vbCrLf
Environment.NewLine may only output Cr or Lf, which may cause your email to either:
a)Be blocked because it's not RFC complient
or
b)Be marked as spammy
To have new lines in email, always use CrLf.
--Dave

VS Macro/Add-in to convert string concatenations to string.format style

I have project in development where string operations like "Hi " + variable + ", welcome to Project" are used at many places (given example is very minor one).
One of the requirement is to convert it to string.format style.
It is very long and tedious job, where I would not like to break earlier working code due to any human error might happen while converting it.
I would like to if any Macro or VS command which I can create to handle it. Just like we mark block of code and do Extract function in Re-factor options.
I felt the code was a little long to post here, but I posted an answer at my blog:
http://www.brianschmitt.com/2010/08/converting-concatenated-string-into.html
-- EDIT --
Per comment here is the relevant Macro - not sure why you cannot access...
Public Sub ConvertToStringFormat()
DTE.UndoContext.Open("ConvertToStringFormat")
Dim textSelection As TextSelection = DTE.ActiveDocument.Selection
Dim output As String = "string.Format(""{0}"", {1})"
Dim delimt As String = ", "
Dim fmtdTostring As String = ".tostring("""
Dim txtSelection As String() = System.Text.RegularExpressions.Regex.Split(textSelection.Text.Trim, "\+\s_[+\n\r\t]|&\s_[+\n\r\t]|\+|&")
Dim hardStrings As String = String.Empty
Dim valueStrings As String = String.Empty
Dim counter As Int16 = 0
For Each str As String In txtSelection
Dim tmpString As String = str.Trim
If tmpString.StartsWith("""") Then
hardStrings &= tmpString.Substring(1, tmpString.Length - 2)
Else
Dim fmt As String = String.Empty
Dim indxToString As Int32 = 0
If tmpString.ToLower.Contains(fmtdTostring) Then
indxToString = tmpString.ToLower.IndexOf(fmtdTostring)
fmt = tmpString.Substring(indxToString + 11, tmpString.Length - tmpString.ToLower.IndexOf(""")", indxToString) - 1)
End If
If fmt <> String.Empty Then
hardStrings &= "{" & counter.ToString & ":" & fmt & "}"
valueStrings &= tmpString.Substring(0, indxToString) & delimt
Else
hardStrings &= "{" & counter.ToString & "}"
valueStrings &= tmpString & delimt
End If
counter += 1
End If
Next
If valueStrings <> String.Empty Then valueStrings = valueStrings.Substring(0, valueStrings.Length - delimt.Length)
textSelection.Text = String.Format(output, hardStrings, valueStrings)
DTE.UndoContext.Close()
End Sub

How to transform a date-string in classic asp

I'm a little blockheaded right now…
I have a date string in european format dd.mm.yyyy and need to transform it to mm.dd.yyyy with classic ASP. Any quick ideas?
If its always in that format you could use split
d = split(".","dd.mm.yyyy")
s = d(1) & "." & d(0) & "." & d(2)
this would allow for dates like 1.2.99 as well
Dim arrParts() As String
Dim theDate As Date
arrParts = Split(strOldFormat, ".")
theDate = DateTime.DateSerial(parts(2), parts(1), parts(0))
strNewFormat = Format(theDate, "mm.dd.yyyy")
OK, I just found a solution myself:
payment_date = MID(payment_date,4,3) & LEFT(payment_date,3) & MID(payment_date,7)
This is a way to do it with built in sanity check for dates:
Dim OldString, NewString
OldString = "31.12.2008"
Dim myRegExp
Set myRegExp = New RegExp
myRegExp.Global = True
myRegExp.Pattern = "(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)[0-9]{2})"
If myRegExp.Test Then
NewString = myRegExp.Replace(OldString, "$2.$1.$3")
Else
' A date of for instance 32 December would end up here
NewString = "Invalid date"
End If
I have my own date manipulation functions which I use in all my apps, but it was originally based on this sample:
http://www.adopenstatic.com/resources/code/formatdate.asp
function MyDateFormat(mydate)
'format: YYYYMMDDHHMMSS
MyDateFormat = year(mydate) & right("0" & month(mydate),2) & _
right("0" & day(mydate),2) & right("0" & hour(mydate),2) &_
right("0" & minute(mydate),2) & right("0" & second(mydate),2)
end function
response.write(MyDateFormat(Now))
show: 20200623102805

Resources