Table of Contents [Hide/Show]
Features Sample Implementation ASPX Markup Code-Behind VB.NET C# Source Code ASPX Markup Code-Behind VB.NET C#
Screen Shot of the AttachmentSelector Control
FileName
URL
UrlMaxLength
MaxLength
RequiredField
AllowUrlAndDocument
False
IsValid
AllowedFileExtensions
ReasonInvalid
Attachment
VirtualUploadPath
Upload
UploadTo
CssClassLabel
CssClassData
CssClass
AlternateLink
Screen Shot of the AttachmentSelector Control using the AlternateLink feature
<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" />
File
AttachmentSelector
AttachmentSelector.UploadTo(serverPath)
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
TODO
<%@ 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="" /> <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>
<%@ 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
<%@ Control Language="C#" AutoEventWireup="false" CodeFile="AttachmentSelector.ascx.cs" Inherits="AttachmentSelector" %>