Eliminate Portion of String in VB.NET - asp.net

Lets say I have a variable: varEmail. It contains a variable equal to the user's email address, so it might contain a value like:
"myemail#emailserver.com"
Now, lets say I want to get just a portion of the email address, e.g. strip off the domain, like so:
"myemail"
How can I accomplish this in VB.NET with string manipulation? I know this must be simple...maybe it is just early in the morning...

The first one gives the email name; the second gives the domain name.
dim varEmail as string="myemail#emailserver.com"
MsgBox(varEmail.Substring(0, varEmail.IndexOf("#")))
MsgBox(varEmail.Substring(varEmail.IndexOf("#") + 1))

If you know you are always dealing with valid email addresses, the easiest way might be as so:
varEmail = varEmail.Split("#"c)(0)

For the fun of it, here is a more old school approach that still works in .Net (and like Matt's answer, this assumes you know this is a valid E-mail Address)...
strResult = Mid(varEmail, 1, (InStr(varEmail, "#") - 1))
If you aren't sure you have a valid e-mail do this in a try catch (it will throw an exception if the e-mail is not valid)...
Dim objMail As New System.Net.Mail.MailAddress(varEmail)
strResult = objMail.User

You can use Split method. For example:
Dim MyString As String = "myemail#emailserver.com"
Dim MyString2() As String
Dim MyString3 As String
MyString2 = Split(MyString, "#", -1, CompareMethod.Binary)
MyString3 = MyString2(0)
Now MyString3 = myemail

Here is the solution for your problem:
Dim value, result as string
value="myemail#emailserver.com"
result = value.Substring(0, value.IndexOf('#')+1)
I hope this will help you out.

Related

Replace the value in asp.net

I want to replace the numeric value in drpFPortofCall.SelectedValue.ToString.
For example, given the string AEJEA~12060 I want the result to be AEJEA. Given the string INNSA~12430 I want the result to be INNSA only. How can I do this?
I tried the following but wasn't able to get through.
Dim frmport As String = drpFPortofCall.SelectedValue.ToString
frmport = frmport.Replace("~", "")
Easy and Simple
Using IndexOf you will replace the rest
Dim frmport As String = drpFPortofCall.SelectedValue.ToString()
Dim value as String = frmport.Substring(0, frmport.IndexOf("~"))
You can use regex to extract everything until the "~".
Here is an example. And a fiddle.
Dim foo = "AEJEA~12060"
Dim match = Regex.Match(foo,".+?(?=~)")
Dim x = match.Value
Console.WriteLine("x = " & x)
Edit: you will need this import:
Imports System.Text.RegularExpressions
First of all, I'm pretty sure drpFPortofCall.SelectedValue is already a string (What you have might not be a ListControl directly, but it almost certainly inherits this property from it). That is, further calling .ToString() from there is silly at best and wasteful at worst.
Moving on from there, it seems like you want everything up to the ~. One option looks like this:
Dim frmport As String = drpFPortofCall.SelectedValue.Split("~"c)(0)
But that might be slower. With a little more code we could do it like this, which might be very slightly faster:
Dim endIndex As Integer = drpFPortofCall.SelectedValue.IndexOf("~"c)
Dim frmPort As String = drpFPortofCall.SelectedValue.SubString(0, endIndex)
... but you won't notice the difference unless you need to run this on 10s of thousands of inputs.
Finally, the two samples we have are strikingly similar in structure, down to the number of characters in each spot. If you can be sure that all of your data follows this format exactly, we can do even better:
Dim frmPort As String = drpFPortofCall.SelectedValue.SubString(0, 5)

VB.net / asp.net: Get URL without filename

i want to set a link in VB.net dynamically to a file.
My url looks like that:
http://server/folder/folder2/file.aspx?get=param
I tried to use Request.URL but i have not found any solution to get only
http://server/folder/folder2/
without the query string and without the filename.
Please help.
Dim url = Request.Url;
Dim result = String.Format(
"{0}{1}",
url.GetLeftPart(UriPartial.Authority),
String.Join(string.Empty, url.Segments.Take(url.Segments.Length - 1))
)
You can easily get a relative file path using the Request instance, then work with that, using Path class ought to help:
Dim relativePath = Request.AppRelativeCurrentExecutionFilePath
Dim relativeDirectoryPath = System.IO.Path.GetDirectoryName(relativePath)
It's worth noting that GetDirectoryName might transform your slashes, so you could expand the path:
Dim mappedPath = HttpContext.Current.Server.MapPath(newpath)
So, to remove redundancy, we could shorten this:
Dim path = _
Server.MapPath( _
Path.GetDirectoryName( _
Request.AppRelativeCurrentExecutionFilePath)))
But you'll need to check for possible exceptions.
You can use Uri.Host to get the computer name and then Uri.Segments (an array) to get everything up to the filename, for example:
var fileName = Uri.Host && Uri.Segments(0) && Uri.Segments(1)
This will give you: server/folder/folder2
If you have a variable number of segments, you can iterate over them and ignore the last one.
I hope that might help :)

Compare values from data source to string

I'm just stumped on what to do with this code, I'm just trying to implement a 'no duplicates' catch on my insert customer form, but it just slips through my if statement to the else everytime. This is the source. Also I tried a .Equals with the same results :(
Protected Sub srcAllClients_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles srcAllClients.Inserting
'Establish Variables
Dim emailAddress As String
Dim srcUsers As SqlDataSource = New SqlDataSource()
srcUsers.ConnectionString = ConfigurationManager.ConnectionStrings("ISSD21ConnectionString").ConnectionString
Dim view As DataView
view = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), DataView)
srcUsers.SelectCommand = "SELECT EmailAddress FROM ISSDClients"
srcUsers.DataSourceMode = SqlDataSourceMode.DataReader
Dim reader As IDataReader
reader = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), IDataReader)
emailAddress = FormView1.FindControl("txtEmail").ToString
While reader.Read()
If reader("EmailAddress") = (emailAddress) Then
lblError.Text = "Your Email is NOT Unique!"
'this is where we cancel the update and return an error
Else
lblError.Text = "Your Email is Unique!"
'nothing needs to happen, maybe just tell them that it went through
End If
End While
reader.Close()
End Sub
emailAddress = FormView1.FindControl("txtEmail").ToString
is just going to return the string "System.Web.UI.WebControls.TextBox". You're not accessing the actual property of the control that would hold the text value, you're just calling ToString() on the control itself.
Try this:
Dim emailBox As TextBox = CType(FormView1.FindControl("txtEmail"), TextBox);
emailAddress = emailBox.Text
In addition to Womp's answer...
In the while loop that is running through the email records, you need to break out of the loop once you find a matching email and alert the user.
if reader("EmailAddress") = (emailAddress) then
'1. Break from the Loop
End if
I would recommend that you pass the emailAddress to the SQL Server as a parameter.
Select Count(EmailAddress) From ISSDClients
Where EmailAddress = #EmailAddress
Execute this statement using ExecuteScalar and cast the result as an integer. If the result is zero then you are ok, otherwise display an error.
Doing it this way avoids using the while loop and should be much quicker if your table has lots of rows.
You also need to get the Text property from the Email Text box.
emailAddress = FormView1.FindControl("txtEmail").Text.ToString
You may want to take a look at the String.Compare method, which will make it easier to compare without respect to things like case sensitivity and culture. It does consider whitespace to be part of your string, so you may wish to trim the string prior to calling it, to help normalize.
For example, the following strings would be considered equal:
var firstString = "some StrinG to Compare ";
var secondString = " somE string to COMPARE";
var equal = (String.Compare(firstString.Trim(), secondString.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0);

How to avoid IndexOutOfRangeException indexing DataReader columns?

I am having a little trouble with an 'IndexOutOfRangeException'. I think it is because when the code tries to get the DateModified col from the database it sometimes contains NULLS (the users haven't always updated the page since they created it).
Here is my code;
s = ("select datemodified, maintainedby, email, hitcount from updates where id = #footid")
Dim x As New SqlCommand(s, c)
x.Parameters.Add("#footid", SqlDbType.Int)
x.Parameters("#footid").Value = footid
c.Open()
Dim r As SqlDataReader = x.ExecuteReader
While r.Read
If r.HasRows Then
datemodified = (r("DateModified"))
maintainedby = (r("maintainedby"))
email = (r("email"))
hitcount = (r("hitcount"))
End If
End While
c.Close()
I thought (after a bit of msdn) that adding;
If r.HasRows Then
End If
Would solve the problem, but so far after adding I am still getting the same old IndexOutOfRangeException
(ps, I have tried datemodified as string / datetime)
Try r.IsDBNull(columnIndex).
Does changing
datemodified = (r("DateModified"))
to
datemodified = (r("datemodified"))
work?
I have tried to recreate you issue by passing in nulls, empty sets. I can't recreate it in the sample of code you provided. Would you mind posting more code, maye even the whole page? Is there a line number that the error happens on? I would like to dig in further.

Getting the Request Variables from an ASP.NET page

I wrote the following function that works about 95% of the time, but I need it to work 100% (obviously):
Public Shared Function getPassedVars() As String
Const keyCount As Integer = 54 ' 54 seems to be the number of parameter keys passed by default (for this web_app).
' there are more if there is a form involved (ie. from search page)
Dim oParams As String = ""
Try
With HttpContext.Current
If .Request.Params.AllKeys.Count > keyCount Then
For i As Integer = 0 To (.Request.Params.AllKeys.Count - (keyCount + 1))
oParams &= String.Format("{0}={1}{2}", .Request.Params.Keys.Item(i), .Request.Params(i), IIf(i < .Request.Params.AllKeys.Count - (keyCount + 1), ";", ""))
Next
End If
End With
Return oParams
Catch ex As Exception
Return Nothing
End Try
End Function
It scrubs the Request.Params object for passed variables, which are in the beginning of the array (the remaining ones are ASP parameters). I am pretty sure I've seen a different way to get these parameters, but I haven't been able to figure it out. Any suggestions?
EDIT
So it looks like I can use the Request.URL.Query to achieve this, I will investigate this and post back.
Here is what I came up with:
Public Shared Function getPassedVars() As String
Dim oParams As String = ""
Dim qString As String = ""
Dim oSplit As New List(Of String)
Try
With HttpContext.Current
qString = .Request.Url.Query
If qString.Length > 0 Then 'do we have any passed variables?
If qString.StartsWith("?") Then qString = qString.Remove(0, 1) 'remove leading ? from querystring if it is there
oSplit.AddRange(qString.Split("&"))
For i As Integer = 0 To oSplit.Count - 1
oParams &= String.Format("{0}{1}", oSplit.Item(i), IIf(i < oSplit.Count - 1, ";", ""))
Next
Return oParams
Else
Return Nothing
End If
End With
Catch ex As Exception
Return Nothing
End Try
End Function
So far so good.
Request.QueryString is a NameValueCollection, so the easiest way to get the "parameters" is to do the following:
foreach (String s in Request.QueryString) {
Response.Write(s + " = " + Request.QueryString[s]);
}
Where is your function located? If it's executing in the page's code behind then you definitely do not need to use the HttpContext variable.
It looks like you are trying to get values from the query string.
For example, for this URL:-
http://www.tempuri.org/mypage.aspx?param1=x&param2=y
I assume you want retreive the values of the query string parameters param1 and param2?
If so, just use:-
Dim param1 as String = Request.QueryString("param1")
Otherwise, if these parameters are contained in a form (an HTTP POST request) then use the method which Mitchel Sellers suggests.
If you know the name you can use the following to get it by key value
Dim myParamValue as String = Request.Form("MyKeyName")
Otherwise, you can loop through the form collection, by key etc, to get the values. The key is, do you really need to be parsing all 54 items? Or are you simply looking for a few specific values?
httpcontext.Current.Request.QueryString("KeyName")
Request.Params will contain the query parameters you're after.
There's no need to parse the info from Request.URL since it's already done for you.

Resources