Check if Variable is declared in a page? - asp.net

I have some web pages that include other pages, and I need to check if a variable (a string) has been declared in the page or not.
I was exploring try catch and finally, but im always getting a compiler error saying the variable doesnt exits.
syntax in my head is:
if variable(exists) then
do something
else
do nothing
end if
From what im finding is this wont even compile if the variable wasnt defined anywhere. I kinda knew that, I was just hoping to find some kind of work around. :/

The only way I know of is to use reflection...
This will not work for variables defined within subs/functions...
Friend Function VariableExists(ByVal variableName As String) As Boolean
For Each tField As FieldInfo In Me.GetType.GetFields
If tField.Name.ToLower() = variableName.ToLower() Then
Return True
End If
Next
Return False
End Function
Cose here is untested and may contain minor errors. Think of it more like pseudocode.

Instead of declaring a variable, how about adding a simple Interface that you can use in the pages that need to be processed a specific way, then you can test whether or not the page implements the Interface?
For example:
Public Interface IMySpecialInterface
End Interface
In the pages that you want special behavior for:
Public Page MySpecialPage
Implements IMySpecialInterface
End Page
In the code that processes the pages:
If TypeOf Me.Page Is IMySpecialInterface Then

What about using an interface:
Public Interface ISpecialProp
Property SpecialProp() As String
End Interface
Then you can test, if a class implements the interface or not using this code:
Dim spec = TryCast(obj, ISpecialProp)
If spec IsNot Nothing Then
Console.WriteLine(spec.SpecialProp)
End If

Related

Generic interface in usercontrol property

I have been banging my head against a wall all day and am starting to think this isnt possible so you guys are my last hope!
I have a user control which is used to create messages and then allows the message to be emailed or sent via SMS depending on what aspx page the user control is on. I have a fair amount of logic in the user control and was find I was doing alot of this:
If type="email" Then
'Logic for email
Exit Sub
End If
If type="sms" Then
'Logic for sms
Exit Sub
End If
And alot of the logic was similar so there was alot of duplication. I ended up abstracting out the similar logic for email and SMS into an Interface:
Public Interface IContactMessager(Of T)
Sub Delete(ref As String)
Function GetAll() As List(Of T)
Function GetByRef(ref As String) As T
Function MessageExists(ref As String) As Boolean
ReadOnly Property RefField() As String
Sub Save(ref As String, message As String)
Sub SendMessage(contact As String, message As String)
Sub Update(ref As String, message As String)
End Interface
I now have a sms and email manager classes that inherit from this interface. This should allow me to do something similar to the below in the user control
Dim handler As IContactMessager(Of Email)=if(type="sms",SMSHandler,EmailHandler)
Then instead of ifs I can just do handler.logic and it will run the correct logic.
Now heres my issue, and its due to the interface being generic. Ideally id like to do the following:
Public ReadOnly Property ContactMessagerHandler() As IContactMessager(Of T)
Get
Return If(MessageType.ToLower() = "email", New EmailContactMessager(), New SMSContactMessager())
End Get
End Property
However I cant have the (Of T) because obviously it has no idea what type to make this. I need to somehow dynamically set this type but I have run out of ideas.
A few things i have toyed with:
Trying to see if I can pass an the object from the calling aspx page
Making the interface a basepage instead then making the calling aspx page inherit from the base page and then trying to get the type from the usercontrols parent, but to no success
Attempting to make methods to set the type of the interface based on text passed through from the calling aspx page
None of these work. Does anyone else have any other ideas? Hopefully this makes sense, if not let me know if I can improve the question somehow

Extend Request.IsSecureConnection property

I'm actually not sure if this is possible in VB.NET, but I am trying to extend the built in property Request.IsSecureConnection.
I am using SSL offloading on a reverse proxy so all connections hitting the node would always return false for Request.IsSecureConnection. My own extension would check the HTTP_X_FORWARDED_PROTO first then fallback to the standard method if the header is not present.
Here's what I have so far, but when I set a breakpoint in here this block never gets hit. I'm sure for a very good reason.. just not sure what that reason is?
Module Extensions
<Extension()>
Public Function IsSecureConnection(Request As HttpRequestBase) As Boolean
If HttpContext.Current.Request("HTTP_X_FORWARDED_PROTO") <> "" Then
Dim https As String = HttpContext.Current.Request("HTTP_X_FORWARDED_PROTO")
If https.ToLower = "on" Then
Return True
Else
Return False
End If
Else
Return Request.IsSecureConnection '<< Not sure here how I would reference the .net framework class without looping back into this function?
End If
End Function
End Module
EDIT:
The reason I want to intercept this property rather than write my own custom method is because a library I am dependent on is referencing this property and I cannot override this.
MSDN says that:
An extension method will never be called if it has the same signature
as a method defined in the type.
https://msdn.microsoft.com/en-GB/library/bb383977.aspx
So I suspect you cannot achieve what you want using extension methods.

New class (and related methods, etc...) wont appear in intellisense

I added a new class file to the app_code directory. For some reason though I can't access it through other pages. Any ideas why?
Code:
Public Class PDFHelper
Public Sub New()
End Sub
Public Shared Function GetFormFieldNames(pdfPath As String) As Dictionary(Of String, String)
...
The following code produces error "PDFHelper is not declared. It may be inaccessible due to its protection level."
Code:
Dim formFieldMap = PDFHelper.GetFormFieldNames(pdfPath)
You probably need to import your PDFHelper class, that or use the fully qualified name to access the method:
NameSpace.Class.Method
instead of
Class.Method
I created the class from scratch and all of a sudden it worked. Very weird. Same code.
It turns out that there was something weird in the class. I recreated the class (using the same code, which is confusing) and all of a sudden saw compile errors. I addressed those and then I was able to access the class, methods, etc...

Populating Object with Data VB.net

I'm looking to populate an object then display the data to labels.
I've created a Student Class:
Public Class student
Public Dim sNum As Integer
Public sName As String
Public Sub New(ByVal sNum As Integer)
MyBase.New()
Me.sNum = sNum
End Sub
I've got a database class that I want to use to populate this.
Public Function populateStudent() As Object
Dim ObjStudent As New student(1)
ObjStudent.sName = "Bitz"
Return ObjStudent
End Function
Obviously this is just a step, eventually I'll be querying the database to populate the data, but I want to get this working first so I know I'm creating this correctly.
In my main class attached to my .aspx I want to be able to do
lblStudentName.Text = ObjStudent.sName
Am I going about this correctly, or is there a better way?
You need not have
MyBase.New()
because you don't have a explicit base class.
The return type of populateStudent() of Object does not make much sense; it should be either a list of Student if you are planning to return a collection of student after querying the db. if you are planning on populating the view from this method itself, then it should be a Sub returning nothing and not a Function.
Otherwise everything else looks okay.
EDIT:
Sounds like you need something like this.
Public Function populateStudent(Id as String) As student
Dim ObjStudent As New student(1)
ObjStudent.sName = "Bitz"
Return ObjStudent
End Function
Close. You'll want to set the .Text property on the Label control:
lblStudentName.Text = ObjStudent.sName
(which you have since edited your question to contain... it often bothers me that SO doesn't show that something was edited if the edit is very soon after the initial post)
As for a "better way" just remember that there are many, many ways to do just about anything. "Better" is very relative and depends on other factors not present in the code you have so far. As of now, you have a method which returns an instance of an object (similar to the Factory pattern, feel free to research more on that and other patterns) and you use properties on that object to populate data fields in the UI. Pretty straightforward, nothing wrong with it.
As the system grows and the problem domain becomes more complex, there will be more definition of "good design" vs. "bad design." But in just getting started, this is perfectly fine.

Is this ASP.NET Inherited Shared Function practice acceptable?

I have a bunch of different forms that I would like to create a base MustInherit class for. One function I would like them all to contain is a shared function called GetForms(). I know that you can't declare a shared function MustOverride so I did the following in my abstract class:
Public Shared Function GetForms() As List(Of OrderForm)
'to be overridden in child class'
Return Nothing
End Function
And this in my child class:
Public Overloads Shared Function GetForms() As List(Of OrderForm)
'do stuff'
End Function
Will this cause problems down the line, or is this an acceptable workaround? It has a smell to it, but it will enforce that all my forms include a shared GetForms function.
EDIT I realize that if this were possible with interfaces, I would use one, but you can't declare shared functions in interfaces and I would like to make sure that this is a SHARED function.
This has a smell because it creates a false expectation of the behavior of the code.
You mention that your reason for doing this is that 'it will enforce that all my forms include a shared GetForms function'. This is only partly true. Yes, they will all have the GetForms function, but you're not actually forcing the derived classes to implement their own version of it. If you forget to implement the function on one of them, you'll be calling the base version, and you won't get any sort of warning about it from the compiler.
That is the smell: it can't actually enforce the behavior that you want, but it creates an impression, at first glance, that it can. This will lead to headaches 6 months from now when you're adding a new Form type and you've forgotten the convention. You'll get no warning that something's wrong until you start getting bad results during testing.
If you want to enforce behavior, you have to do it using instance members; using MustOverride (abstract) functions or an interface.
You can have static (Shared) methods like that, but you can't enforce the implementation of them.
Each static method is local to it's class, you can't overload it in a child class or make it abstract (MustInherit). You have to use an instance method (non-static) to get the object oriented aspects that you want.
Yes, that does smell!
Looks like you should be using an interface instead.
Here is a vb.net article: http://www.developer.com/lang/other/article.php/939411
Why wouldn't you simply declare it as:
Public MustOverride Function GetForms() As List(Of OrderForm)?
Static methods aren't inherited, so the expectation of overriding is not something we want to encourage. In other words, I think you might be barking up the wrong tree here.

Resources