Thursday, July 7, 2011

Report Viewer - Hiding Export Format

Sometime, we will need to hide the export format (excel or pdf) from particular user group. There is a great article explaining how we can do that, which you can find here. Many thanks to the author Ahmed Elbaz for providing such useful solution.

The code snippet in that article is written in C#, so for VB.Net developer like me, I will need to convert the code to VB.Net in my project.

Below are the code I converted to VB.Net using online code conversion tool. Hope it helps!


Public NotInheritable Class ReportViewerExtensions
    Private Sub New()
    End Sub


    Public Shared Sub SetExportFormatVisibility(ByVal viewer As ReportViewer, ByVal format As ReportViewerExportFormat, ByVal isVisible As Boolean)


        Dim formatName As String = format.ToString()


        Const Flags As System.Reflection.BindingFlags = System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.[Public] Or System.Reflection.BindingFlags.Instance
        Dim m_previewService As System.Reflection.FieldInfo = viewer.LocalReport.[GetType]().GetField("m_previewService", Flags)


        Dim ListRenderingExtensions As System.Reflection.MethodInfo = m_previewService.FieldType.GetMethod("ListRenderingExtensions", Flags)
        Dim previewServiceInstance As Object = m_previewService.GetValue(viewer.LocalReport)


        Dim extensions As IList = DirectCast(ListRenderingExtensions.Invoke(previewServiceInstance, Nothing), IList)
        Dim name As System.Reflection.PropertyInfo = extensions(0).[GetType]().GetProperty("Name", Flags)


        'object extension = null;
        For Each ext As Object In extensions


            If (String.Compare(name.GetValue(ext, Nothing).ToString(), formatName, True) = 0) Then
                Dim m_isVisible As System.Reflection.FieldInfo = ext.[GetType]().GetField("m_isVisible", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance)


                Dim m_isExposedExternally As System.Reflection.FieldInfo = ext.[GetType]().GetField("m_isExposedExternally", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance)
                m_isVisible.SetValue(ext, isVisible)
                m_isExposedExternally.SetValue(ext, isVisible)


                Exit For


            End If
        Next
    End Sub


End Class


Public Enum ReportViewerExportFormat
    Excel
    PDF
End Enum

No comments:

Post a Comment