VB.net String Reverse Property different based on Env - vb.net

I am debugging an application that runs on a server and users will access the application on another server. The application uses encryption and as part of the key, I am using the String.Reverse property.
Dim Mystring As String = "123abc"
Dim reverse = String.Format("{0},{1}", Mystring.Reverse)
The string reverse is different when I run it from one machine (RDP/Citrix Environment ASP.NET 4.6.1). The value is:
System.Linq.Enumerable+<ReverseIterator>d__a2`1[System.Char]
The same string, but ran from another machine (RPD non-Citrix Environment ASP.NET 4.5.2). The value of reverse is:
System.Linq.Enumerable+<ReverseIterator>d__73`1[System.Char]
Why are the values different in the different environments?

Look at this line first:
Dim reverse = String.Format("{0},{1}", Mystring.Reverse)
Specifically, this expression:
Mystring.Reverse
Reverse is a function, not a property, but it's missing the parentheses (). The trick here is the String.Format() method accepts the base Object type as an argument, and compiler is able to treat the MyString.Reverse expression as a delegate type that is convertible to object. The values you see in your output are the result of calling .ToString() on that function delegate. It's the type name for the function, rather than anything to do with the value of your MyString object. Since that type is dynamically and randomly generated at runtime, you'll see different values not only on different platforms, but different runs on the same computer.
In the VB6 era, it was normal to call methods without the parentheses. In the .Net world, always use parentheses when you call a method.
What you want is this:
Dim reverse As String = String.Format("{0},{1}", Mystring.Reverse())
Even here, you're missing the second argument to match the format string. I doubt you'll get the result you expect.
Finally, reversing a string as the key seems very wrong when it comes to encryption. You are using a real cyrptogrpahic algorithm from the System.Security.Cryptography library, right? Right!?

You are not outputting the value of the reversed String but the name of the type used to perform the reversal. That type is dynamically created and randomly named. The "d" in those two names means "dynamic" and the "a2" and "73" parts are random.
Basically, what you perceive to be an issue is not an issue. The problem is that you're not actually creating a String from the reversed output. You say "String.Reverse property but that is NOT a property. It is a method and it is not a member of the String class but rather an extension method on the IEnumerable(Of T) interface. You are treating your String as an enumerable list of Char values and reversing that. If you want a String from that then you need to create one, i.e.
MyReversedString = New String(Mystring.Reverse().ToArray())
That will push the contents of your iterator into an array and then create a new String object from that array.

Related

Difference between replaceCharacterInRange and stringByReplacingOccurrenceOfString

I m very confused with the string replacing methods of objective c.
Please tell where to use ReplaceCharacterInRange method and Where to use
stringByReplacingOccurrenceOfString Method.
These two methods differ a lot.
replaceStringWithCharactersInRange: withString:replaces all characters in the given range with the new string. It works on a NSMutableString and changes the string object you call it on.
In contrast stringByReplacingOccurrencesOfString:withString: replaces all occurrences of a given string, but returns a new string object. So it does work with immutable string as well.
So you use the first method if you want to keep your string but change parts of it while you use the second when you want to replace certain substrings within the string without changing the original string.

String.Concat with non-string arguments, unexpected behaviour

As a summary: I'm trying to get String.Concat to use a reference type's ToString overload when sticking string together.
Edit: Added this overview: The example code below is a cooked down extract of my real code - as such it would be immediately obvious when refactoring if I only had two lines of code. The important issue here (to me) is that I changed from a string to an object and there was no compile error from String.Concat. Equally it's behaviour wasn't what I would have expected (Using my object's to string method, rather than the bog standard object name). If I'd been using "&", there would have been a compile error. I'm concerned that the String.Concat syntactic sugar may lead to bugs that otherwise would have been avoided (in this case when refactoring). I'd like to know if there's a way of altering the behaviour of String.Concat or if I should consider it to be dangerous.
The situation:I've got a solution which processes a whole heap of data; I was using a String to contain the identifier of each piece of data, but have just swapped this out for a class (FeatureIdentifier) to enable me to extend the identifier to include things like batches etc.
I've refactored my code so that I use this class instead of just the string. When refactoring this type of thing (rightly or wrongly) I tend to rely on compile errors as a to-do list.
Now, I'm a self-taught programmer and I'm probably a bit set in my ways (I tend to look at new features in terms of if they let me do anything new rather than if they let me do stuff I can already do only easier) and I've just come across something which makes me sad.
So, I was sticking my identifier onto an underscore onto a type. My code looked like this:
Dim x as string = "MyIdentifer"
dim myOutputValue as string = String.Concat(x,"_ANCHOR.txt")
Running this I got myOutputValue equal to "MyIdentifier_ANCHOR.txt". Following refactoring, my code looked like this:
Dim x as new FeatureIdentifier("MyIdentifier")
dim myOutputValue as string = String.Concat(x,"_ANCHOR.txt")
Running this I got myOutputValue equal to "MyNamespace.FeatureIdentifier_ANCHOR.txt".
Having kicked myself and implemented a ToString method on my class, I run it again and get exactly the same output (that is "MyNamespace.FeatureIdentifier_ANCHOR.txt"). In immediate, if I do: ?x.ToString, I get "MyIdentifier", so I'm certain I've implemented ToString correctly.
So, here's my problem. I like the syntax of String.Concat but I don't like the fact that it doesn't do one of:
a) calling ToString on reference types it sticks together orb) throwing a compile error if you pass it non-string based arguments. The old school: x & "_ANCHOR.txt" gives me a compile error (which I would have picked up when refactoring).
Here's what I've tried:
I've tried shadowing the String.Concat function with an extension (something like this:
<System.Runtime.CompilerServices.Extension()> Public Function Concat(...some arguments...) As String
Return String.Concat(...some arguments...)
End Function
) but hit two problems:
1) When trying to narrow the type of the arguments down to string to cause compile errors, I realised that the argument is a param array and hence objects in the first place. So fail there.
2) When I tried to make multiple overloads ((s1 as string, s2 as string), (s1 as string, s2 as string, s3 as string) etc), I felt it was a bit lame and also discovered that you can't actually overload an extension on a static class (which is what I guess String is).
So, does anyone know a way of getting String.Concat to behave as well as old-school concatenation, or should I avoid String.Concat in favour of old-school concatenation?.
(I'm not going to use a StringBuilder, as I'm only concatenating a few strings and I don't believe this is the place for one).
I don't believe there is any way that you are going to "fix" the String.Concat method to only allow strings. Chalk it up to another reason why shared methods should be created and used as sparingly as possible. However, through the miracle of operator overloading, you can make your custom class work just like a string. To fix the Concat method, you need to overload the CType operator. To fix the string concatenation operator (&), you need to overload that operator separately, like this:
Public Class FeatureIdentifier
Public Sub New(id As String)
Me.Id = id
End Sub
Public Property Id As String
Public Property SomethingElse As Integer
Public Overloads Shared Widening Operator CType(value As FeatureIdentifier) As String
Return value.Id
End Operator
Public Overloads Shared Operator &(value1 As FeatureIdentifier, value2 As String) As String
Return value1.Id & value2
End Operator
Public Overloads Shared Operator &(value1 As String, value2 As FeatureIdentifier) As String
Return value1 & value2.Id
End Operator
End Class
Now you can use it like this:
Dim x As New FeatureIdentifier("MyIdentifier")
Dim myOutputValue As String = String.Concat(x, "_ANCHOR.TXT")
Or like this:
Dim x As New FeatureIdentifier("MyIdentifier")
Dim myOutputValue As String = x & "_ANCHOR.TXT"
And it will work just like as if it were still a string, in those circumstances. You may also want to overload some of the other operators too, just in case. For instance, the + operator also concatenates when applied to two strings. However, I should caution you that operator overloading can cause confusion to people who are not familiar with the code, since it works unexpectedly, so you should only use it if it really makes sense to do so.
Do you need to override ToString and even make sure it's called for this? It would seem to be more proper to expose a property of FeatureIdentifier named Identifier, or some such thing, and then you can just do:
Dim myOutputValue as string = String.Concat(x.Identifier, "_ANCHOR.txt")

Is there a way to use default arguments that are the result of a function call in VB.NET?

I have a whole slew of database access functions which assume a particular connection string. Within my application I call
myList = DB_MyTable.GetTableItems()
and within GetTableItems() I have something like
Dim connection As SqlConnection = MyDB.GetConnection
So the connection string is in one place in the code, and I call a method to get it.
What I'm running into now is I want to reuse the same database functions, but with a different connection string. I can rewrite all of the functions like DB_MyTable.GetTableItems() easily because they're generated from a script, but within the main application code I'll need to take care of every function call that now needs to know what connection string I want to use.
I tried changing the arguments to GetTableItems() like this:
Public Shared Function GetTableItems(Optional ByVal useThisString as String = MyDB.GetConnection) As List(Of MyItems)
in hopes of being able to pass in, by default, the string I'm already using in most of the code, but I got an error saying that the default value had to be a constant expression. This would mean peppering a specific connection string everywhere, which I don't want to do.
Is there a way to accomplish what I'm after, or do I need to make the connection string a required argument and change all of the calls in my application to match the new signature?
Thanks as always!
Can you make your default value an empty string? Then, in your functions, if the useThisString variable is blank, then use default, else use the one you passed in? A littler dirtier, but just barely.

How Do I Create Something 'OF' a Variable's Type?

I have some code like:
Lookup(Of String)("Testing")
Lookup(Of Integer)("Testing")
And both of those Lookups work great. What I'm trying to is call the appropriate LookUp based on the type of another variable. Something that would look like...
Lookup(Of GetType(MyStringVariable))("Testing")
I've tried to Google this but I'm having a hard time coming up with an appropriate search. Can anyone tell me how to do what I want?
You do not specify the full signature for the method that you're calling, but my psychic powers tell me that it is this:
Function Lookup(Of T)(key As String) As T
And you want to avoid having to repeat Integer twice as in the example below:
Dim x As Integer
x = Lookup(Of Integer)("foo");
The problem is that type parameters are only deduced when they're used in argument context, but never in return value context. So, you need a helper function with a ByRef argument to do the trick:
Sub Lookup(Of T)(key As String, ByRef result As T)
T = Lookup(Of T)(key)
End Sub
With that, you can write:
Dim x As Integer
Lookup("foo", x);
One solution to this is to use reflection. See this question for details.
You can't use a dynamic type unless you do runtime compiling, which of course is really inefficient.
Although generics allows you to use different types, the type still has to be known at compile time so that the compiler can generate the specific code for that type.
This is not the way to go. You should ask about what problem you are trying to solve, instead of asking about the way that you think that it should be solved. Even if it might be possible to do something close to what you are asking, it's most likely that the best solution is something completely different.
The VB.NET compiler in VS2008 actually uses type-inference. That means if you are using a generic method, and one of the parameters is of the generic type, then you don't need to specify the generic type in your call.
Take the following definition...
Function DoSomething(Of T)(Target As T) As Boolean
If you call it with a strongly-typed String for Target, and don't specify the generic parameter, it will infer T as String.
If you call it with a strongly-typed Integer for Target, and don't specify the generic parameter, it will infer T as Integer.
So you could call this function as follows:
Dim myResult As Boolean = DoSomething("my new string")
And it will automatically infer the type of T as String.
EDIT:
NOTE: This works for single or multiple generic parameters.
NOTE: This works also for variables in the argument list, not just literals.

Visual Basic 6.0 to VB.NET declaration

How do I declare "as any" in VB.NET, or what is the equivalent?
The closest you can get is:
Dim var as Object
It's not exactly the same as VB6's as Any (which stores values in a Variant) but you can store variables of any type as Object, albeit boxed.
VB.NET does not support the as any keyword, VB.NET is a strongly typed language, you can however (with .NET 3.5) use implicit typing in VB
Dim fred = "Hello World" will implicitly type fred as a string variable. If you want to simply hold a value that you do not know the type of at design time then you can simply declare your variable as object (the mother of all objects) NOTE, this usually is a red flag for code reviewers, so make sure you have a good reason ready :-)
As Any must be referring to Windows API declarations, as it can't be used in variable declarations. You can use overloading: just repeat the declarations for each different data type you wish to pass. VB.NET picks out the one that matches the argument you pass in your call.
This is better than As Any was in VB6 because the compiler can still do type-checking.
I suppose you have problems with converting WinAPI declarations. Sometimes you can get away if you just declare your variable as string or integer because that is the real type of value returned.
You can also try marshaling:
<MarshalAsAttribute(UnmanagedType.AsAny)> ByRef buff As Object
VB.NET doesn't support the "As Any" keyword. You'll need to explicitly specify the type.