converting a string to a constant string - asp.net

I have the following code...
Const ToAddress As String = username.Text & "#gmail.com"
which sets to ToAddress to be used in on my Net.Mail.MailMessage
that is to be created with the following constructor
Dim mm As New Net.Mail.MailMessage(username.Text, ToAddress)
which takes in a string and a constant string. But I get an error here
Const ToAddress As String = **username.Text** & "#gmail.com"
that says : constant expression required

how to use mailmessage
username.text is variable, you wont be able to create a const
you can always create a function that would do validation on the username.text
public function ToAddress(byval _username as string) as MailAddress
'
'validation here for _username
'
return new MailAddress(_username & "#gmail.com")
end function

That is not how a Const should be used. See the first line here. "a constant is a special kind of variable whose value cannot be altered during program execution"
Edit: See Fredou's answer for the correct syntax.

VB.NET and C# are not C. Constant modifier is just used for constants whose values are known at the time of compilation.

Remember that a constant is a value that is compiled as a literal into the assembly by the compiler. This is why you cannot define constants as an expression because the compiler cannot evaluate the expression at compilation time.
When you define a constant the compiler takes the value of that constant and replaces all uses of the constant in your source with the literal value. In your example I don't see any reason why you would need to define your string as Const since the method receiving the string will have no way of determining if the string was a Const at compilation time.

Rather than using a Const, specifically, if you just want the "constant" behavior for the life of an instance of your class, try:
ReadOnly ToAddress As String = username.Text & "#gmail.com"

Thank you for your assistance. I closed visual studio and restarted it and now it's sending mail works fine. Seems like VS has a bug...

Related

Newtonsoft Json JsonSerializationException with simple string

My datasource creates the JSON representing an array of integers as "1,2,3,4,5". I can't do anything about this (Like changing it to [1,2,3,4,5]), it is an enterprise CMS that we have to just deal with.
I'm trying to read up on how the newtonsoft ToObject method handles the following code:
JValue theValue = new JValue("1,2,3")
List<int> x = theValue.ToObject<List<int>>();
I get a Newtonsoft.Json.JsonSerializationException. Could not cast or convert from System.String to System.Collections.Generic.List`1[System.String]. I understand this fully, but I'd like to know if the Newtonsoft JSON libraries have a built in way to convert from a comma delimited string to a List.
I'd like to think there's a better way than trying to check if the variable is a comma delimited list or not and then converting it to a List<> manually, or maybe a JArray, but I've been wrong before !
EDIT
I wanted to share my solution:
dynamic theValue = new JValue("1,2,3,4"); /// This is just passed in, i'm not doing this on purpose. Its to demo.
if (info.PropertyType == typeof (List<int>))
{
if (info.CanWrite)
{
if (theValue.GetType() == typeof (JValue) && theValue.Value is string)
{
theValue = JArray.Parse("[" + theValue.Value + "]");
}
info.SetValue(this, theValue.ToObject<List<int>>());
}
} else {
// do other things
You have three problems from what I can see:
You should be using JArray not JValue. You are intending this to be an array of things, so you need to use the equivalent class in Newtonsoft to represent an array. (A JValue, as best I can tell, represents a simple type--e.g. string, number, Date, etc.)
You should use the Parse method versus using the constructor. Parse will read the content of the string as an array, however...
...in order for it to do that, you will need to surround the data that you get with the square brackets or JArray can't correctly the parse the data. There is no need to fiddle with the CMS; just do a string concat before you parse.
e.g.
JArray theValue = JArray.Parse("[" + "1,2,3" + "]");

Convert a String to Call a Public Class ASP.NET VB

I have looked at this link and I cannot seem to get it to work
Creating a New control of the same type as another control that is already declared
I have also tried this from searches:
Dim ClassToCreate As String = "TestClass1.CountItems"
Dim myInstance = Activator.CreateInstance(Type.GetType(ClassToCreate), True)
Error is:
"Value cannot be null.
Parameter name: type"
Problem:
I have multiple classes and want to change which one is called based on a string.
(example is not correct of course)
Dim strClassToCall = "TestClass1.CountItems"
'then convert the string to the actual class so it can be called like this:
Dim strResult = TestClass1.CountItems(strSomeParameter)
Thanks for your help!
Based on the error message it sounds like your Type is not getting loaded properly as it is null. The method you are using will create the object like you need assuming you get the valid Type to pass to the activator. Is the type coming from an referenced DLL?
Here is one method you could use to get the type if just using the string representation is not working. This uses reflection to find the type:
// Sorry this is c# :)
System.Reflection.Assembly pAssembly = System.Reflection.Assembly.Load(
System.Reflection.Assembly.GetExecutingAssembly().
GetReferencedAssemblies().Single(a => a.Name.Equals("YourNamespace.ClassName")));
yourType = pAssembly.GetTypes().First(c => (c.FullName != null) &&
c.FullName.Equals("YourNamespace.ClassName"));
var yourObject = Activator.CreateInstance(yourType, true);

Why is TrimStart not recognised in VisualStudio for ASP.NET?

I whant to use TrimStart for my string value like this: How to remove all zeros from string's beginning?
But TrimStart syntax is not recognise in VisualStudio. How to corectly generate it?
my code:
string str = parameters.Internal;
string s = str;
string no_start_zeros = s.TrimStart('0');
At the top of your .CS file do you have: using system; the string.TrimStart(); method is found in the system namespace, which is contained inside mscorlib.dll - you can also try referencing mscorlib.dll directly.
TrimStart() function is used to Removes all leading occurrences of a set of characters specified in an array from the current String object.
when visual studio version you are using ? as far as I know trimStart() support in almost all version from 1.1 to 4.5
check out below snippet for more detail
string szInput = "000YTHLKJH";
string output = szInput.TrimStart('0');
//output will be : YTHLKJH
Hope it helps

Looks like a query string, but won't act as a query string

I am working with VB in asp.net,
The basic problem is, I want to pair up the elements in a string, exactly like request.QueryString() will do to the elements in the query string of the web page.
However instead of the function looking at the current webpage query string I want it to look at a string (that is in the exact form of a query string) stored as a variable.
So if I define a string such as:
Dim LooksLikeAQueryString As String = "?category1=answer1&category2=answer2"
I want a function that if I input LooksLikeAQueryString and "category1" it outputs "answer1" etc.
Is there anything that can already do this or do I have to build my own function? If I have to build my own, any tips?
I should add that in this case I won't be able to append the string to the url and then run request.QueryString.
You can use the HttpUtility.ParseQueryString method - MSDN link
ParseQueryString will do it for you - something along these lines:
Private Function QueryStringValue(queryString As String, key As String) As String
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(queryString)
For Each s As String In qscoll.AllKeys
If s = key Then Return qscoll(s)
Next
Return Nothing
End Function
Usage:
Dim LooksLikeAQueryString As String = "?category1=answer1&category2=answer2"
Response.Write(QueryStringValue(LooksLikeAQueryString, "category2"))
If you dont want the dependancy of System.Web, of the top of my head
public string GetValue(string fakeQueryString,string key)
{
return fakeQueryString.Replace("?",String.Empty).Split('&')
.FirstOrDefault(item=>item.Split('=')[0] == key);
}

How to extract website hostname from full url using VB.NET?

I get ReffererUrl from current User, if refferer is exists i need to extract hostname without .com/.co.uk .... etc. value from it. So if ReffererUrl is http://main.something.biz/sup.aspx?r=e3432r3 i want to get just "something".
Doesn't matter whether it is Regex or something else.
thanks...
Note: it is just for your specs only: you can extend it by adding more condition at the end of my code. but i'd say that it wont work when path is like "abc.ss33.video.somthing.co.us"
Uri u = new Uri("http://main.something.biz/sup.aspx?r=e3432r3");
string a = u.DnsSafeHost;
string[] arr1 = a.Split('.');
string somethinVar = String.Empty;
if (arr1.Length == 3)
somethinVar = arr1[1];
There is no built-in way to do this in the sense you describe, because neither IIS nor ASP.NET knows the difference between the host name and domain name.
You have to write some code to do that.
an example could be:
string hostName=ReffererUrl.split('.')[1];
This code works only if the ReffererUrl look like the one you have posted and you have to make sure the array that the split function return an array with a number of elements greater than 1
HttpContext.Current.Request.ServerVariables("HTTP_HOST")
Extract domain with subdomain if present:-
Public Function ExtractSubAndMainDomainFromURL(URL As String) As String
'
' cut-off any url encoded data
URL = URL.Split("?"c)(0)
'return array of segments between slashes
Dim URLparts() As String = URL.Split("/"c)
'find first segment with periods/full-stops
Dim Domain As String = Array.Find(URLparts, Function(x) (x.Contains(".")))
'check if nothing returned - if necessary
If IsNothing(Domain) Then Domain = String.Empty
Return Domain
End Function

Resources