Solved

Extend a sub from another class

Posted on 2014-03-01
10
339 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Export import database 4 43
Turn on intranet settings 1 41
SQL Login 17 40
Importing CSV file encoded in UTF-8 in SQL SERVER 2008 using BULK INSERT 5 31
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

895 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

19 Experts available now in Live!

Get 1:1 Help Now