Function [function signature] Statement is not valid in a namespace - vb.net

I get 2 errors on the following statements when making a keygenerator for XP Repair Pro6:
TextBox2.Text = Generate(Strings.LCase(TextBox1.Text), Strings.LCase(MD5("xprp6-K0Wc0kf3Wcm5g-FEe43f")))
'MD5' is a type and cannot be used as an expression.
Public Shared Function MD5(ByVal InputStr As String) As String
Statement is not valid in a namespace.
How do I fix this?

You defined your MD5 function in a namespace, and that's not valid; functions must be in a Module or Class scope; it's modules and classes that live in namespaces, not functions.
In other words, you have this:
Namespace Some.Namespace
Class Foo
'...code...
End Class
Public Shared Function MD5(ByVal InputStr As String) As String
'...code...
End Function
End Namespace
And you need to have this:
Namespace Some.Namespace
Class Foo
'...code...
Public Shared Function MD5(ByVal InputStr As String) As String
'...code...
End Function
End Class
End Namespace

Related

BC36645 error in vb.net

I'm using Visual Studio 2015 to develop a website using web forms and Visual Basic. My problem is the error BC36645 has occured, preventing me from building the solution. It is described as "Data type(s) of the type parameter(s) in method 'Public Shared Overloads Function FromResult(Of TResult)(result As TResult) As Task(Of TResult)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error."
Which I understand the basic meaning of. However, it's stated to be in a file that I have not touched, it's autogenerated. The file is IdentityModels.vb located in the Models folder.
I got the same error in another project in the same solution, which I solved by deleting, re-creating the project and rebuilding. But this is not really a convenient way to solve the problem.
Does someone have the same problem, can explain what it is about, or even have a proper solution?
//Eva-Lotta
EDIT:
This is the contents of the file the error points to (with the error in " Return Task.FromResult(GenerateUserIdentity(manager))":
Imports System
Imports System.Threading.Tasks
Imports System.Security.Claims
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Public Class ApplicationUser
Inherits IdentityUser
Public Function GenerateUserIdentity(manager As ApplicationUserManager) As
Dim userIdentity = manager.CreateIdentity(Me, DefaultAuthenticationTypes.ApplicationCookie)
Return userIdentity
End Function
Public Function GenerateUserIdentityAsync(manager As ApplicationUserManager)
As Task(Of ClaimsIdentity)
Return Task.FromResult(GenerateUserIdentity(manager))
End Function
End Class
Public Class ApplicationDbContext
Inherits IdentityDbContext(Of ApplicationUser)
Public Sub New()
MyBase.New("DefaultConnection", throwIfV1Schema:=False)
End Sub
Public Shared Function Create As ApplicationDbContext
Return New ApplicationDbContext()
End Function
End Class
#Region "Helpers"
Public Class
Public Const XsrfKey As String = "xsrfKey"
Public Const ProviderNameKey As String = "providerName"
Public Shared Function GetProviderNameFromRequest(request As HttpRequest) As String
Return request.QueryString(ProviderNameKey)
End Function
Public Const CodeKey As String = "code"
Public Shared Function GetCodeFromRequest(request As HttpRequest) As String
Return request.QueryString(CodeKey)
End Function
Public Const UserIdKey As String = "userId"
Public Shared Function GetUserIdFromRequest(request As HttpRequest) As String
Return HttpUtility.UrlDecode(request.QueryString(UserIdKey))
End Function
Public Shared Function GetResetPasswordRedirectUrl(code As String, request As HttpRequest) As String
Dim absoluteUri = "/Account/ResetPassword?" + CodeKey + "=" + HttpUtility.UrlEncode(code)
Return New Uri(request.Url, absoluteUri).AbsoluteUri.ToString()
End Function
Public Shared Function GetUserConfirmationRedirectUrl(code As String, userId As String, request As HttpRequest) As String
Dim absoluteUri = "/Account/Confirm?" + CodeKey + "=" + HttpUtility.UrlEncode(code) + "&" + UserIdKey + "=" + HttpUtility.UrlEncode(userId)
Return New Uri(request.Url, absoluteUri).AbsoluteUri.ToString()
End Function
Private Shared Function IsLocalUrl(url As String) As Boolean
Return Not String.IsNullOrEmpty(url) AndAlso ((url(0) = "/"c AndAlso (url.Length = 1 OrElse (url(1) <> "/"c AndAlso url(1) <> "\"c))) OrElse (url.Length > 1 AndAlso url(0) = "~"c AndAlso url(1) = "/"c))
End Function
Public Shared Sub RedirectToReturnUrl(returnUrl As String, response As HttpResponse)
If Not [String].IsNullOrEmpty(returnUrl) AndAlso IsLocalUrl(returnUrl) Then
response.Redirect(returnUrl)
Else
response.Redirect("~/")
End If
End Sub
End Class
#End Region
To resolve this error You may be able to specify a data type for the type parameter or parameters instead of relying on type inference.

Shared function that infers the class type and can be returned in a list

I would like to create a shared function that returns a list of instances of the classes type. Currently this is what my code looks like
class MyClass
Implements BusinessObject
Shared Function LoadAll(Of T As {BusinessObject, New})() As IEnumerable(Of T)
Dim helper = New SQLHelper()
Return helper.LoadDataTableFromDatabase("LoadTable", LoadAllProcedureName).Rows.Cast(Of DataRow).Select(Function(s) New T().FillDataRow(Of T)(s))
End Function
End Class
class MyDerivedClass Implements MyClass
End MyClass
When I go to use it, I have to use it like this:
MyDerivedClass.LoadAll(Of MyDerivedClass)()
I would like to be able to infer the type, instead of having to use the (Of MyDerivedClass) so that my code looks like MyDerivedClass.LoadAll().
Any help or keywords that I am missing to achieve this would be greatly appreciated.
Here is an extension method which (theoretically) would work on any class you define:
Public Module Module1
<Extension()> _
Public Function LoadAll(Of T As {BusinessObject, New})(ByVal x As T) As IEnumerable(Of T)
Dim LoadAllProcedureName As String = "LoadAllProcedure"
Dim helper = New SQLHelper()
Return helper.LoadDataTableFromDatabase("LoadTable", LoadAllProcedureName).Rows.Cast(Of DataRow).Select(Function(s) New T().FillDataRow(Of T)(s))
End Function
Public Sub Main()
Dim dC As New DerivedClass()
Dim allDc As IEnumerable(Of DerivedClass) = dC.LoadAll()
'::: Somewhat shorter syntax
Dim allDC As IEnumerable(Of DerivedClass) = (New DerivedClass()).LoadAll()
End Sub
End Module
But, as others have pointed out, this doesn't really clean anything up for you. More to the point, you are going to have to type (Of DerivedClass) in whatever variable you intend on populating with your enumerated DerivedClass, no?
And from what I can tell, you cannot have Shared extension methods -- should you be thinking that is the way to go.

Can UDT's be used as method parameters in any way?

For years I've been avoiding the use of Public Type UDT's in VBA, because they're hard to pass around and I never really bothered trying to understand why.. until now - it was simply easier to just create a class module and work with actual objects instead.
But recently I gave it a shot, and once I figured they had to be passed ByRef (as an array would), things started to look like I could start using them.
So I defined a Public Type in a standard module, got this compile error:
So I moved the Public Type into a class module, made the class PublicNotCreatable, and then got this compile error:
Here's some code to reproduce the compile error.
Class module "Something":
Option Explicit
' cannot define a public user-defined type within an object module
Public Type TSomething
Foo As Integer
End Type
Public Function Create(ByRef info As TSomething) As Something
End Function
If you move the definition of TSomething to a standard module, you'll get the other compiler error, telling you that the public UDT must be defined in a public object module (i.e. a class module)... which takes you back to square one.
So if you cannot define a Public Type in a class module, why would the compiler throw a fit and even mention "public user defined types defined in public object modules" if such a thing can't legally exist?
Did it work in VB6 and the compiler message is a remnant of that version? Or is the reason somewhere in how COM works? Is it just me or the two error messages are contradicting each other? Or there's something I'm not understanding?
Obviously I'm misusing/abusing UDT's here. So what are they supposed to be used for, if not for passing a "record" to some method?
From standard module it works without any error. Following code threw no error.
Public Type TEST_TYPE
Prop1 As String
End Type
Public Function fTest(ByRef param1 As TEST_TYPE) As String
param1.Prop1 = "Hello from function"
End Function
Public Sub sTest(ByRef param1 As TEST_TYPE)
param1.Prop1 = "Hello from Sub"
End Sub
Public Sub caller()
Dim p As TEST_TYPE
'/Call Sub
Call sTest(p)
MsgBox p.Prop1
'/Call Function
Call fTest(p)
MsgBox p.Prop1
End Sub
One issue with UDT is about Forward referencing. So this will not compile, apart from that It works perfectly fine with standard modules.
Public Type TEST_TYPE
Prop1 As String
Prop2 As TEST_TYPE2 '/ Fails due to Forward referencing. TEST_TYPE2 should be declared before this UDT.
End Type
Public Type TEST_TYPE2
Prop3 As String
End Type
Edit:
However, the work around to use the UDT in class is Friend
VBA Code for Class
'/ Using UDT in VBA-Class
Private Type TEST_TYPE3
Prop3 As String
End Type
Public Sub caller()
Dim p As TEST_TYPE3
p.Prop3 = "Hello from Class"
Call testClassUDT(p)
End Sub
Friend Sub testClassUDT(p As TEST_TYPE3)
MsgBox p.Prop3
End Sub
Here's a Type being passed as a parameter to a class method, and being returned by a class method.
First the class SomeClass (doesn't need to be PublicNotCreatable)
Option Explicit
Sub test(foo As TFooBar)
Dim s As String
s = foo.foo
End Sub
Function ReturnTFoo() As TFooBar
ReturnTFoo.bar = "bar"
ReturnTFoo.foo = " bar"
End Function
And the Module:
Option Explicit
Public Type TFooBar
foo As String
bar As String
End Type
Sub test()
Dim c As SomeClass
Set c = New SomeClass
Dim t1 As TFooBar
Dim t2 As TFooBar
t1.bar = "bar"
t1.foo = "Foo"
c.test t1
t2 = c.ReturnTFoo
End Sub

force module namespace qualification

VB.net allows you to skip the qualification of a function call with the module name:
Public Module EvalDataFetcher
Public Function JoinStr(ByVal values As IEnumerable(Of String)) As String
' body
End Function
End Module
And then do:
Dim foo As String = JoinStr(myBars)
How to force the users to use the fully qualified form? ie force:
Dim foo As String = EvalDataFetcher.JoinStr(myBars)
If there is a way to force you to specify the module name, I'm not sure what it would be. However, the way you ca do it is to make it a class with shared members rather than a module. For instance:
Public Class EvalDataFetcher
Public Shared Function JoinStr(ByVal values As IEnumerable(Of String)) As String
' body
End Function
End Module
Now, when you call the JoinStr method, you will be forced to specify the class name:
Dim foo1 As String = JoinStr(myBars) ' Won't compile
Dim foo2 As String = EvalDataFetcher.JoinStr(myBars) ' Works
This behavior can be achieved with HideModuleName attribute as workaround - HideModuleNameAttribute
Wrap your module with namespace and add HideModuleName attribute to the module
Namespace Utils
<HideModuleName()>
Friend Module UtilsModule
Public Sub YourMethod(parameter As Object)
'Method code
End Sub
End Module
End Namespace
If namespace will not be added with the Imports in the file, then
you will need to use namespace name and HideModuleName attribute will hide module name from the intellisense
Utils.YourMethod(param)

Create a new instance of a type given as parameter

I've searched for an answer and found some c#-examples, but could not get this running in vb.net:
I thought of something like the following:
public function f(ByVal t as System.Type)
dim obj as t
dim a(2) as t
obj = new t
obj.someProperty = 1
a(0) = obj
obj = new t
obj.someProperty = 2
a(1) = obj
return a
End Function
I know, I can create a new instance with the Activator.Create... methods, but how to create an array of this type or just declare a new variable? (dim)
Thanks in advance!
It really depends on the type itself. If the type is a reference type and has an empty constructor (a constructor accepting zero arguments), the following code should create an insance of it:
Using Generics:
Public Function f(Of T)() As T
Dim tmp As T = GetType(T).GetConstructor(New System.Type() {}).Invoke(New Object() {})
Return tmp
End Function
Using a type parameter:
Public Function f(ByVal t As System.Type) As Object
Return t.GetConstructor(New System.Type() {}).Invoke(New Object() {})
End Function
Personaly I like this syntax much more.
Public Class Test(Of T As {New})
Public Shared Function GetInstance() As T
Return New T
End Function
End Class
Or if you want to limit the possible types:
Public Class Test(Of T As {New, MyObjectBase})
Public Shared Function GetInstance() As T
Return New T
End Function
End Class