Solved

Extend a sub from another class

Posted on 2014-03-01
10
337 Views
Last Modified: 2014-03-12
I have this setup (stripped example):

class: manager.vb
private shared function save(byval object as myobject) as boolean
  'saving of object
end function

webpage codebehind: default.aspx.vb
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
   manager.save(myobject)
End Sub

So this works just fine, the user clicks a button and the object is saved through the save function of manager.vb class.

Now I would like to create a second class, e.g. log.vb with for example this function:
class: log.vb
private shared function LogEvent() as boolean
  'add event to the log
end function

I want to call this log function without having to write additional code in default.aspx.vb
So basicly something like this:

private shared function LogEvent() as boolean
   if manager.save is called then
  'add event to the log
   end if
end function

How can I accomplish this?

ps. I know I could call LogEvent from the save function in manager.vb, but I would like to keep it seperate, and in case of log.vb being removed, not breaking manager.vb

Thank you!
0
Comment
Question by:Onthrax
  • 6
  • 3
10 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39897983
There are a few ways to achieve this. You can pass the logger class reference to the manager save method. Then in save method, check to see if the logger has been supplied and if it is then use the LogEvent method. The other approach is to declare a global logger and keep it in some shared place like session or application object and call it from different parts of the application.
0
 
LVL 13

Author Comment

by:Onthrax
ID: 39898389
Hi,

Thank you for your answer.

However neither is a perfect solution. Your first solution would require a code adjustment in all places the manager is called from, if the logger class ever was removed.
In this case it would be easier just to call the logger from the manager class, so I would only have to remove 1 line if it ever is removed.

In your second solution I would still have to call the logger 'manually' instead of automatically being triggered.

I have also looked into events, but as far as my research goes it seems I cannot handle an event from one class in another class file...

Perhaps what I want is simply not possible.
0
 
LVL 18

Expert Comment

by:Dennis Aries
ID: 39898937
The only way to do what you desire requires adding code to the base class.
Based on your description that the logger-class might be removed in the future, you might consider adding an event to your manager-class and hook into that.

That way you can add additional functionality to your save-code without altering that class later on.
0
 
LVL 13

Author Comment

by:Onthrax
ID: 39899124
Hi,

Could you give a short example code of what you are proposing. I have been experimenting with events but have been unsuccesful thus far.

Thank you!
0
 
LVL 13

Author Comment

by:Onthrax
ID: 39905721
Dennis, could you please provide an example, I'd like to continue this route if it is possible...

Thank you.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 18

Accepted Solution

by:
Dennis Aries earned 500 total points
ID: 39906350
Very simple sample:

managerclass
Imports System.ComponentModel

Public Class Manager

    Private Const SAVEDEVENTNAME As String = "Manager_SavedEvent"
#Region "EventList"
    Private _events As EventHandlerList = Nothing

    Protected ReadOnly Property Events() As EventHandlerList
        Get
            If _events Is Nothing Then
                _events = New EventHandlerList()
            End If
            Return _events
        End Get
    End Property
#End Region
#Region "Events"
    Public Custom Event Manager_Saved As EventHandler
        AddHandler(ByVal value As EventHandler)
            Me.Events.AddHandler(SAVEDEVENTNAME, value)
        End AddHandler

        RemoveHandler(ByVal value As EventHandler)
            Me.Events.RemoveHandler(SAVEDEVENTNAME, value)
        End RemoveHandler

        RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim handler = CType(Me.Events(SAVEDEVENTNAME), EventHandler)
            If (handler IsNot Nothing) Then
                handler.Invoke(sender, e)
            End If
        End RaiseEvent
    End Event
#End Region

    Public Sub Save()
        ' Add your code here

        RaiseEvent Manager_Saved(Me, New EventArgs())
    End Sub

End Class

Open in new window


And a form (for demonstrationpurpose):
Public Class Form1
    Dim WithEvents manager As Manager

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        manager = New Manager()
        manager.Save()
    End Sub

    Private Sub manager_Manager_Saved(ByVal sender As Object, ByVal e As System.EventArgs) Handles manager.Manager_Saved
        ' Add your logging-code here
        MessageBox.Show("Hello World!")
    End Sub
End Class

Open in new window

0
 
LVL 13

Author Comment

by:Onthrax
ID: 39914935
Thank you for the example, which works fine.

However I am using a shared class for the manager class and after some thought a shared event is not such a good idea as this would trigger the handler for all users on that page and thus multiple logging code firing. I could either rebuilt the manager class to make it not shared or take a different route.

Thank you for your time. I learned a great deal about events and will certainly apply them when possible.
0
 
LVL 13

Author Comment

by:Onthrax
ID: 39914969
Thank you for the example, which works fine.

However I am using a shared class for the manager class and after some thought a shared event is not such a good idea as this would trigger the handler for all users on that page and thus multiple logging code firing. I could either rebuilt the manager class to make it not shared or take a different route.

Thank you for your time. I learned a great deal about events and will certainly apply them when possible.
0
 
LVL 18

Expert Comment

by:Dennis Aries
ID: 39914972
Glad to be of help

Dennis
0
 
LVL 13

Author Closing Comment

by:Onthrax
ID: 39922784
Although I can't use this as I am using a shared class, this does answer the original question and will be usable in other situations, so therefore accepted as answer. Thanks again.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now