Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

AttachmentSelector Web Control - ASP.NET

RSS
Modified on Tue, Sep 15, 2009, 11:42 AM by Administrator Categorized as ASP·NET Web Forms, Class Library
This page is part of the Class Library Pages collection.
Click the icon to see the index.

Table of Contents [Hide/Show]


   Features
   Sample Implementation
      ASPX Markup
      Code-Behind
         VB.NET
         C#
   Source Code
      ASPX Markup
      Code-Behind
         VB.NET
         C#

{outline||<1> - |

.<1> - }

Features

The AttachmentSelector control, shown below, provides the following features.

Screen Shot of the AttachmentSelector Control

Screen Shot of the AttachmentSelector Control


  • FileName and URL properties which are read/write.
  • A UrlMaxLength property, which gets or sets the MaxLength property of the URL textbox.
  • A RequiredField property, which is used for validation.
  • An AllowUrlAndDocument property, which is also used for validation. If False and the user specified both a URL and a file to upload, the IsValid property returns False.
  • If the user tries to upload a file, the file extension is validated against the AllowedFileExtensions setting in the web.config file.
  • An IsValid property, which is calculated based on other property settings.
  • A ReasonInvalid property, which provides an explanation for why IsValid is False.
  • An Attachment property, which is read-only, and returns the URL or FileName (whichever is specified).
  • A VirtualUploadPath property, which sets the target path of the uploaded file
  • An Upload method, which uploads the file to the VirtualUploadPath folder.
  • An UploadTo method, which accepts a server virtual path to upload the file to. (If no upload file is specified, then this method does nothing.)
  • CssClassLabel and CssClassData properties which set the CssClass property of the various child controls.
  • An AlternateLink property, which accepts literal HTML code to be used in place of the document hyperlink for an uploaded file. (This doesn't display when the user specifies a URL — only an uploaded file.)

Screen Shot of the AttachmentSelector Control using the AlternateLink feature

Screen Shot of the AttachmentSelector Control using the AlternateLink feature



Sample Implementation

To use this control, you need to follow the instructions in the Consuming Custom Controls in ASP.NET article.

ASPX Markup

<asp:CustomValidator runat="server" ID="uxAttachmentValidator"
    SetFocusOnError="true" ValidationGroup="MainValidationGroup"
    EnableClientScript="false"
    OnServerValidate="uxAttachmentValidator_Validate"
    ErrorMessage="ERROR"
    >
    
    <asp:Image ID="Image6" runat="server" 
        ImageUrl="~/images/Exclamation.PNG" />

    </asp:CustomValidator>

...

<abc:AttachmentSelector runat="server" ID="uxAttachmentSelector" 
    AllowUrlAndDocument="false" RequiredField="false"
    />

Code-Behind

In addition to the following code, you will need to do two things which depend on your implementation.

  • When displaying a record, set the File, URL, or both properties of the AttachmentSelector.
  • After saving a record, call the AttachmentSelector.UploadTo(serverPath) method.

VB.NET

Protected Sub uxAttachmentValidator_Validate(ByVal sender As Object, ByVal e As _
ServerValidateEventArgs)

    Dim uxValidator As CustomValidator = CType(sender, CustomValidator)
    Dim selectorName As String = uxValidator.ID.Replace("Validator", "Selector")
    Dim c As Control = uxValidator.Parent.FindControl(selectorName)
    Dim uxAttachmentSelector As AttachmentSelector = CType(c, AttachmentSelector)

    e.IsValid = uxAttachmentSelector.IsValid
    uxValidator.ErrorMessage = uxAttachmentSelector.ReasonInvalid

End Sub

C#

TODO

Source Code

ASPX Markup

The header line will change depending on the language of the code-behind file.

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="AttachmentSelector.ascx.vb"
    Inherits="AttachmentSelector" %>

<asp:HiddenField runat="server" ID="uxFileNameField" />
<asp:HiddenField runat="server" ID="uxUploadPathField" />

<asp:Table runat="server" ID="uxDocumentTable" Width="100%">

    <%-- Document Link, Literal Control, and Delete Checkbox --%>
    <asp:TableRow>
        <asp:TableCell VerticalAlign="middle" HorizontalAlign="right" CssClass="fieldLabel" Font-Size="8pt"
                Width="7em" ID="uxDocumentCell">
            Link:
            </asp:TableCell>
        <asp:TableCell VerticalAlign="middle" HorizontalAlign="left" ColumnSpan="2" >
        
            <asp:HyperLink runat="server" ID="uxDocumentHyperLink" Target="_blank" CssClass="fieldLabel" ForeColor="blue" />
            <asp:Literal runat="server" ID="uxAlternateLinkLiteral" Text="" />
            &nbsp;
            <asp:CheckBox runat="server" ID="uxDeleteCheckBox" Checked="false" Text="No attachment"
                Visible="false" CssClass="fieldLabel" />
        
                
        </asp:TableCell>
    </asp:TableRow>
    
    <%-- File Upload --%>
    <asp:TableRow>
    
        <asp:TableCell VerticalAlign="middle" HorizontalAlign="right" CssClass="fieldLabel" Font-Size="8pt"
            ID="uxUploadCell" Text="Replace with:" />
            
        <asp:TableCell VerticalAlign="middle" HorizontalAlign="left">
        
            <asp:FileUpload runat="server" ID="uxFileUpload" Width="98%" CssClass="fieldData" />
            
        </asp:TableCell>
    </asp:TableRow>
    
    <%-- URL --%>
    <asp:TableRow>
        <asp:TableCell VerticalAlign="middle" HorizontalAlign="right" CssClass="fieldLabel" Font-Size="8pt"
            ID="uxUrlCell" Text="URL:" />
            
        <asp:TableCell VerticalAlign="middle" HorizontalAlign="left">
        
            <asp:TextBox runat="server" ID="uxUrlTextBox" Width="98%" CssClass="fieldData" />
            
        </asp:TableCell>
    </asp:TableRow>
    
</asp:Table>

Code-Behind

VB.NET

To be used with the following "header" line.
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="AttachmentSelector.ascx.vb"  
    Inherits="AttachmentSelector"   
    %>

Imports System.IO

Partial Class AttachmentSelector

    Inherits System.Web.UI.UserControl

    Private _reasonInvalid As String
    Private _allowUrlAndDoc As Boolean
    Private _requiredField As Boolean
    Private _cssClassLabels As String
    Private _cssClassFields As String
    Private _labels() As String
    Private _fields() As String

    Public Sub UserControl_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender

        'uxDebuggingLabel.Visible = System.Diagnostics.Debugger.IsAttached

        For Each s As String In _labels
            Dim ctl As WebControl = Me.FindControl(s)
            If ctl IsNot Nothing Then
                ctl.CssClass = _cssClassLabels
            End If
        Next

        For Each s As String In _fields
            Dim ctl As WebControl = Me.FindControl(s)
            If ctl IsNot Nothing Then
                ctl.CssClass = _cssClassFields
            End If
        Next

        DisplayHyperLink()

    End Sub
    Public Sub New()

        _reasonInvalid = ""
        _allowUrlAndDoc = False
        _requiredField = False
        _labels = New String() {"uxDebuggingLabel", "uxDocumentCell", "uxDocumentHyperLink", _
                                "uxDeleteCheckBox", "uxUrlCell", "uxUploadCell"}
        _fields = New String() {"uxUrlTextBox", "uxFileUpload"}

    End Sub

    Public Property AllowUrlAndDocument() As Boolean
        Get
            Return _allowUrlAndDoc
        End Get
        Set(ByVal value As Boolean)
            _allowUrlAndDoc = value
        End Set
    End Property

    ''' <summary>
    ''' If specified, returns the URL; otherwise returns the FileName specified.
    ''' </summary>
    Public ReadOnly Property Attachment() As String
        Get
            Dim result As String = Me.FileName
            If Me.URL.Length > 0 Then
                result = Me.URL
            End If
            Return result
        End Get
    End Property

    Public Property CssClassLabel() As String
        Get
            Return _cssClassLabels
        End Get
        Set(ByVal value As String)
            _cssClassLabels = value
        End Set
    End Property

    Public Property CssClassData() As String
        Get
            Return _cssClassFields
        End Get
        Set(ByVal value As String)
            _cssClassFields = value
        End Set
    End Property

    ''' <summary>
    ''' File name WITHOUT path
    ''' </summary>
    Public Property FileName() As String
        Get

            Dim result As String = ""

            If Me.URL.Length = 0 And Not uxDeleteCheckBox.Checked Then

                result = uxFileUpload.FileName

                If result.Length = 0 Then

                    result = uxFileNameField.Value

                End If

            End If

            Return result

        End Get
        Set(ByVal value As String)
            uxFileNameField.Value = value
            DisplayHyperLink()
        End Set
    End Property

    Public ReadOnly Property IsValid() As Boolean
        Get

            Dim result As Boolean = False
            Dim validExtensions As String = ConfigurationManager.AppSettings("AllowedFileExtensions")
            _reasonInvalid = ""

            Dim itemsSpecified As Integer = 0

            If uxUrlTextBox.Text.Length > 0 Then
                itemsSpecified += 1
            End If

            If uxFileUpload.HasFile Then
                itemsSpecified += 1
            End If

            'result = (itemsSpecified <= 1)

            '-- Verify something was specified (?) ------------------------------------------------
            If _requiredField And itemsSpecified = 0 And uxFileNameField.Value.Length = 0 Then

                _reasonInvalid = "Either Document or URL must be specified."

            '-- Verify both weren't specified (?) -------------------------------------------------
            ElseIf itemsSpecified = 2 And Not _allowUrlAndDoc Then

                _reasonInvalid = "Cannot specify both a Document and a URL."


            '-- Verify that Valid Extensions are Configured ---------------------------------------
            ElseIf validExtensions Is Nothing Then

                _reasonInvalid = "No valid extensions for file uploads were found in the " & _
                                    "configuration file."

            '-- Validate File Extension for Uploaded File (?) -------------------------------------
            ElseIf uxFileUpload.HasFile Then

                Dim exts() As String = validExtensions.Split(New Char() {"|"c}, _
                                            StringSplitOptions.RemoveEmptyEntries)

                Dim myExt As String = Path.GetExtension(uxFileUpload.FileName).ToUpper()
                If myExt.Length > 0 Then
                    myExt = myExt.Substring(1)
                End If

                _reasonInvalid = "You are not allowed to upload files with an extension of '." & _
                                    myExt & "'"

                For Each ext As String In exts

                    If myExt = ext.ToUpper() Then
                        result = True
                        _reasonInvalid = ""
                    End If

                Next

            '-- Default Case ----------------------------------------------------------------------
            Else

                result = True

            End If

            Return result

        End Get
    End Property

    Public Property AlternateLink() As String
        Get
            Return uxAlternateLinkLiteral.Text
        End Get
        Set(ByVal value As String)
            uxAlternateLinkLiteral.Text = value
            DisplayHyperLink()
        End Set
    End Property

    ''' <remarks>IMPORTANT: Be sure to call the IsValid property before accessing the 
    '''     ReasonInvalid property!</remarks>
    Public ReadOnly Property ReasonInvalid() As String
        Get

            Return _reasonInvalid

        End Get
    End Property

    Public Property RequiredField() As Boolean
        Get
            Return _requiredField
        End Get
        Set(ByVal value As Boolean)
            _requiredField = value
            uxDeleteCheckBox.Visible = Not _requiredField
        End Set
    End Property

    Public Property VirtualUploadPath() As String
        Get
            Return uxUploadPathField.Value
        End Get
        Set(ByVal value As String)
            uxUploadPathField.Value = value
            DisplayHyperLink()
        End Set
    End Property

    Public Property URL() As String
        Get
            Dim result As String = ""
            If Not uxDeleteCheckBox.Checked Then
                result = uxUrlTextBox.Text
            End If
            Return result
        End Get
        Set(ByVal value As String)
            uxUrlTextBox.Text = value
            DisplayHyperLink()
        End Set
    End Property

    Public Property UrlMaxLength() As Integer
        Get
            Return uxUrlTextBox.MaxLength
        End Get
        Set(ByVal value As Integer)
            uxUrlTextBox.MaxLength = value
        End Set
    End Property

    Public Sub UploadTo(ByVal virtualPath As String)

        If uxFileUpload.HasFile AndAlso Me.IsValid And Not uxDeleteCheckBox.Checked Then

            Try

                Me.VirtualUploadPath = virtualPath

                Dim shortFileName As String = uxFileUpload.FileName
                Dim serverPath As String = Me.Page.Server.MapPath(virtualPath)

                If Not Directory.Exists(serverPath) Then
                    Directory.CreateDirectory(serverPath)
                End If

                Dim serverFile As String = Path.Combine(serverPath, shortFileName)

                uxFileUpload.SaveAs(serverFile)

            Catch ex As Exception

                Throw ex

            End Try

        End If

        DisplayHyperLink()

    End Sub
    ''' <summary>
    ''' Maps the VirtualUploadPath property to a physical path on the server, creates the folder  
    ''' (if necessary), and uploads the specified file to this folder.
    ''' </summary>
    Public Sub Upload()
        Me.UploadTo(Me.VirtualUploadPath)
    End Sub

    Private Sub DisplayHyperLink()

        If Not Me.IsValid Then

            ' Do nothing

        ElseIf Me.URL.Length > 0 Then

            uxDocumentHyperLink.Visible = True
            uxDocumentHyperLink.Text = Me.URL
            uxDocumentHyperLink.NavigateUrl = Me.URL
            uxDeleteCheckBox.Visible = Not _requiredField
            uxAlternateLinkLiteral.Visible = False
            uxUploadCell.Text = "Upload:"

        ElseIf Me.FileName.Length > 0 Then

            uxDocumentHyperLink.Text = Me.FileName
            uxDocumentHyperLink.Visible = (uxAlternateLinkLiteral.Text.Length = 0)
            uxDocumentHyperLink.NavigateUrl = Path.Combine(Me.VirtualUploadPath, Me.FileName)
            uxDeleteCheckBox.Visible = Not _requiredField
            uxAlternateLinkLiteral.Visible = True
            uxUploadCell.Text = "Replace with:"

        Else

            uxDocumentHyperLink.Text = "(unspecified)"
            uxDocumentHyperLink.Visible = True
            uxDocumentHyperLink.NavigateUrl = ""
            uxDeleteCheckBox.Visible = False
            uxAlternateLinkLiteral.Visible = False
            uxUploadCell.Text = "Upload:"
            
            ' This is to prevent retaining the URL or FileName
            uxUrlTextBox.Text = ""
            uxFileNameField.Value = ""

        End If

        ' This is to prevent retaining the "No attachment" selection
        If Not uxDeleteCheckBox.Visible Then
            uxDeleteCheckBox.Checked = False
        End If

    End Sub

End Class

C#

To be used with the following ASPX "header" line.
<%@ Control Language="C#" AutoEventWireup="false" CodeFile="AttachmentSelector.ascx.cs"  
    Inherits="AttachmentSelector"   
    %>

TODO

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.