Imports System.Xml
Imports System.Xml.Serialization
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.Enumerations
Imports CharterDotCom.CommonEntities.Library.EntityMemberServices
Imports CharterDotCom.CommonEntities.Library.EntityEBSServices
Imports CharterDotCom.CommonEntities.Library.EntitySupport
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports CharterDotCom.CommonEntities.Library.EntityWebConfig
Imports CharterDotCom.CommonEntities.Library.EntityG2BServices
Imports System.Configuration
Imports System.Runtime.Remoting
Imports CharterDotCom.WebSite.Library
Imports System.Web
Imports System.IO

Public Class ContentBinaryFileHandler
    Implements IHttpHandler

    Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

        Dim request As HttpRequest = context.Request
        Dim response As HttpResponse = context.Response

        Dim BinaryFileName As String
        Dim BinaryFileExtension As String
        Dim objContent As ContentSchema.BINARYFILE
        Try
            Dim strTemp As String
            Dim strChar(1) As Char
            Dim strSplit() As String
            strTemp = request.RawUrl
            strChar(0) = CChar("/")
            Select Case True
                Case (InStr(strTemp, ".ccswf") > 0)
                    strSplit = strTemp.Split(strChar, StringSplitOptions.RemoveEmptyEntries)
                    BinaryFileName = Replace(strSplit(UBound(strSplit)), ".ccswf", "")
                    BinaryFileExtension = ".swf"
                    response.ContentType = "application/x-shockwave-flash"
                Case (InStr(strTemp, ".ccxml") > 0)
                    strSplit = strTemp.Split(strChar, StringSplitOptions.RemoveEmptyEntries)
                    BinaryFileName = Replace(strSplit(UBound(strSplit)), ".ccxml", "")
                    BinaryFileExtension = ".xml"
                    response.ContentType = "text/xml"
                    'Case (InStr(strTemp, ".ccflv") > 0)
                    '    strSplit = strTemp.Split(strChar, StringSplitOptions.RemoveEmptyEntries)
                    '    BinaryFileName = Replace(strSplit(UBound(strSplit)), ".ccflv", "")
                    '    BinaryFileExtension = ".flv"
                    '    response.ContentType = "flv-application/octet-stream"
                Case Else
                    Exit Sub
            End Select

            If context.Cache("*CMSBinaryFiles*" & BinaryFileName & BinaryFileExtension) Is Nothing Then
                Try
                    objContent = GetBinaryFile(BinaryFileName, BinaryFileExtension)
                Catch ex As Exception

                End 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 lManager As New BLContentManager
                Dim expiredate As DateTime = lManager.GenerateContentCacheExpirationDate()
                '#############################################################################




                '###########################################################################
                'ROD COPELAND   FEB 9, 2009     CREATIVE LIFT REDESIGN PROJECT
                '###########################################################################
                'WHEN ADDING ITEMS TO CACHE, A PRIORITY IS ASSIGNED TO THE ITEM. IN TIMES 
                'OF LOW RESOURCES ON THE BOX, THE .NET FRAMEWORK STARTS REMOVING ITEMS 
                'WITH LOWEST PRIORITY FIRST TO KEEP THE APPLICATION ALIVE. THE CONCERN IS 
                'IF THE APP IS NOT CACHING, IT'S LIKELY MAKING A REMOTING CALL TO GET THE 
                'DATA.  TO MANY REMOTING CALLS AT THE SAME TIME WILL CAUSE A REMOTING CALL 
                'BOTTLE NECK, AT THAT POINT THE APPLICATION WILL START QUEUEING THE CALLS. 
                'ALL THE QUEUED REMOTING CALLS WILL EVENTUALLY RUN UP THE CPU IF NOT 
                'CLEARED.  IF NOT CLEARED THE BOX WILL STOP RESPONDING.
                '###########################################################################
                'THE FOLLOWING IS THE ORDER OF PRIORITY AT THE TIME THIS WAS WRITTEN:
                'CONTENT RECORDS,       NOT REMOVABLE = 6                                           CONTENTMANAGER.GetContent()
                'CCOM IMAGE FILES,      NOT REMOVABLE = 6                                           CONTENTIMAGEHANDLER.ProcessRequest()
                'XBIN PDF FILES,        THIS ITEM IS NOT CACHED AT THIS TIME DUE TO SIZE REASONS.
                'SUPPORT ARTICLES,      ABOVE NORMAL = 4                                            SITEMANAGER.GETDOCUMENT()
                'CCSWF FLASH FILES,     BELOW NORMAL = 3                                                  CONTENTBINARYFILEHANDLER.ProcessRequest()
                'CCXML FILES,           BELOW NORMAL = 2                                            CONTENTBINARYFILEHANDLER.ProcessRequest()
                'CCFLV FILES,           LOW = 1                                                     CONTENTBINARYFILEHANDLER.ProcessRequest()
                '############################################################################
                If Not (objContent.m_BinaryFileData Is Nothing) Then
                    If Not (BinaryFileExtension Is Nothing) Then
                        Select Case BinaryFileExtension.ToLower()
                            Case ".swf"
                                context.Cache.Insert("*CMSBinaryFiles*" & BinaryFileName & BinaryFileExtension, objContent.m_BinaryFileData, Nothing, expiredate, Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.BelowNormal, Nothing)
                            Case ".xml"
                                context.Cache.Insert("*CMSBinaryFiles*" & BinaryFileName & BinaryFileExtension, objContent.m_BinaryFileData, Nothing, expiredate, Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.BelowNormal, Nothing)
                            Case ".flv"
                                context.Cache.Insert("*CMSBinaryFiles*" & BinaryFileName & BinaryFileExtension, objContent.m_BinaryFileData, Nothing, expiredate, Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.Low, Nothing)
                            Case Else
                                context.Cache.Insert("*CMSBinaryFiles*" & BinaryFileName & BinaryFileExtension, objContent.m_BinaryFileData, Nothing, expiredate, Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.Low, Nothing)
                        End Select
                    End If
                Else
                    '###################################################################
                    'IN THE EVENT THE BINARY COMES BACK NOT FOUND, 
                    'WE MAKE A CACHE ENTRY WITH BLANK VALUE TO AVIOD REMOTING CALLS FOR 
                    'BAD FILE NAMES.
                    '###################################################################
                    Dim emptyBinary As Byte() = New Byte(1) {}
                    context.Cache.Insert("*CMSBinaryFiles*" & BinaryFileName & BinaryFileExtension, emptyBinary, Nothing, expiredate, Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.NotRemovable, Nothing)
                End If


            Else
                objContent.m_BinaryFileData = CType(context.Cache("*CMSBinaryFiles*" & BinaryFileName & BinaryFileExtension), Byte())
            End If

            If Not objContent.m_BinaryFileData Is Nothing Then
                response.BinaryWrite(objContent.m_BinaryFileData)
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Function GetBinaryFile(ByVal BinaryFileName As String, ByVal BinaryFileExtension As String) As ContentSchema.BINARYFILE
        Try
            Dim cmProxy As BLContentManager = New BLContentManager
            'Dim trackingID As String
            Common.RegisterChannels()
            'trackingID = cmProxy.Initialize(Nothing)
            Return cmProxy.GetBinaryFile(Nothing, BinaryFileName, BinaryFileExtension)

        Catch ex As Exception
            Throw ex
        End Try
    End Function

End Class

