How can I get the display name from my enum - vb.net

I have researched and it seems that most is bouncing around the problem I have.
#Code
#Imports System.ComponentModel
Dim values = New SelectList([Enum].GetNames(GetType(myEnum)).GetAttribute<DisplayAttribute>()
End Code
The last pararenthesis has a blue line under it and when hover tells me an expression is expected. I want to capture the display name from my enum and have tried many things found on the google search without success. Why am I getting the expression expected error?
Attempted to incorporate and now getting at end parenthesis
Dim type = typeof(MyEnum) ls is expected.

You might want to have a look at this awesome NuGet package called UnconstrainedMelody from Jon Skeet.
https://www.nuget.org/packages/UnconstrainedMelody/
Helpful static methods (or extension methods) for enums and delegates, with constraints which can't be expressed in regular C#.
Have a look at the functions UnconstrainedMelody.Enums.GetNames() and UnconstrainedMelody.Enums.GetValues()

Related

How to prevent empty list errors in in clause in sql?

One common problem we have in our codebase is that people forget to check if a list is empty before using it in an in clause.
For example (in Scala with Anorm):
def exists(element: String, list: List[String]): Boolean =
SQL("select {element} in {list} as result")
.on('element -> element, 'list -> list)
.as(SqlParser.bool("result").single)
This code works perfectly well as long as list has at least one element.
If it has 0 elements, you get a syntax error, which is weird if you're used to other programming languages that would allow this empty list case.
So, my question is: what's the best way to prevent this error from happening?
Initially, we did this:
def exists(element: String, list: List[String]): Boolean =
if (list.nonEmpty) {
SQL("select {element} in {list} as result")
.on('element -> element, 'list -> list)
.as(SqlParser.bool("result").single)
} else {
false
}
This works perfectly well, and has the added advantage that it doesn't hit the database at all.
Unfortunately, we don't remember to do this every time, and it seems that 1-2 times a month we're fixing an issue related to this.
An alternate solution we came up with was to use a NonEmptyList class instead of a standard List. This class must have at least one element. This works excellent, but again, people have not been diligent with always using this class.
So I'm wondering if there's an approach I'm missing that prevent this type of error better?
It looks like you've already found a way to resolve this problem - you have an exists() function which handles an empty list cleanly. The problem is that people are writing their own exists() functions which don't do that.
You need to make sure that your function is accessible as a utility function, so that you can reuse it whenever you need to, rather than having to rewrite the function.
Your problem is an encapsulation problem: the Anorm API is like an open flame and people can burn themselves. If you rely just on people to take precautions, someone will get burnt.
The solution is to restrict the access to the Anorm API to a limited module/package/area of your code:
Anorm API will be private and accessible only from very few places, where it is going to be easy to perform the necessary controls. This part of the code will expose an API
Every other part of the code will need to go through that API, effectively using Anorm in the "safe" way

How to execute Selenium ExpectedConditions based on string variables

VERY LONG story short, I'm trying to develop a MS Excel AddIn to allow an uneducated user (open to interpretation) to create Excel-based scripts that Visual Basic (yeah not C#) can essentially parse into the individual pieces and send to the browser via Selenium commands. So far, I've had quite a bit of success. Granted there is a little bit clunkiness, but this is round 1, and I've only been working with Selenium for a week.
Up to this point I have been able to use the CallByName function to call various Selenium methods where each _argument is passed from a higher level handler originating from values in spreadsheet cells.
Dim eleActionElement as Remote.RemoteWebElement = Nothing
eleActionElement = driver.FindeElement(By.Id("PresentObjectID"))
CallByName(eleActionElement, _strAction, CallType.Method, _strActionArg)
Initially I had problems with Bys:
Dim myBy As By = CallByName(By, _strBy, CallType.Method, _strByArg)
Intelisense warns that "By" is a class type and cannot be used as an expression. Fortunately, there are individual methods for each by type, so I have been able to retrieve elements effectively through:
Public Function DriverFindElementBy(_strBy As String, _strByArg As String) As Remote.RemoteWebElement
Dim strElementBy As String = "FindElementBy" & _strBy
Dim eleWebElement As Remote.RemoteWebElement = Nothing
eleWebElement = CallByName(ThisAddIn.driver, strElementBy, CallType.Method, _strByArg)
Return eleWebElement
End Function
Unfortunately, I haven't found a way to get ExpectedConditions to work. My best guess (of many) is:
Public Function WaitOnCondition(_strCondition As String, _strBy As String, _strByArg As String)
Dim myExpectedConditionObj As ExpectedConditions
CallByName(myExpectedConditionObj, _strCondition, CallType.Method)
waitDefault.Until(CallByName(myExpectedConditionObj, _strCondition, CallType.Method))
If strTestResult.Length = 0 Then
Return "Success"
Else
Return strTestResult.ToString
End If
End Function
Intelisense warns this could result in a NullReference and it does. I can see how the object is not instantiated yet, but the same approach worked with the RemoteWebElement. If studied the Selenium docs, and both are class types; so I'm left thinking the problem has to do with various methods of the ExpectedConditions and By classes take and return different numbers and types of arguments. It may be because both classes are delegates. It may be some simple error I'm making - although, I've written and rewritten these functions a dozen times with the recurring thought, "geez, this should work." One of those times you'd think I'd have blindly gotten it right.
I'm certainly not a .Net expert and advanced techniques can be baffling at times, but I do study the solutions people provide on SO and often have to go and expand my skills; so please know that nay help will be appreciate and will not go in vain.
One tiny request, if you give a C# (or Java or Python) explanation, just let me know if you KNOW / DON'T KNOW or AREN'T SURE if it will work in VB. My biggest challenge in advanced topics is that narrow segment of stuff that doesn't crossover between C# and VB.
THANKS in advance!

EnableCors for VB.net

Does anyone know how to put the enableCors into the controller on vb.net. i am working along with a pluralsight course and tried a code translator with no luck. my attempt is below.
<EnableCors(origins: "http://localhost:53080", headers: "*", methods: "*")>
The correct syntax would be something like this:
<EnableCors("http://localhost:53080", "*","*")>
The C# example appears to use named parameters. VB.NET supports that too, however the EnableCorsAttributes has properties and contractor arguments that only differ by letter casing. This confuses the compiler as to whether you are attempting to set the named parameter or the property in the attribute. So, in this case we can just drop the named arguments all together.
In Vb.net this <EnableCors("http://localhost:53080", "*","*")> will work, but, you have to add on NuGet the Microsoft.AspNet.WebApi.Cors and Microsoft.AspNet.Cors. You need to add Imports System.Web.Http.Cors on the class.
Remove any empty line between the http://localhost:53080", "*","*")> and the declaration of the controller class.

VB can't get the right function to work with strings

Basically, I'm trying to do some string manipulation to edit directories.
I found some code to try and edit the directories, but when I use it it doesn't recognise 'right' as being a function and only recognises it as a right property, thus producing an error.
I was wondering if there's something I haven't imported or if perhaps 'right' is an obsolete function that was used in VB6 but replaced with something.
The code I have is as follows:
Dim Foo As String
Dim Bar As String
Bar = 'some form of directory input i.e. my.computer.currentdirectory
Foo = right(Bar, (Len(Bar) - InStrRev(Bar, "/")))
MsgBox(Foo)
Ideally I need either a better method of manipulating directories or a way to get the 'right' functionality working.
but when I use it it doesn't recognise 'right' as being a function and only recognises it as a right property, thus producing an error.
If you have a "right" property, you can fully qualify the function:
Foo = Microsoft.VisualBasic.Right(Bar, (Len(Bar) - InStrRev(Bar, "/")))
For details, see the docs for the Right Function.
Note that, for directory parsing, you can handle this much more cleanly via the System.IO namespace. In particular, you can construct a DirectoryInfo and get the parent folder via the Parent property.
You can also use Path.GetDirectoryName to work with strings. In your case, if you had Bar set to "C:\Some\Path\To\A\File.txt" and you call Path.GetDirectoryName(Bar), it will return "C:\Some\Path\To\A". If you call it on that, you'll get ""C:\Some\Path\To", etc.
Look up System.IO.Path - has lots of useful tools for this stuff. You'll want GetDirectoryName and GetFileName especially. They work on directories as well as filenames.
Bar = "C:\Dir1\Dir2\Dir3"
Foo = IO.Path.GetFileName(Bar) 'now = Dir3
Foo = IO.Path.GetDirectoryName(Bar) 'now = C:\Dir1\Dir2
http://msdn.microsoft.com/en-us/library/system.io.path.getfilename
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname

Write String.Join(Of T) in VB.Net

I have a simple code in C#:
Console.WriteLine(string.Join<char>("", ""));
And I can't convert it to VB.Net. Even reflector show me code in VB like:
Console.WriteLine(String.Join(Of Char)("", ""))
But it can't be compiled becouse I have an starge error:
Error 1 Expression expected.
It looks like VB.Net don't have this generic method at all.
Both project use Net Framework 4.
Why this error happened?
UPD:
I've create a custom class and copy Join(Of T) declaration to it:
Class string2
Public Shared Function Join(Of T)(ByVal separator As String, ByVal values As System.Collections.Generic.IEnumerable(Of T)) As String
Return "1"
End Function
End Class
Console.WriteLine(string2.Join(Of Char)("", ""))
It works
UPD2:
My compilation string, where you can see that I'm using Net4:
http://pastebin.com/TYgS3Ys3
Do you have a code element named String somewhere in your project?
Based on the answer you have added to this question (where you indicate that changing String to [String] appears to have solved the problem), I guessed that this may be the result of a naming collision.
I was able to duplicate the error you are seeing -- "Expression expected" -- by adding a module to my project called String and defining a (non-generic) Join method from within that module.
This may not be the specific scenario you find yourself in. But the fact that the code works for you with [String] is, to me, very compelling evidence of a simple namespace collision.
Based on the documentation for the "Expression expected" error, I'm guessing you haven't included the entire section of code where this error is appearing for you.
Do you have a lingering operator such as + or = somewhere?
(The VB.NET code you posted is indeed equivalent to the C# code above it and should compile no problem. This is why I suspect the real issue lies elsewhere.)
String.Join<T>(string, IEnumerable<T>) is useful with LINQ, for standard joins is better to use the String.Join(string, string()) overload.
In C#, "" as Char produces an empty Char (\0). Writing the same thing ("") in VB produces an empty string which is not the same as an empty char. In order to produce an empty character, you'll have to write New Char().
Your VB code therefore becomes:
Console.WriteLine(String.Join(Of Char)(New Char(), New Char()))
Edit
I just checked and it appears String.Join does not support the format you're specifying.
Instead, it goes as follows:
Join(separator As String, value As String()) As String
Your code should be as follows:
Console.WriteLine(String.Join("", New String() {""}))
String.Join(Of Char)(str1, str2) wasn't added til .net 4, it seems. That's why your custom class worked -- it had the declaration, but the String class in the framework you're actually using doesn't.
Check your settings and references to make sure you're targeting .net 4 all around -- cause that's the only thing that seems able at this point to stop the call from working.
Here the solution:
Console.WriteLine([String].Join(Of Char)("", ""))
Why this problem occurs only with generic method? I wish I know...