Imports System.web
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Lifetime

'##################################################
Imports System.Data.Common
'Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Runtime.Serialization.Formatters.Binary



Public MustInherit Class GenericClient
    Inherits MarshalByRefObject

    Private _trackingID As String


    Public Property TrackingID() As String
        Get
            Return _trackingID
        End Get
        Set(ByVal value As String)
            _trackingID = value
        End Set
    End Property

    Public Function Initialize(ByVal trackingid As String) As String
        If trackingid Is Nothing Then
            _trackingID = System.Guid.NewGuid.ToString
        Else
            _trackingID = trackingid
        End If
        Return _trackingID
    End Function

    Public Function Destroy(ByVal trackingid As String) As Boolean
        HttpContext.Current.Application.Remove(_trackingID)
    End Function

    Protected ReadOnly Property Session(ByVal key As String) As Object
        Get
            Try
                'Dim list As Dictionary(Of String, Object) = DirectCast(HttpContext.Current.Application(_trackingID), Dictionary(Of String, Object))

                If Not (HttpContext.Current Is Nothing) Then
                    If Not (HttpContext.Current.Session Is Nothing) Then
                        Dim x As New Object
                        x = HttpContext.Current.Session(key)

                        If Not (x Is Nothing) Then
                            Dim list As Dictionary(Of String, Object) = CType(x, Dictionary(Of String, Object))
                            '#######################
                            'MANAGER KEY HAS A VALUE
                            '#######################
                            Return list
                        Else
                            Return Nothing
                        End If
                    Else
                        Return Nothing
                    End If
                Else
                    Return Nothing
                End If





            Catch ex As Exception
                Throw ex
            End Try
        End Get
    End Property

    Protected Sub SetSession(ByVal key As String, ByVal value As Object)
        Try

            'Dim list As Dictionary(Of String, Object) = DirectCast(HttpContext.Current.Application(_trackingID), Dictionary(Of String, Object))

            HttpContext.Current.Session(key) = value


            'If Not list Is Nothing Then
            '  '#########
            '  'has value
            '  '#########
            '  If list.ContainsKey(key) Then
            '    list(key) = value
            '  Else
            '    list.Add(key, value)
            '  End If
            '  HttpContext.Current.Application(_trackingID) = list
            'Else
            '  '###################################################################################################
            '  'no manager exists yet create on and add "value" to it in the dictionary, then set in app object.
            '  '###################################################################################################
            '  list = New Dictionary(Of String, Object)
            '  list.Add(key, value)
            '  HttpContext.Current.Application(_trackingID) = list
            'End If



        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Protected MustOverride Sub PopulateLocalVariables(ByVal trackingID As String)

    Public Overrides Function InitializeLifetimeService() As Object

        Dim lease As ILease = CType(MyBase.InitializeLifetimeService(), ILease)
        If lease.CurrentState = LeaseState.Initial Then
            lease.InitialLeaseTime = TimeSpan.FromMinutes(1)
            lease.SponsorshipTimeout = TimeSpan.FromMinutes(2)
            lease.RenewOnCallTime = TimeSpan.FromSeconds(2)
        End If
        Return lease

    End Function



    Private Sub PersistSession(ByVal ID As String, ByVal ManagerKey As String, ByVal SessionValue As Object)
        '    Dim objstream As New IO.MemoryStream()
        '    Dim formatter As New BinaryFormatter
        '    Dim CMD As DbCommand
        '    Dim DB As Database

        '    Try
        '        DB = DatabaseFactory.CreateDatabase("Charter.Website.WS.CommerceEngineConnectionString")
        '        CMD = DB.GetStoredProcCommand("SESSIONSTATE.SET_SESSION")

        '        formatter.Serialize(objstream, SessionValue)

        '        Dim BinarySession(CType(objstream.Length, Integer)) As Byte
        '        objstream.Position = 0
        '        objstream.Read(BinarySession, 0, CType(objstream.Length, Integer))

        '        DB.AddInParameter(CMD, "@TRACKINGID", DbType.String, ID)
        '        DB.AddInParameter(CMD, "@MANAGERKEY", DbType.String, ManagerKey)
        '        DB.AddInParameter(CMD, "@SESSIONOBJECT", DbType.Binary, BinarySession)

        '        Dim retCode As Integer
        '        retCode = DB.ExecuteNonQuery(CMD)

        '    Catch ex As Exception
        '        Throw ex
        '    Finally
        '        If Not (objstream Is Nothing) Then
        '            objstream.Close()
        '            objstream = Nothing
        '        End If

        '        If Not CMD Is Nothing Then
        '            CMD.Dispose()
        '        End If

        '    End Try
    End Sub

    Private Function RetriveSession(ByVal ID As String, ByVal ManagerKey As String) As Object
        '    Dim CMD As Data.Common.DbCommand
        '    Dim DB As Database
        '    Dim ds As DataSet
        '    Dim objstream As IO.MemoryStream
        '    Dim data() As Byte
        '    Try
        '        DB = DatabaseFactory.CreateDatabase("Charter.Website.WS.CommerceEngineConnectionString")
        '        CMD = DB.GetStoredProcCommand("SESSIONSTATE.GET_SESSION")
        '        DB.AddInParameter(CMD, "@TRACKINGID", DbType.String, ID)
        '        DB.AddInParameter(CMD, "@MANAGERKEY", DbType.String, ManagerKey)
        '        ds = DB.ExecuteDataSet(CMD)

        '        If ds.Tables(0).Rows.Count > 0 Then
        '            data = CType(ds.Tables(0).Rows(0)("SESSIONOBJECT"), Byte())
        '            Dim formatter As New BinaryFormatter
        '            objstream = New IO.MemoryStream(data.Length)


        '            objstream.Position = 0
        '            objstream.Write(data, 0, data.Length)
        '            objstream.Seek(0, IO.SeekOrigin.Begin)


        '            Return formatter.Deserialize(objstream)
        '        Else
        '            Return Nothing
        '        End If


        '    Catch ex As Exception
        '        Throw ex
        '        Return Nothing
        '    Finally
        '        If Not (objstream Is Nothing) Then
        '            objstream.Close()
        '            objstream = Nothing
        '        End If

        '        If Not CMD Is Nothing Then
        '            CMD.Dispose()
        '        End If
        '    End Try
        Return Nothing
    End Function

    Private Sub RemoveSession(ByVal ID As String)
        'Dim CMD As Data.Common.DbCommand
        'Dim DB As Database
        'Dim ds As DataSet
        'Try
        '    DB = DatabaseFactory.CreateDatabase("Charter.Website.WS.CommerceEngineConnectionString")
        '    CMD = DB.GetStoredProcCommand("SESSIONSTATE.DELETE_SESSION")
        '    DB.AddInParameter(CMD, "@TRACKINGID", DbType.String, ID)
        '    ds = DB.ExecuteDataSet(CMD)

        'Catch ex As Exception
        '    Throw ex
        'Finally
        '    If Not CMD Is Nothing Then
        '        CMD.Dispose()
        '    End If
        'End Try

    End Sub

    Public Function GenerateContentCacheExpirationDate() As DateTime
        Try
            '#############################################################################
            'MODIFICATION   MAR 6, 2009     ROD COPELAND
            '#############################################################################
            'NORMAL OPERATION: DUMP/EXPIRE CACHE AT 3AM TODAY UNLESS IT'S AFTER 3AM, THEN JUST 
            'DUMP/EXPIRE CACHE 3AM TOMORROW MORNING.
            '#############################################################################
            'THE CONTENT CACHE IS ABLE TO BE DUMPED BASED ON AN ADMIN USER MANUALLY 
            'CLICKING THE RESET CACHE BUTTON IN THE ADMIN UI ON THE APP TIER.  THERE IS 
            'ANOTHER NOT SO WE'LL KNOWN FEATURE OF THE SITE THAT DUMPS THE CACHE 
            'AUTOMATICALLY AT 3AM BY SETTING THE CONTENT EXPIRATION DATE WHEN ADDING TO THE 
            'HTTP CACHE COLLECTION. THE EXPIRATION DATE OF THE CONTENT IS INTENDED TO BE A 
            'CONFIGURABLE VALUE TO BE CHANGED AT RUNTIME FOR NEW ENTRIES TO THE CACHE ONLY.  
            'THIS VALUE SHOULD EXIST IN THE ADMIN.WEBCONFIG TABLE WITH A KEY OF 
            '"NUM_OF_DAYS_TO_CACHE" AND "NUM_OF_HOURS_TO_CACHE".  DETAILS OF THE USE OF 
            'THESE VALUES CAN BE FOUND IN THE 
            'commonEntities.Library.dll\virtualManagers\GenericClient.vb\GenerateContentCacheExpirationDate() 
            'method  ANY EXCEPTION IN THE FUNCTION CALL TO GET THE 
            'EXPIRATION DATE WILL SHOULD RESULT IN A RETURNED DATE OF 2 DAYS FROM NOW AT 3AM.
            '#############################################################################
            Dim expiredate As DateTime
            Dim lNumOfDaysToCache As Integer = 2
            Dim lNumOfHoursToCache As Integer = 3

            '##########################################################
            'GET THE DAYS TO CACH VALUE FROM DB TABLE ADMIN.WEBCONFIG
            '##########################################################
            If HttpContext.Current.Application("NUM_OF_DAYS_TO_CACHE") Is Nothing Then
                lNumOfDaysToCache = 2
            Else
                Try
                    lNumOfDaysToCache = CType(HttpContext.Current.Application("NUM_OF_DAYS_TO_CACHE"), Integer)
                Catch ex As Exception
                    lNumOfDaysToCache = 2
                End Try
            End If

            '##########################################################
            'GET THE HOURS TO CACH VALUE FROM DB TABLE ADMIN.WEBCONFIG
            '##########################################################
            If HttpContext.Current.Application("NUM_OF_HOURS_TO_CACHE") Is Nothing Then
                lNumOfHoursToCache = 3
            Else
                Try
                    lNumOfHoursToCache = CType(HttpContext.Current.Application("NUM_OF_HOURS_TO_CACHE"), Integer)
                Catch ex As Exception
                    lNumOfHoursToCache = 3
                End Try
            End If

            If Now() > Date.Today.AddHours(3) Then
                expiredate = Date.Today.AddDays(lNumOfDaysToCache).AddHours(lNumOfHoursToCache)
            Else
                expiredate = Date.Today.AddHours(lNumOfHoursToCache)
            End If
            '#####################################################################
            '#####################################################################

            Return expiredate

        Catch ex As Exception
            '#####################################################
            'MANUALLY DEFAULT THIS VALUE TO 2 DAYS AWAY AT 3AM.
            '#####################################################
            Return Date.Today.AddDays(2).AddHours(3)

        End Try

    End Function


End Class
