Posts tagged VB

ASP.NET MVC Full URL From A Controller

In working with ASP.NET MVC, I came across the need to send an email with the URL of a document that is to be approved.  There are helper functions accessible from the View to build an ActionLink or get the URL of an action, but I had problems finding how to build this URL from within a controller.  Here is the simple code that I finally pieced together to do what I wanted:

Dim link As String = HttpContext.Request.Url.Scheme + _
    "://" + HttpContext.Request.Url.Authority + _
    Url.Action("ActionName", "ControllerName", New With {.id = idOfDocument})

HttpContext.Request.Url.Scheme returns “http” or “https”, which ever one you’re using.
HttpContext.Request.Url.Authority returns the Base Url of your application.
And, the Url.Action method creates the Url to the Controller, Action, and ID of the document that is being sent out for approval.

Understanding Polymorphism

Introduction

This article will explain what polymorphism is and how it can help you design and reuse code in Object-Oriented Programming.  You’ll learn what polymorphism is and how to use it.  In the following examples, I’ll be using Visual Basic .NET, but any language that supports Object-Oriented Programming should be able to use these same techniques.

If you have not already read the articles on Understanding Objects and Understanding Inheritance, please check them out as some of the terms and other information explained there will be used in this article.

What is Polymorphism?

According to dictionary.com, the definition of Polymorphism is as follows:

3. Biology The occurrence of different forms, stages, or types in individual organisms or in organisms of the same species, independent of sexual variations.

So, how does this relate to programming?  We’ll develop Objects that have different forms of the same “species”.  The great thing about Polymorphism is that when you are building your program, you assume you are working with the “species” Object, but you actually use an individual “organism” Object.  This allows the “organism” Objects to be exchanged in the code for one another.

In other words, say we have a Parent Class called Animal and two Child Classes that Inherit from Animal called Cat and Dog.  The Cat and Dog are both Animals, so they will inherit all the properties and methods that an Animal has.  If we wanted to store an array of Cats or Dogs, we could just declare the array to be of type Animal and then we’d be able to store either Cats or Dogs within the array.  That is Polymorphism.

Parent Classes and Interfaces

Both Parent Classes and Interfaces can be used to setup an Object as the “species” level.  Parent Classes have been explained in Understanding Inheritance.

What is an Interface?

An Object’s Interface is how you communicate or interact with that Object.  Interfaces in programming terms are similar to a Class Object, but an Interface does not implement the properties or methods it declares, it simply declares them.

Why is this useful?  Interfaces force the Class Objects that implement the Interface to have all of the properties and methods of the Interface.  So, the following IAnimal Interface could be implemented by Cat and Dog to force them to implement the properties, Height and Weight, along with the methods, Eat and Drink.

Public Interface IAnimal

    Property Height() As Integer
    Property Weight() As Integer

    Function Eat(footType As String) As Boolean
    Function Drink(drinkType As String) As Boolean

End Interface

Interfaces can be used with Parent or Child classes and multiple Interfaces can be used by one Class.  Also, in some cases, you may want to use an Interface in place of a Parent Class, forcing all properties and methods to be fully implemented in each class.  Another thing to keep in mind is that a Parent Class that implements the IAnimal Interface does not have to fully implement all properties and methods.  Instead, the Parent Class could implement those common properties or methods that will not change no matter the Child Class, and leave the others to be implemented by the Child Class.  In VB.NET, you can use the MustOverride keyword on the function declaration.  This will make the Parent Class an Abstract class.

Public MustInherit Class Animal Implements IAnimal

    'Data Members.
    Private _height As Integer
    Private _weight As Integer

    Public Property Height() As Integer Implements IAnimal.Height
        Get
            return _height
        End Get
        Set(ByVal Value As Integer)
            _height = value
        End Set
    End Property

    Public Property Weight() As Integer Implements IAnimal.Weight
        Get
            Return _weight
        End Get
        Set(ByVal Value As Integer)
            _weight = Value
        End Set
    End Property

    'Abstract Functions.
    Public MustOverride Function Eat(foodType As String) As Boolean Implements IAnimal.Eat
    Public MustOverride Function Drink(drinkType As String) As Boolean Implements IAnimal.Drink

End Class

 Now, things are looking pretty good.  We can force are Classes to implement certain properties and methods, but there is still one downside.  Our methods are passing in a String value for foodType and drinkType.  What if we wanted to use a different data type, such as our own Object that holds other properties for foodType?  We don’t want to have to modify the Interface or Parent Class each time this may change.  What we want to do is make the Class or Interface Generic.

How do I make my Interface or Class Generic?

Making a Class or Interface Generic will make your code more reusable.  When you make a Class or Interface Generic, you don’t have to know what type of data you will be using with the Object until you declare or create an instance of the Object.  So, various programs could use the same Class Object, but passing in different data types to work with when instantiating the Object. 

Public Interface IAnimal(Of T)

    Property Height() As Integer
    Property Weight() As Integer

    Function Eat(foodType As T) As Boolean
    Function Drink(drinkType As T) As Boolean

End Interface

T is a place holder for the type of data we will declare later on.  Notice in the declaration of the Interface and both methods, Eat and Drink, T is used.  Now, when we create a Cat or Dog using the IAnimal Interface, we can determine what type of data will be used for foodType and drinkType.

Public Class Cat Implements IAnimal(Of String)

This would declare a Cat to use a String data type to store the foodType and drinkType.

Public Class Dog Implements IAnimal(Of Integer)

And this one would declare a Dog to use an Integer data type to store the foodType and drinkType.

We could also define our own complex Class Object as the data type.

Advantages of using Polymorphism, Interfaces, and Generic Objects

  • Polymorphism allows you to use similar types of data together.  It also can be used to improve system maintenance, reuse code, and easily setup testing Objects that mimic communications with databases and other resources.
  • Interfaces force the implementation of properties and methods on Objects that implement the Interface.
  • Generic Objects allow more reusable code when building Class Objects and Interfaces.

Understanding Inheritance

Before we get started on the topic of Inheritance, please check out Understanding Objects.  Now, onward…

According to dictionary.com, one definition of inheritance is:

2. the genetic characters transmitted from parent to offspring, taken collectively.

This definition also fits with Object Oriented Programming.  Remember, that our Objects mimic those found in real-life and just like in real-life, Objects can have Parent Objects or Children Objects.  Inheritance is the process of obtaining the properties and methods from another Object.  The Child Object inherits these properties and methods from the Parent Object.

Using Inheritance, we can extend the functionality of a Class Object without having to modify that Object.  This helps you make your own code more reusable as well as gives you the ability to improve other people’s Class Objects.

Access Modifiers

I had talked breifly about Access Modifiers in Understanding Objects.  When building Parent and Child Class Objects, you will most likely be using all three: Private, Public and Protected.

A Child Class that inherits from a Parent does not gain access to all of the Parent’s properties and methods.  The Parent uses Encapsulation and Data Hiding to protect it’s Private properties and methods.  The Child Class can only access those properties and methods that are Protected or make up the Public Interface for the Parent Class.

The Protected access modifier acts similar to Private, keeping the properties and methods hidden from outside use, but it will allow Child Class Objects access to them.

Below is an example of a Parent Class:

Public Class MyParent

    Private _hiddenVariable As String
    Private _errors As String

    Public Sub New()

        _hiddenVariable = “”
        _errors = “”

    End Sub

    Protected Sub AddError(error As String)

        _errors += error + VbCrLf

    End Sub

    Public Function GetErrors()

        Return _errors

    End Function

End Class

Below is an example of a Child Class:

Public Class MyChild
    Inherits MyParent

    Public Sub New()

        MyBase.New()

    End Sub

    Public Function MyNewFunction()

        Return "It Worked!"

    End Function

End Class

In the above examples, the Parent Class has a couple Private string variables.  The subroutine, AddError, would normally be a Private function, but since we want the Child Class to have access to this function, we must change it to Protected.

There are two methods on MyParent’s Public Interface: New() and GetErrors().

The MyChild Class uses Inheritance to extend MyParent’s functionality.  In VB, the Inherits keyword is used to tell which class is the Parent.  Within MyChild, all of the functions on the Public Interface for MyParent as well as the Protected function, AddError, can be accessed.

There are three methods on MyChild’s Public Interface: New(), GetErrors(), and MyNewFunction().

Overriding Methods

When developing a Child Class, you may find that you need to change the way that one of the Parent Class’ methods work.  To do this, you must override the method in the Child Class.  When an instance of the Child Class is used, the overridden function would be used within the Child Class instead of the Parent Class.

Some languages allow you to override the function by simply declaring the same function in the Child as in the Parent.  In VB, you would use the Overrides keyword to declare you are overriding a function.

Protected Overrides Sub AddError(error As String)

    _errors += "MyChild:" + error + VbCrLf

End Sub

This subroutine would be placed in the MyChild Class and would override the AddError subroutine found in the MyParent Class.  Errors that occur in the Child Class would show “MyChild:” in front of them.

Also, the Child method that overrides the Parent, can also call the Parent’s method.  This allows you the power of performing some small change without having to re-implement the entire method in the Child Class.  In VB, you would use the MyBase keyword to signal you are looking for the Parent Class version of the method.

MyBase.AddError("my error")

Abstraction

Abstraction is the process of declaring a Class, property or method without giving the details on the implementation of that element.  A Parent Class can use Abstraction to declare that a function must be present in any Child Class of that Parent.  The Child Class can then either define what the method does or declare the method as Abstract also.

If a Class is Abstract, then an instance of that Class can not be created.  You must instead, access the Class through one of it’s children. 

In VB, you can force a Class to be Abstract by using the MustInherit keyword.

Public MustInherit Class MyParent

Below is an example of the MyParent Class if we wanted to make the AddError function Abstract. 

Public Class MyParent

    Private _hiddenVariable As String
    Private _errors As String

    Public Sub New()

        _hiddenVariable = “”
        _errors = “”

    End Sub

    Protected MustOverride Sub AddError(error As String)

    Public Function GetErrors()

        Return _errors

    End Function

End Class

Advantages of Inheritance, Abstraction, and Overriding Methods

  • Inheritance helps you extend the functionality of your own classes or other people’s classes.
  • Abstraction can be useful if you need multiple Classes that have similar properties and methods.  You can create an Abstract Parent Class with the common properties and methods and have the Children Classes hold the unique properties and methods.
  • Overriding Methods allows you to change the functionality of a Parent Class without modifying the Parent’s code.