Solved

Need help in finding out why the path is being duplicated?

Posted on 2011-03-10
8
241 Views
Last Modified: 2012-06-21
Hi all;

I am having a problem when submitting this form. The path of the file to be uploaded gets duplicated and the file does not get uploaded . Could you please help me??

Here is the code:
<%@ Page 
&#9;Language="VB" 
&#9;MasterPageFile="~/_templates/MasterPage-ContentNormal.master" 
&#9;autoeventwireup="false" 
&#9;inherits="SierraClub.PublicSite.BasePage"
&#9;title="San Francisco Internships  - Careers - Sierra Club"
&#9;ShortTitle="San Francisco"
&#9;%>
<asp:content id="content1" contentplaceholderid="maincontent" runat="Server">

<style type="text/css">
 body{
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
}
p, h1, form, button{border:0; margin:0; padding:0;}
.spacer{clear:both; height:1px;}
/* ----------- My Form ----------- */
.myform{
margin:0 auto;
width:600px;
padding:14px;
}

/* ----------- stylized ----------- */
#stylized{
border:solid 2px #b7ddf2;
background:#ebf4fb;
}
#stylized h1 {
font-size:14px;
font-weight:bold;
margin-bottom:8px;
}
#stylized p{
font-size:11px;
color:#666666;
margin-bottom:20px;
border-bottom:solid 1px #b7ddf2;
padding-bottom:10px;
}
#stylized label{
display:block;
font-weight:bold;
text-align:right;
width:140px;
float:left;
}
#stylized .small{
color:#666666;
display:block;
font-size:11px;
font-weight:normal;
text-align:right;
width:140px;
}
#stylized input{
float:left;
font-size:12px;
padding:4px 2px;
border:solid 1px #aacfe4;
width:200px;
margin:2px 0 20px 10px;
}
#stylized button{
clear:both;
margin-left:150px;
width:125px;
height:31px;
background:#666666 url(img/button.png) no-repeat;
text-align:center;
line-height:31px;
color:#FFFFFF;
font-size:11px;
font-weight:bold;
}
 </style>
 <div class="myform" id="stylized">
  
<asp:label ID="errorLabel" runat="server"></asp:label>
<asp:Panel ID="Panel1" runat="server">

    

    <div 
        id="formbody" 
        runat="server" 
        style="clear: left; padding: 10px 0 0" 
        visible="true"         
        >  
  
  <fieldset>
  <legend>Basic Information</legend>
  <table>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    * First Name:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox8" runat="server" AutoPostBack="True" 
                        CausesValidation="True" MaxLength="40">First Name</asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidatorFirstName" runat="server" 
                        ControlToValidate="TextBox1" Display="Dynamic" 
                        ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    * Last Name:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox9" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Address:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox10" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2" align="right" style="font-weight: bold" valign="middle">
                    <b>Address Line 2 (<em>Optional</em>):</b></td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox11" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    City:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox12" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    State:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox13" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Zip code:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox14" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Day/Work Phone (000)-000-0000:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox15" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Evening Phone (000)-000-0000:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox16" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    * Email:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox17" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Name of School:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox18" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Year in School:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox19" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Graduated:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox20" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    Degree:</td>
                <td valign="middle">
                    <asp:TextBox ID="TextBox21" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style6" align="right" style="font-weight: bold" valign="middle">
                    &nbsp;</td>
                <td valign="middle">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            </table>

    </fieldset>
    <table>
        <tr>
            <td class="style4" colspan="7">
                &nbsp;</td>
        </tr>

           
        <tr>
            <td colspan="7">
                <fieldset id="application">
    <legend><b>Application Questions</b></legend>
    <br />
    <table>
    <tr>
            <td class="style5" align="right" valign="middle">
                1.</td>
            <td colspan="6" class="style3">
                
                    <b>Why are you interested in this position of Conservation Training Intern? What 
                                  about the position intrigues you? </b>
                
            </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                <asp:TextBox ID="TextBox1" runat="server" Height="70px" Width="550px" 
                    TextMode="MultiLine"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style4" colspan="7">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style4" align="right" valign="middle">
                2.</td>
            <td colspan="6">
               
                    <b>What would you hope to learn or to accomplish?</b>
            </td>
        </tr>
        <tr>
            <td class="style4" align="right">
                &nbsp;</td>
            <td colspan="6">
                <asp:TextBox ID="TextBox2" runat="server" Height="70px" TextMode="MultiLine" 
                    Width="550px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style4" colspan="7">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style4" align="right" valign="middle">
                3.</td>
            <td colspan="6">
                
                    <b>What kind of experience do you have in either organizing events, running 
                                  meetings or as a trainer?</b>
            </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                <asp:TextBox ID="TextBox3" runat="server" Height="70px" TextMode="MultiLine" 
                    Width="550px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style4" align="right" valign="middle">
                4.</td>
            <td colspan="6">
               <b>Tell me a little bit about your availability, what does your schedule look 
                                  like and what would work for you in terms of being part of our team?</b></td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                <asp:TextBox ID="TextBox4" runat="server" Height="70px" TextMode="MultiLine" 
                    Width="550px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                &nbsp;</td>
        </tr>
    </table>
        </fieldset>
       </td>          
    <td class="style4" colspan="7">
                &nbsp;</td>
        </tr>
        
    
        
        <tr>
            <td class="style4">
                &nbsp;
             </td>
            <td colspan="6">
            </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
               <fieldset id="Fieldset2">
    <legend><b>Specifically, please let me know days of the week you are available</b></legend>
    <br /><label for="Monday">Monday</label>
    <input name="Monday" id="Monday" type="checkbox" 
    value="Monday"/>
    <br /><br /><br />
    <label for="Tuesday">Tuesday</label> 
    <input name="Tuesday" id="Tuesday" type="checkbox" 
    value="Tuesday"/>
    <br /><br /><br />
    <label for="Wednesday">Wednesday</label> 
    <input name="Wednesday" id="Wednesday" type="checkbox" 
    value="Wednesday" />
    <br /><br /><br />
    <label for="Thursday">Thursday</label> 
    <input name="Thursday" id="Thursday" type="checkbox" 
    value="Thursday" />
    <br /><br /><br />
    <label for="Wednesday">Friday</label> 
    <input name="Friday" id="Friday" type="checkbox" 
    value="Friday" />
   
    <br />
    </fieldset> </td>
            
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                &nbsp;</td>
        </tr>
        
        
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
               <fieldset id="Fieldset1">
    <legend><b>Time you are available</b></legend>
    <br /><label for="email">mornings (9-12 p.m.)</label>
    <input name="email" id="email" type="checkbox" 
    value="email"/>
    <br /><br /><br />
    <label for="afternoon">afternoons (1-5)</label> 
    <input name="afternoon" id="afternoon" type="checkbox" 
    value="afternoon"/>
    <br /><br /><br />
    <label for="other">Other</label> 
    <input name="other" id="other" type="checkbox" 
    value="other" />
    <br />
    </fieldset></td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
               <fieldset id="page_kind">
    <legend><b>Dates Available</b></legend>
    <br /><label for="website">Start date</label> 
    <input name="sdate" id="sdate"  type="text" /><br /><br /><br />
    <label for="website">End date</label> 
    <input name="edate" id="edate"  type="text" />
    </fieldset>
     </td>
        </tr>
        
        
        <tr>
            <td class="style4" align="right" valign="middle">
                5.</td>
            <td colspan="6">
               <b>Do you have any questions for me? Let me know.</b></td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                <asp:TextBox ID="TextBox7" runat="server" Height="70px" TextMode="MultiLine" 
                    Width="550px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style7">
                </td>
            <td class="style7" width="80px" colspan="2">
                File Name:</td>
            <td class="style7" colspan="2">
                <asp:FileUpload ID="SampleFileUpload" runat="server" Width="200px" />
            </td>
            <td class="style7" colspan="2">
                </td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                Thanks for your interest in this internship.   Someone will be in touch with you to let you know the status of
 your application, set up an interview or request additional materials.  These materials would include:  a brief
  cover letter, a resume and a writing sample (flyers for events you have organized - rally, concert, etc. welcome too!).</td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6">
                &nbsp;</td>
        </tr>
        <tr>
            <td class="style4">
                &nbsp;</td>
            <td colspan="6" align="center" valign="middle">

            </td>
        </tr>
    </table>
</div>



&#9;    <SiteControls:FormControl 
&#9;        FileUploadControlName="ctl00$maincontent$SampleFileUpload" 
&#9;        id="form_submitted" 
&#9;        runat="Server"
&#9;        FileDirectory="/upload/resumes/"
&#9;        FilePath="media_interns.txt"
&#9;        sendto="adrian.cotter@sierraclub.org"
&#9;        FormNameValue="MediaInterns"
&#9;        From="website@sierraclub.org"
&#9;        FromName="MediaIntern App"
&#9;        showEmailsent="true"
&#9;        IncludeEmail="false"
&#9;        IncludeName="false" 
&#9;        Appendformdetails="true"
&#9;   &#9;    AppendUserDetails="true"
&#9;        FormEmailField="Email"
    &#9;    Subject="Test"
        &#9;ConfirmationText="Confirmed!"
        &#9;IncludeFrom="false"
        &#9;errormessagebox="errorLabel"
        &#9; 
        &#9;
        ></SiteControls:FormControl>

</asp:Panel>

</div>

</asp:content>

Open in new window


And here is the Web form control page

Imports Microsoft.VisualBasic
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web
Imports System.Data
Imports System.data.SqlClient
Imports System.Data.Common
Imports SierraClub.PublicSite.UI
Imports System.Collections
Imports System.Collections.Generic
Imports system.Web.Configuration
Imports System.Net.Mail
Imports System.io

Namespace SierraClub.PublicSite.UI.Controls
    Public Class FormWebPart
        Inherits UserControl

        Private _EmailsTo As String
        Private _EmailsToCC As String
        Private _EmailsToBCC As String
        Private _EmailFrom As String = "website@sierraclub.org"
        Private _EmailFromName As String = "Public Website"
        Private _EmailFromField As String
        Private _EmailSubject As String
        Private _EmailHeaderText As String
        Private _EmailFooterText As String
        Private _EmailFormat As String
        Private _FilePath As String
        Private _FileDirectory As String
        Private _body As String
        Private _html As Boolean
        Private _baseDirectory As String
        Private _isappenduserdetails As Boolean = False
        Private _isappendformdetails As Boolean = False
        Private _errormessagelabel As String
        Private _formfieldnames As String
        Private _sendconfirmation As Boolean = False
        Private _confirmationtext As String = ""
        Private _showemailsent As String = ""
        Private _fileuploadcontrol As String = ""

        Protected Overridable Sub setUpForm()
            If Not Page.FindControl("ctl00$maincontent$form_submitted$originalpage") Is Nothing Then
                Dim obj As HiddenField = Page.FindControl("ctl00$maincontent$form_submitted$originalpage")
                obj.Value = Page.Request.ServerVariables.Item("REFERER")
            End If
        End Sub

        Private Sub setFormInfo()
            Dim obj As HiddenField = Page.FindControl("FormSubmitter$submitdate")
            If Not obj Is Nothing Then
                obj.Value = Now().ToString()
            End If
        End Sub

        Protected Function validateForm(ByVal formResults As System.Collections.Specialized.NameValueCollection) As Boolean
            Dim isFormValid As Boolean = True
            Dim submitdate As Date
            Dim currentdate As Date = Now()
            Dim errortext As String = ""

            Try
                submitdate = CType(formResults("ctl00$maincontent$form_submitted$submitdate"), Date)
                If IsDate(submitdate) Then
                    If submitdate.AddHours(12) < currentdate Then
                        errortext = "* form submission date not close to current date. current:" & currentdate.ToString() & " " & submitdate.ToString() & vbCrLf
                        isFormValid = False
                    End If

                Else
                    errortext = "* submit date is not a date " & vbCrLf
                    isFormValid = False
                End If
            Catch objerror As Exception
                errortext = objerror.Message & "* an error occured in validating submit date." & submitdate & vbCrLf
                isFormValid = False
            End Try
&#9;
&#9;&#9;&#9;' SUBMITTIME is a spam filter... it sbould be empty. If it is not,
&#9;&#9;&#9;' it is likely a spam bot filling in the form.
            Dim extrafield As String = formResults("FormSubmitter$submittime")
            If extrafield <> "" Then
                errortext = "* submit time should be empty. " & extrafield & vbCrLf
                isFormValid = False
            End If

            If Not isFormValid Then
                sendError(errortext)
                WriteError("<p>Sorry. For some reason your form submission did not validate correctly. Please send an email to webmaster@sierraclub.org with the URL, and any details of your form submission.</p>")

            End If

            Return isFormValid

        End Function

        Protected Function sendEmail() As Boolean
            Dim isSent As Boolean = True
            Dim mm As New MailMessage()
            Try

                mm.From = New MailAddress(From, FromName)
                addEmails(sendto, mm.To)
                addEmails(CC, mm.CC)
                addEmails(BCC, mm.Bcc)
                mm.Subject = Subject

                sendbody = sendbody.Replace("<", "&lt;")
                sendbody = sendbody.Replace(">", "&gt;")

                mm.Body = sendbody

                mm.IsBodyHtml = sendhtml

                Dim smtp As New SmtpClient
                smtp.Send(mm)
            Catch objerror As Exception
                isSent = False
                WriteError("<p>(Sorry. For some reason your form submission was not sent. Please send an email to webmaster@sierraclub.org with the URL, and any details of your form submission.</p>" & objerror.StackTrace)
            End Try
            Return isSent

        End Function

        Protected Function logSubmission(ByVal FormItems As NameValueCollection, ByVal includeUserInfo As Boolean) As Boolean
            Dim hasSavedFile As Boolean = True
            Dim lineOfData As String = ""
            Dim headerData As String = ""

            Dim key As String
            Dim item As String
            For Each key In formitems
                If Not key.StartsWith("__") And Not (key.Contains("$") And Not key.Contains("ctl00$maincontent")) Then
                    headerData &= key & vbTab
                    If FormItems(key) <> "" Then
                        item = FormItems(key)
                        item = item.Replace(vbCrLf, " [newline] ")
                        item = item.Replace(vbTab, " ")
                        item = item.Replace("<", "&lt;")
                        item = item.Replace(">", "&gt;")
                        lineOfData &= item & vbTab
                    Else
                        lineOfData &= " " & vbTab
                    End If
                End If
            Next

            If lineOfData <> "" Then
                lineOfData = lineOfData
                hasSavedFile = logData(headerData, lineOfData)
            End If
            Return hasSavedFile
        End Function

        Protected Function logSubmission(ByVal submissionData As Collection, ByVal includeUserInfo As Boolean) As Boolean
            Dim hasSavedFile As Boolean = True



            Return hasSavedFile
        End Function

        Private Function logData(ByVal headerdata As String, ByVal lineOfData As String) As Boolean
            Dim hasSavedFile As Boolean = True
&#9;&#9;&#9;if FilePath.startswith("/") or FilePath.startswith("\") then
&#9;&#9;&#9;&#9;FilePath = FilePath.substring(1)
&#9;&#9;&#9;end if
            Dim fullfilepath As String = FilePath
            fullfilepath.Replace("\", "/")

            Dim actualfilepath As String = fullfilepath.Substring(0, fullfilepath.LastIndexOf("/"))
            Dim filename As String = fullfilepath.Substring(fullfilepath.LastIndexOf("/") + 1)

            Dim objfilepath As DirectoryInfo = New DirectoryInfo(actualfilepath)
            Response.Write("<br>SAVEFILE-" & actualfilepath & " " & filename & "-SAVEFILE")
            Dim errortext As String = ""
            Dim isNew As Boolean = False


            If Not (objfilepath.Exists) Then
                Try
                    isNew = True
                    objfilepath.Create()
                Catch objError As Exception
                    errortext = "<br>The path could not created."
                    sendError("Was not able to create the path: " & vbCrLf & actualfilepath & vbCrLf & vbCrLf & "while trying to save this data:" & vbCrLf & vbCrLf & lineOfData & vbCrLf & vbCrLf & objError.Message)
                End Try
            End If


            Dim objStreamWriter As StreamWriter = Nothing
            If String.IsNullOrEmpty(errortext) Then
                Dim objFile As New FileInfo(fullfilepath)
                If objFile.Exists Then
                    Try
                        objStreamWriter = File.AppendText(fullfilepath)
                        objStreamWriter.WriteLine(lineOfData)
                    Catch objError As Exception
                        errortext = "<br>The data could not be saved. Please email webmaster@sierraclub.org with this error."
                        sendError("The data was not saved to the file: " & vbCrLf & fullfilepath & vbCrLf & vbCrLf & "while trying to save this data:" & vbCrLf & vbCrLf & lineOfData & vbCrLf & vbCrLf & objError.Message)
                    Finally
                        'Close the stream
                        If Not objStreamWriter Is Nothing Then
                            objStreamWriter.Close()
                        End If
                    End Try
                Else
                    Try
                        objStreamWriter = File.CreateText(fullfilepath)
                        objStreamWriter.WriteLine(headerdata)
                        objStreamWriter.WriteLine(lineOfData)
                    Catch objError As Exception
                        errortext = "<br>The file could not created."
                        sendError("Was not able to create the file: " & vbCrLf & fullfilepath & vbCrLf & vbCrLf & "while trying to save this data:" & vbCrLf & vbCrLf & lineOfData & vbCrLf & vbCrLf & objError.Message)
                    Finally
                        'Close the stream
                        If Not objStreamWriter Is Nothing Then
                            objStreamWriter.Close()
                        End If
                    End Try
                End If
            End If


            If Not String.IsNullOrEmpty(errortext) Then
                hasSavedFile = False
                WriteError("<p>A record of your form submission was not logged." & errortext & " </p>")
            End If

            Return hasSavedFile

        End Function


        Protected Sub sendError(ByVal errortext As String)
            Dim mm As New MailMessage()
            mm.From = New MailAddress("webmaster@sierraclub.org", Page.Title())
            mm.To.Add("lbeddawi84@gmail.com")
            mm.Subject = "ERROR: Email Message Error"
            mm.Body = "An email submitted from:" & vbCrLf
            mm.Body &= Page.Request.Url.ToString() & vbCrLf
            mm.Body &= "Was not send because of " & vbCrLf
            mm.Body &= errortext & vbCrLf & vbCrLf
            mm.Body &= "from: " & From & vbCrLf
            mm.Body &= "from name: " & FromName & vbCrLf
            mm.Body &= "to: " & sendto & vbCrLf
            mm.Body &= "cc: " & CC & vbCrLf
            mm.Body &= "bcc: " & BCC & vbCrLf
            mm.Body &= "subject: " & Subject & vbCrLf
            mm.Body &= "body: " & appendFormInfo(Request.Form) & vbCrLf
            mm.Body &= "ishtml: " & sendhtml & vbCrLf
            mm.IsBodyHtml = False
            Try
                Dim smtp As New SmtpClient
                smtp.Send(mm)
            Catch objerror As Exception
                WriteError(objerror.Message)
            End Try

        End Sub

        Protected Function appendNormalFormInfo(ByVal formitems As NameValueCollection) As String
            Dim formdetails As String = "INFO SUBMITTED:" & vbCrLf
            Dim key As String
            Dim tempKey As String = ""

&#9;&#9;&#9;' SENDING and email to the user. We want to only send them form fields
&#9;&#9;&#9;' that they have filled in.
&#9;&#9;&#9;' ??? One problem might be if we have any input elements in the form
&#9;&#9;&#9;' that have runat="server"
            For Each key In formitems
                If Not key.StartsWith("__") And Not (key.Contains("$") and not key.Contains("ctl00$maincontent"))  Then
&#9;&#9;&#9;&#9;'                If Not key.StartsWith("__") And Not key.Contains("FormSubmitter$") And Not (key.Contains("Clubhouse") And key.Contains("$")) And Not key.Contains("sender_sessionID") Then
                    tempKey = key.Replace("_", " ")
                    tempKey = tempKey.Replace("-", " ")
&#9;&#9;&#9;&#9;&#9;' trying to strip out extra data in field names that ASP.NET adds
&#9;&#9;&#9;&#9;&#9;if (tempKey.contains("$")) then
&#9;&#9;&#9;&#9;&#9;&#9;tempKey = tempKey.substring( tempKey.lastIndexOf("$")+1 )
&#9;&#9;&#9;&#9;&#9;end if
                    formdetails &= tempKey & ": " & formitems(key) & vbCrLf
                End If
            Next

            Return formdetails
        End Function

        Protected Function appendFormInfo(ByVal formitems As NameValueCollection) As String
            Dim formdetails As String = "FORM DETAILS --" & vbCrLf
            Dim key As String

&#9;&#9;&#9;' THIS lists out form elements intro a string.
&#9;&#9;&#9;' &#9;Formelementname: Value
&#9;&#9;&#9;' We want to exlude things that don't belong to the form
&#9;&#9;&#9;' __ elements, are ASP.NET form elements
&#9;&#9;&#9;' we want to also include any elements that are inside the control
            For Each key In formitems
                If Not key.StartsWith("__") And Not (key.Contains("$") and not key.Contains( me.id )) Then
&#9;&#9;&#9;&#9;&#9;dim currentKey as string = key
&#9;&#9;&#9;&#9;&#9;' trying to strip out extra data in field names that ASP.NET adds
&#9;&#9;&#9;&#9;&#9;if (key.contains("$")) then
&#9;&#9;&#9;&#9;&#9;&#9;currentKey = key.substring( key.lastIndexOf("$")+1 )
&#9;&#9;&#9;&#9;&#9;end if
                    formdetails &= currentKey & ": " & formitems(key) & vbCrLf
                End If
            Next

            Return formdetails
        End Function

        Protected Function appendUserInfo() As String
            Dim userinfo As String = "USER INFO --" & vbCrLf

            userinfo &= "form url: " & Page.Request.Url.ToString() & vbCrLf
            userinfo &= "browser type: " & Request.Browser.Type & vbCrLf
            userinfo &= "browser version: " & Request.Browser.MajorVersion & "." & Request.Browser.MinorVersion & vbCrLf
            userinfo &= "platform: " & Request.Browser.Platform & vbCrLf
            userinfo &= "cookies enabled: " & Request.Browser.Cookies.ToString() & vbCrLf
            userinfo &= "ip address: " & Request.ServerVariables.Item("REMOTE_ADDR") & vbCrLf
            userinfo &= "win user: " & Request.ServerVariables.Item("REMOTE_USER") & vbCrLf
            userinfo &= "js version: " & Request.Browser.EcmaScriptVersion.ToString() & vbCrLf
            If Page.User.Identity.IsAuthenticated Then
                userinfo &= "clubhouse user: " & Page.User.Identity.Name & vbCrLf
            End If

            Return userinfo
        End Function

        Private Sub addEmails(ByVal addresses As String, ByRef emailtype As System.Net.Mail.MailAddressCollection)
            If addresses <> "" Then
                Dim emails() As String
                Dim x As Integer
                Dim email As String
                emails = addresses.Split(",")
                For x = 0 To emails.Length - 1
                    email = emails(x).Trim()
                    emailtype.Add(email)
                Next
            End If
        End Sub

        Protected Sub WriteError(ByVal errortext As String)
            If Not String.IsNullOrEmpty(ErrorMessageBox) Then
                If Not Me.Page.FindControl(ErrorMessageBox) Is Nothing Then
                    Dim errorbox As Label = CType(FindControlRecursive(Me, ErrorMessageBox), Label)
                    errorbox.Text &= errortext
                Else
                    Response.Write(errortext)
                End If
            End If
        End Sub


        Property FileUploadControlName() As String
            Get
                Return _fileuploadcontrol
            End Get
            Set(ByVal value As String)
                _fileuploadcontrol = value
            End Set
        End Property

        Property SetBaseDirectory() As String
            Get
                Return _baseDirectory
            End Get
            Set(ByVal value As String)
                _baseDirectory = value
            End Set
        End Property


        Property ErrorMessageBox() As String
            Get
                Return _errormessagelabel
            End Get
            Set(ByVal value As String)
                _errormessagelabel = value
            End Set
        End Property

        Property sendto() As String
            Get
                Return _EmailsTo
            End Get
            Set(ByVal value As String)
                _EmailsTo = value
            End Set
        End Property
        Property CC() As String
            Get
                Return _EmailsToCC
            End Get
            Set(ByVal value As String)
                _EmailsToCC = value
            End Set
        End Property
        Property BCC() As String
            Get
                Return _EmailsToBCC
            End Get
            Set(ByVal value As String)
                _EmailsToBCC = value
            End Set
        End Property

        Property From() As String
            Get
                Return _EmailFrom
            End Get
            Set(ByVal value As String)
                _EmailFrom = value
            End Set
        End Property

        Property FromName() As String
            Get
                Return _EmailFromName
            End Get
            Set(ByVal value As String)
                _EmailFromName = value
            End Set
        End Property


        Property Subject() As String
            Get
                Return _EmailSubject
            End Get
            Set(ByVal value As String)
                _EmailSubject = value
            End Set
        End Property

        Property HeaderText() As String
            Get
                Return _EmailHeaderText
            End Get
            Set(ByVal value As String)
                _EmailHeaderText = value
            End Set
        End Property

        Property FooterText() As String
            Get
                Return _EmailFooterText
            End Get
            Set(ByVal value As String)
                _EmailFooterText = value
            End Set
        End Property

        Property FilePath() As String
            Get
                Return _FileDirectory & _FilePath
            End Get
            Set(ByVal value As String)
                _FilePath = value
            End Set
        End Property

        Property FileDirectory() As String
            Get
                Return _FileDirectory
            End Get
            Set(ByVal value As String)
                _FileDirectory = value
            End Set
        End Property



        Property EmailFormat() As String
            Get
                Return _EmailFormat
            End Get
            Set(ByVal value As String)
                _EmailFormat = value
            End Set
        End Property
        Property sendbody() As String
            Get
                Return _body
            End Get
            Set(ByVal value As String)
                _body = value
            End Set
        End Property
        Property sendhtml() As Boolean
            Get
                Return _html
            End Get
            Set(ByVal value As Boolean)
                _html = value
            End Set
        End Property

        Property AppendUserDetails() As Boolean
            Get
                return _isappenduserDetails
            End Get
            Set(ByVal value As Boolean)
                _isappenduserdetails = value
            End Set
        End Property
        Property AppendFormDetails() As Boolean
            Get
                Return _isappendformdetails
            End Get
            Set(ByVal value As Boolean)
                _isappendformdetails = value
            End Set
        End Property

        Property FormFieldNames() As String
            Get
                Return _formfieldnames
            End Get
            Set(ByVal value As String)
                _formfieldnames = value
            End Set
        End Property

        Property FormEmailField() As String
            Get
                Return _EmailFromField
            End Get
            Set(ByVal value As String)
                _EmailFromField = value
            End Set
        End Property

        Property SendConfirmation() As Boolean
            Get
                Return _sendconfirmation
            End Get
            Set(ByVal value As Boolean)
                _sendconfirmation = value
            End Set
        End Property


        Property ConfirmationText() As String
            Get
                Return _confirmationtext
            End Get
            Set(ByVal value As String)
                _confirmationtext = value
            End Set
        End Property

        Property showEmailsent() As Boolean
            Get
                Return _showemailsent
            End Get
            Set(ByVal value As Boolean)
                _showemailsent = value
            End Set
        End Property

        Function FindControlRecursive(ByVal ctrl As Control, ByVal id As String) As Control
            Dim c As Control = Nothing

            If ctrl.ID = id Then
                c = ctrl
            Else
                For Each childCtrl as control In ctrl.Controls
                    Dim resCtrl As Control = FindControlRecursive(childCtrl, id)
                    If resCtrl IsNot Nothing Then c = resCtrl
                Next
            End If

            Return c
        End Function

    End Class

End Namespace

Open in new window


In addition, I need to have a a link to the uploaded file in the email--> to the TO address of the form
--> sendEmail()

so how do I do that?

Thank you so much
 Error Message
0
Comment
Question by:Lamab
8 Comments
 
LVL 8

Expert Comment

by:PagodNaUtak
ID: 35105856
What is the content of the page_load?

Did you check the IsPostBack?
0
 

Author Comment

by:Lamab
ID: 35111398
Hi PagodNaUtak;

Here is the code for Page_Load:

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Collections
Imports SierraClub.PublicSite.UI

Namespace SierraClub.PublicSite.UI.Controls
    Partial Class controls_user_form
        Inherits FormWebPart
        Private formIsNotTargetPage As Boolean = False

        Public Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
            SetBaseDirectory = ConfigurationManager.AppSettings("transactions")

            ' SETS up default values to send in the email.
            formname.Value = FormNameValue
            submitdate.Value = Now()
            Dim pageid As String
            pageid = Request.QueryString("id")
            Dim url As String

            url = Parent.Page.Request.FilePath

            If Not Page.IsPostBack Then

    	        Dim obj As HiddenField = ctype(FindControlRecursive(Page, "originalpage"), hiddenfield)
		   	    If Not obj Is Nothing Then
    	            obj.Value = Page.Request.Url.ToString()
	            End If
                Dim divFormBody As HtmlGenericControl = CType(FindControlRecursive(Page, "ctl00_maincontent_formbody"), HtmlGenericControl)
                If Not divFormBody Is Nothing Then
                    divFormBody.Visible = True
                End If
                thanks.Visible = False
                submitbutton.Visible = True
                resetbutton.Visible = True
            End If

        End Sub

        Protected Sub submitbutton_submit(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbutton.Click
            Dim divFormBody As HtmlGenericControl = CType(Me.Page.FindControl("ctl00$maincontent$formbody"), HtmlGenericControl)

            If validateForm(Request.Form) Then

                Dim fileuploadinfo As String = ""
                If Not String.IsNullOrEmpty(FileUploadControlName) Then

                    Dim fileUploader As FileUpload = CType(Me.Page.FindControl(FileUploadControlName), FileUpload)
                    If fileUploader.HasFile Then
                        Try
                            Dim filename As String = Now.Year & Now.Month & Now.Day & Now.Hour & Now.Minute & Now.Second & Now.Millisecond & "." & fileUploader.FileName
                            Dim path As String = Server.MapPath("/uploads/resumes/")

                            fileUploader.SaveAs(path & filename)

                            fileuploadinfo = fileUploader.PostedFile.FileName & "(" & fileUploader.PostedFile.ContentLength & "/" & fileUploader.PostedFile.ContentType() & ")"

                            'fileuploaded.Text = "File name: " & _
                            '   file_path.PostedFile.FileName & "<br>" & _
                            '  "File Size: " & _
                            ' file_path.PostedFile.ContentLength & " kb<br>" & _
                            '"Content type: " & _
                            'file_path.PostedFile.ContentType()
                        Catch ex As Exception
                            Response.Write("Error uploading file: " & ex.Message.ToString())
                        End Try
                    Else
                        Response.Write("No file was specified.")
                    End If
                End If


                Dim oldfrom As String = From
                Dim oldfromname As String = FromName
                If panel_from.Visible Then
                    FromName = email_fromname.Text
                    From = email_fromemail.Text
                ElseIf From = "" And FormEmailField <> "" Then
                    From = Request.Form(FormEmailField)
                ElseIf From = "" Then
                    From = "webmaster@sierraclub.org"
                    FromName = "Sierra Club"
                    oldfrom = From
                    oldfromname = FromName
                End If

                If panel_email.Visible Then
                    sendto = email.Text
                ElseIf sendto = "" And CC = "" And BCC = "" Then
                    sendto = "webmaster@sierraclub.org"
                End If

                Dim toname As String = ""
                If panel_name.Visible Then
                    toname = name.Text
                End If

				' ________________________________________
                ' EMAIL CONTENT STUFF STARTS
				sendbody = HeaderText
				
				' FormFieldNames is a way to create an email\
				' in a particular format.
				'
				' ??? APC - not sure exactly what the format should look like.
				' find an example on clubhouse?
                If FormFieldNames <> "" Then
                    Dim fields() As String = FormFieldNames.Split(",")
                    Dim fi As Integer
                    Dim afieldname As String = ""
                    For fi = 0 To fields.Length - 1
                        afieldname = fields(fi).Trim()
                        EmailFormat = EmailFormat.Replace("{" & fi.ToString() & "}", Request.Form(afieldname))
                    Next
                    EmailFormat = EmailFormat.Replace("<tab>", vbTab)
                    EmailFormat = EmailFormat.Replace("<return>", vbCrLf)

                    If EmailFormat <> "" Then
                        sendbody &= EmailFormat & vbCrLf & vbCrLf
                    End If
                End If
                sendbody &= FooterText

                Dim messageonly As String = sendbody

				' FORM INPUT FIELDS
				' This should list out all the Form INPUT/TEXAREA/SELECT fields
				' that occur on the page.
                If AppendFormDetails Then
                    If sendbody <> "" Then
                        sendbody &= vbCrLf & vbCrLf
                    End If
					' appendFormInfo is in FormWebPart
                    sendbody = appendFormInfo(Request.Form)		
					
                End If
				
				' ??? IF FILE UPLOADED
				' if not fileuploadinfo empty
				' then append to sendbody
				' sendbody &= filepath & filename 
				' for the email to the sierra club person.
				'	have a link to the file
				'	http://natdev.sierraclub.org/path/filename.
				

				' USER INFORMATION
				' appendUserInfo also appears in FormWebPart
				' this adds browser and other information about 
				' the user.
                If AppendUserDetails Then
                    sendbody &= vbCrLf & appendUserInfo()
                End If

				' flag to let us know whether email should be sent
				' as HTML or not.
                If Not sendhtml Then
                    sendbody = sendbody.Replace("<br>", vbCrLf)
                    sendbody = sendbody.Replace("<br />", vbCrLf)
                End If
                ' EMAIL CONTENT STUFF ENDS
				' ________________________________________

                Response.Write(sendbody)

				' SEND EMAIL AND LOG
                Dim emailSent As Boolean = sendEmail()
                Dim fileSaved As Boolean = logSubmission(Request.Form, True)
                
				' CONFIRMATION EMAIL
				Dim confirmemail As String = ""
                If emailSent And SendConfirmation Then
                    If FormEmailField <> "" Then
                        confirmemail = Request.Form(FormEmailField)
                        Dim oldsendto As String = sendto
                        Dim oldcc As String = CC
                        Dim oldbcc As String = BCC
                        Dim oldsendbody As String = sendbody
                        Dim oldsubject As String = Subject
                        From = oldfrom
                        FromName = From
                        sendto = confirmemail
                        Subject = "Confirmation: " & oldsubject
                        sendbody = "This email confirms the following information was sent to the Sierra Club. " & vbCrLf & messageonly
						' This function appendNormalFormInfo strips out
						' any function that has $
                        If AppendFormDetails Then
                            sendbody &= vbCrLf & appendNormalFormInfo(Request.Form)
                        End If
                        If Not String.IsNullOrEmpty(fileuploadinfo) Then
                            sendbody &= vbCrLf & "FILE: " & fileuploadinfo
                        End If

			' ??? IF FILE UPLOADED
			' give name that was loaded. not path. not link.
			' if fileinfo not empty
			' sendbody &=  


                        Dim confirmationEmailSent As Boolean = sendEmail()
                        sendto = oldsendto
                        sendbody = oldsendbody
                        Subject = oldsubject
                        CC = oldcc
                        BCC = oldbcc
                    End If
                End If

				' display results to the user.
                If emailSent Or fileSaved Then
                    thanks.Visible = True
                   	divFormBody.Visible = False
                    panel_additional.Visible = False
                    panel_name.Visible = False
                    panel_email.Visible = False
                    submitbutton.Visible = False
                    panel_from.Visible = False
                    resetbutton.Visible = False
                    If originalpage.Value <> "" Then
                        RefreshURL.NavigateUrl = originalpage.Value
                        RefreshURL.Visible = True
                        If formIsNotTargetPage Then
                            RefreshURL.Text = "RETURN TO PAGE"
                        Else
                            RefreshURL.Text = "RETURN TO FORM"
                        End If
                    End If
                    If sendto <> "" Then
                        formemailto.Text = sendto
                    Else
                        formemailto.Text = " a staff person"
                    End If
                    If confirmemail <> "" Then
                        formemailto.Text &= ". A confirmation email was sent to " & confirmemail
                    End If
                    If showEmailsent Then
                        emailmessagesent.InnerHtml = "<b>Here is the message that was sent:</b><br /><br />" & messageonly.Replace(vbCrLf, "<br />")
                        If AppendFormDetails Then
                            emailmessagesent.InnerHtml &= "<br />" & appendNormalFormInfo(Request.Form).Replace(vbCrLf, "<br />") & "<br />"
                        End If
                    Else
                        emailmessagesent.Visible = False
                    End If
                    If emailSent And Not fileSaved Then
                        WriteError("The email was sent.")
                    ElseIf fileSaved And Not emailSent Then
                        WriteError("A record of the form submissions was saved.")
                    End If
                Else
                    WriteError("Nothing was sent or saved :-(")
                End If
            Else
            End If

        End Sub

        Property ThanksMessage() As String
            Get
                Return custommessage.Text
            End Get
            Set(ByVal value As String)
                custommessage.Text = value
            End Set
        End Property


        Property IncludeEmail() As String
            Get
                Return panel_email.Visible
            End Get
            Set(ByVal value As String)
                If value = "true" Then
                    panel_email.Visible = True
                Else
                    panel_email.Visible = False
                End If
            End Set
        End Property

        Property IncludeName() As String
            Get
                Return panel_name.Visible
            End Get
            Set(ByVal value As String)
                If value = "true" Then
                    panel_name.Visible = True
                Else
                    panel_name.Visible = False
                End If
            End Set
        End Property

        Property IncludeFrom() As String
            Get
                Return panel_from.Visible
            End Get
            Set(ByVal value As String)
                If value = "true" Then
                    panel_from.Visible = True
                Else
                    panel_from.Visible = False
                End If
            End Set
        End Property

        Property ReturnButton() As String
            Get
                Return panel_return.Visible
            End Get
            Set(ByVal value As String)
                If value = "true" Then
                    panel_return.Visible = True
                Else
                    panel_return.Visible = False
                End If
            End Set
        End Property


        Property SubmitText() As String
            Get
                Return submitbutton.Text
            End Get
            Set(ByVal value As String)
                submitbutton.Text = value
            End Set
        End Property

        Property FormNameValue() As String
            Get
                Return formname.Value
            End Get
            Set(ByVal value As String)
                formname.Value = value
            End Set
        End Property


    End Class

    Public Class field
        Inherits Control

        Private _type As String = "textbox"
        Private _length As Integer = 10
        Private _class As String = ""

        Public Sub New()

        End Sub


    End Class

    Public Class fields
        Inherits Control

        Private _fields As ArrayList
        Private _header As String


        Public ReadOnly Property field() As ArrayList
            Get
                Return _fields
            End Get
        End Property

        Public ReadOnly Property header() As String
            Get
                Return _header
            End Get
        End Property


    End Class

End Namespace

Open in new window

0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 35187719
>The path of the file to be uploaded gets duplicated and the file does not get uploaded .
Not sure what you mean by it gets duplicated.

Why dont you refer to the fileupload control instead of using the FindControl?
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:Lamab
ID: 35236265
HI CodeCruiser:

I was able to solve the problem above.

Thank you so much.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 35238940
Great. How did you solve it?
0
 

Accepted Solution

by:
Lamab earned 0 total points
ID: 35286513
Hi;

Here is what I did:
Imports Microsoft.VisualBasic
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web
Imports System.Data
Imports System.data.SqlClient
Imports System.Data.Common
Imports SierraClub.PublicSite.UI
Imports System.Collections
Imports System.Collections.Generic
Imports system.Web.Configuration
Imports System.Net.Mail
Imports System.io

Namespace SierraClub.PublicSite.UI.Controls
    Public Class FormWebPart
        Inherits UserControl

        Private _EmailsTo As String
        Private _EmailsToCC As String
        Private _EmailsToBCC As String
        Private _EmailFrom As String
        Private _EmailFromName As String
        Private _EmailFromField As String
        Private _EmailSubject As String
        Private _EmailHeaderText As String
        Private _EmailFooterText As String
        Private _EmailFormat As String
        Private _FilePath As String
        Private _FileDirectory As String
        Private _body As String
        Private _html As Boolean
        Private _baseDirectory As String
        Private _isappenduserdetails As Boolean = False
        Private _isappendformdetails As Boolean = False
        Private _errormessagelabel As String
        Private _formfieldnames As String
        Private _sendconfirmation As Boolean = False
        Private _confirmationtext As String = ""
        Private _showemailsent As String = ""
        Private _fileuploadcontrol As String = ""

        Protected Overridable Sub setUpForm()
            If Not Page.FindControl("ctl00$maincontent$form_submitted$originalpage") Is Nothing Then
                Dim obj As HiddenField = Page.FindControl("ctl00$maincontent$form_submitted$originalpage")
                obj.Value = Page.Request.ServerVariables.Item("REFERER")
            End If
        End Sub

        Private Sub setFormInfo()
            Dim obj As HiddenField = Page.FindControl("FormSubmitter$submitdate")
            If Not obj Is Nothing Then
                obj.Value = Now().ToString()
            End If
        End Sub

        Protected Function validateForm(ByVal formResults As System.Collections.Specialized.NameValueCollection) As Boolean
            Dim isFormValid = True
            Dim submitdate As Date
            Dim currentdate As Date = Now()
            Dim errortext As String = ""

            Try
                submitdate = CType(formResults("ctl00$maincontent$form_submitted$submitdate"), Date)
                If IsDate(submitdate) Then
                    If submitdate.AddHours(12) < currentdate Then
                        errortext = "* form submission date not close to current date. current:" & currentdate.ToString() & " " & submitdate.ToString() & vbCrLf
                        isFormValid = False
                    End If

                Else
                    errortext = "* submit date is not a date " & vbCrLf
                    isFormValid = False
                End If
            Catch objerror As Exception
                errortext = objerror.Message & "* an error occured in validating submit date." & submitdate & vbCrLf
                isFormValid = False
            End Try
	
			' SUBMITTIME is a spam filter... it sbould be empty. If it is not,
			' it is likely a spam bot filling in the form.
            Dim extrafield As String = formResults("FormSubmitter$submittime")
            If extrafield <> "" Then
                errortext = "* submit time should be empty. " & extrafield & vbCrLf
                isFormValid = False
            End If

            If Not isFormValid Then
                sendError(errortext)
                WriteError("<p>Sorry. For some reason your form submission did not validate correctly. Please send an email to webmaster@sierraclub.org with the URL, and any details of your form submission.</p>")

            End If

            Return isFormValid

        End Function

        Protected Function sendEmail() As Boolean
            Dim isSent = True
            Dim mm As New MailMessage()
            Try

                mm.From = New MailAddress(From, FromName)
                addEmails(sendto, mm.To)
                addEmails(CC, mm.CC)
                addEmails(BCC, mm.Bcc)
                mm.Subject = Subject

                sendbody = sendbody.Replace("<", "&lt;")
                sendbody = sendbody.Replace(">", "&gt;")

                mm.Body = sendbody

                mm.IsBodyHtml = sendhtml

                Dim smtp As New SmtpClient
                smtp.Send(mm)
            Catch objerror As Exception
                isSent = False
                WriteError("<p>(Sorry. For some reason your form submission was not sent. Please send an email to webmaster@sierraclub.org with the URL, and any details of your form submission.</p>")
            End Try
            Return isSent

        End Function

        Protected Function logSubmission(ByVal FormItems As NameValueCollection, ByVal includeUserInfo As Boolean) As Boolean
            Dim hasSavedFile As Boolean = True
            Dim lineOfData As String = ""
            Dim headerData As String = ""

            Dim key As String
            Dim item As String
            For Each key In formitems
                If Not key.StartsWith("__") And Not (key.Contains("Clubhouse") And key.Contains("$")) Then
                    headerData &= key & vbTab
                    If FormItems(key) <> "" Then
                        item = FormItems(key)
                        item = item.Replace(vbCrLf, " [newline] ")
                        item = item.Replace(vbTab, " ")
                        item = item.Replace("<", "&lt;")
                        item = item.Replace(">", "&gt;")
                        lineOfData &= item & vbTab
                    Else
                        lineOfData &= " " & vbTab
                    End If
                End If
            Next

            If lineOfData <> "" Then
                lineOfData = lineOfData
                hasSavedFile = logData(headerData, lineOfData)
            End If
            Return hasSavedFile
        End Function

        Protected Function logSubmission(ByVal submissionData As Collection, ByVal includeUserInfo As Boolean) As Boolean
            Dim hasSavedFile As Boolean = True



            Return hasSavedFile
        End Function

        Private Function logData(ByVal headerdata As String, ByVal lineOfData As String) As Boolean
            Dim hasSavedFile As Boolean = True
			if FilePath.startswith("/") or FilePath.startswith("\") then
				FilePath = FilePath.substring(1)
			end if
            Dim fullfilepath As String = FilePath
            fullfilepath.Replace("\", "/")

            Dim actualfilepath As String = fullfilepath.Substring(0, fullfilepath.LastIndexOf("/"))
            Dim filename As String = fullfilepath.Substring(fullfilepath.LastIndexOf("/") + 1)

            Dim objfilepath As DirectoryInfo = New DirectoryInfo(actualfilepath)
            Dim errortext As String = ""
            Dim isNew As Boolean = False


            If Not (objfilepath.Exists) Then
                Try
                    isNew = True
                    objfilepath.Create()
                Catch objError As Exception
                    errortext = "<br>The path could not created."
                    sendError("Was not able to create the path: " & vbCrLf & actualfilepath & vbCrLf & vbCrLf & "while trying to save this data:" & vbCrLf & vbCrLf & lineOfData & vbCrLf & vbCrLf & objError.Message)
                End Try
            End If


            Dim objStreamWriter As StreamWriter = Nothing
            If String.IsNullOrEmpty(errortext) Then
                Dim objFile As New FileInfo(fullfilepath)
                If objFile.Exists Then
                    Try
                        objStreamWriter = File.AppendText(fullfilepath)
                        objStreamWriter.WriteLine(lineOfData)
                    Catch objError As Exception
                        errortext = "<br>The data could not be saved. Please email webmaster@sierraclub.org with this error."
                        sendError("The data was not saved to the file: " & vbCrLf & fullfilepath & vbCrLf & vbCrLf & "while trying to save this data:" & vbCrLf & vbCrLf & lineOfData & vbCrLf & vbCrLf & objError.Message)
                    Finally
                        'Close the stream
                        If Not objStreamWriter Is Nothing Then
                            objStreamWriter.Close()
                        End If
                    End Try
                Else
                    Try
                        objStreamWriter = File.CreateText(fullfilepath)
                        objStreamWriter.WriteLine(headerdata)
                        objStreamWriter.WriteLine(lineOfData)
                    Catch objError As Exception
                        errortext = "<br>The file could not created."
                        sendError("Was not able to create the file: " & vbCrLf & fullfilepath & vbCrLf & vbCrLf & "while trying to save this data:" & vbCrLf & vbCrLf & lineOfData & vbCrLf & vbCrLf & objError.Message)
                    Finally
                        'Close the stream
                        If Not objStreamWriter Is Nothing Then
                            objStreamWriter.Close()
                        End If
                    End Try
                End If
            End If


            If Not String.IsNullOrEmpty(errortext) Then
                hasSavedFile = False
                WriteError("<p>A record of your form submission was not logged." & errortext & " </p>")
            End If

            Return hasSavedFile

        End Function


        Protected Sub sendError(ByVal errortext As String)
            Dim mm As New MailMessage()
            mm.From = New MailAddress("webmaster@sierraclub.org", Page.Title())
            mm.To.Add("lbeddawi84@gmail.com")
            mm.Subject = "ERROR: Email Message Error"
            mm.Body = "An email submitted from:" & vbCrLf
            mm.Body &= Page.Request.Url.ToString() & vbCrLf
            mm.Body &= "Was not send because of " & vbCrLf
            mm.Body &= errortext & vbCrLf & vbCrLf
            mm.Body &= "from: " & From & vbCrLf
            mm.Body &= "from name: " & FromName & vbCrLf
            mm.Body &= "to: " & sendto & vbCrLf
            mm.Body &= "cc: " & CC & vbCrLf
            mm.Body &= "bcc: " & BCC & vbCrLf
            mm.Body &= "subject: " & Subject & vbCrLf
            mm.Body &= "body: " & appendFormInfo(Request.Form) & vbCrLf
            mm.Body &= "ishtml: " & sendhtml & vbCrLf
            mm.IsBodyHtml = False
            Try
                Dim smtp As New SmtpClient
                smtp.Send(mm)
            Catch objerror As Exception
                WriteError(objerror.Message)
            End Try

        End Sub

        Protected Function appendNormalFormInfo(ByVal formitems As NameValueCollection) As String
            Dim formdetails As String = "INFO SUBMITTED:" & vbCrLf
            Dim key As String
            Dim tempKey As String = ""

			' SENDING and email to the user. We want to only send them form fields
			' that they have filled in.
			' ??? One problem might be if we have any input elements in the form
			' that have runat="server"
            For Each key In formitems
                If Not key.StartsWith("__") And Not (key.Contains("$") and not key.Contains("ctl00$maincontent"))  Then
				'                If Not key.StartsWith("__") And Not key.Contains("FormSubmitter$") And Not (key.Contains("Clubhouse") And key.Contains("$")) And Not key.Contains("sender_sessionID") Then
                    tempKey = key.Replace("_", " ")
                    tempKey = tempKey.Replace("-", " ")
					' trying to strip out extra data in field names that ASP.NET adds
					if (tempKey.contains("$")) then
						tempKey = tempKey.substring( tempKey.lastIndexOf("$")+1 )
					end if
                    formdetails &= tempKey & ": " & formitems(key) & vbCrLf
                End If
            Next

            Return formdetails
        End Function

        Protected Function appendFormInfo(ByVal formitems As NameValueCollection) As String
            Dim formdetails As String = "FORM DETAILS --" & vbCrLf
            Dim key As String

			' THIS lists out form elements intro a string.
			' 	Formelementname: Value
			' We want to exlude things that don't belong to the form
			' __ elements, are ASP.NET form elements
			' we want to also include any elements that are inside the control
            For Each key In formitems
                If Not key.StartsWith("__") And Not (key.Contains("$") and not key.Contains( me.id )) Then
					dim currentKey as string = key
					' trying to strip out extra data in field names that ASP.NET adds
					if (key.contains("$")) then
						currentKey = key.substring( key.lastIndexOf("$")+1 )
					end if
                    formdetails &= currentKey & ": " & formitems(key) & vbCrLf
                End If
            Next

            Return formdetails
        End Function

        Protected Function appendUserInfo() As String
            Dim userinfo As String = "USER INFO --" & vbCrLf

            userinfo &= "form url: " & Page.Request.Url.ToString() & vbCrLf
            userinfo &= "browser type: " & Request.Browser.Type & vbCrLf
            userinfo &= "browser version: " & Request.Browser.MajorVersion & "." & Request.Browser.MinorVersion & vbCrLf
            userinfo &= "platform: " & Request.Browser.Platform & vbCrLf
            userinfo &= "cookies enabled: " & Request.Browser.Cookies.ToString() & vbCrLf
            userinfo &= "ip address: " & Request.ServerVariables.Item("REMOTE_ADDR") & vbCrLf
            userinfo &= "win user: " & Request.ServerVariables.Item("REMOTE_USER") & vbCrLf
            userinfo &= "js version: " & Request.Browser.EcmaScriptVersion.ToString() & vbCrLf
            If Page.User.Identity.IsAuthenticated Then
                userinfo &= "clubhouse user: " & Page.User.Identity.Name & vbCrLf
            End If

            Return userinfo
        End Function

        Private Sub addEmails(ByVal addresses As String, ByRef emailtype As System.Net.Mail.MailAddressCollection)
            If addresses <> "" Then
                Dim emails() As String
                Dim x As Integer
                Dim email As String
                emails = addresses.Split(",")
                For x = 0 To emails.Length - 1
                    email = emails(x).Trim()
                    emailtype.Add(email)
                Next
            End If
        End Sub

        Protected Sub WriteError(ByVal errortext As String)
            If Not String.IsNullOrEmpty(ErrorMessageBox) Then
                If Not Me.Page.FindControl(ErrorMessageBox) Is Nothing Then
                    Dim errorbox As Label = CType(FindControlRecursive(Me, ErrorMessageBox), Label)
                    errorbox.Text &= errortext
                Else
                    Response.Write(errortext)
                End If
            End If
        End Sub


        Property FileUploadControlName() As String
            Get
                Return _fileuploadcontrol
            End Get
            Set(ByVal value As String)
                _fileuploadcontrol = value
            End Set
        End Property

        Property SetBaseDirectory() As String
            Get
                Return _baseDirectory
            End Get
            Set(ByVal value As String)
                _baseDirectory = value
            End Set
        End Property


        Property ErrorMessageBox() As String
            Get
                Return _errormessagelabel
            End Get
            Set(ByVal value As String)
                _errormessagelabel = value
            End Set
        End Property

        Property sendto() As String
            Get
                Return _EmailsTo
            End Get
            Set(ByVal value As String)
                _EmailsTo = value
            End Set
        End Property
        Property CC() As String
            Get
                Return _EmailsToCC
            End Get
            Set(ByVal value As String)
                _EmailsToCC = value
            End Set
        End Property
        Property BCC() As String
            Get
                Return _EmailsToBCC
            End Get
            Set(ByVal value As String)
                _EmailsToBCC = value
            End Set
        End Property

        Property From() As String
            Get
                Return _EmailFrom
            End Get
            Set(ByVal value As String)
                _EmailFrom = value
            End Set
        End Property

        Property FromName() As String
            Get
                Return _EmailFromName
            End Get
            Set(ByVal value As String)
                _EmailFromName = value
            End Set
        End Property


        Property Subject() As String
            Get
                Return _EmailSubject
            End Get
            Set(ByVal value As String)
                _EmailSubject = value
            End Set
        End Property

        Property HeaderText() As String
            Get
                Return _EmailHeaderText
            End Get
            Set(ByVal value As String)
                _EmailHeaderText = value
            End Set
        End Property

        Property FooterText() As String
            Get
                Return _EmailFooterText
            End Get
            Set(ByVal value As String)
                _EmailFooterText = value
            End Set
        End Property

        Property FilePath() As String
            Get
                Return _FileDirectory & _FilePath
            End Get
            Set(ByVal value As String)
                _FilePath = value
            End Set
        End Property

        Property FileDirectory() As String
            Get
                Return _FileDirectory
            End Get
            Set(ByVal value As String)
                _FileDirectory = value
            End Set
        End Property



        Property EmailFormat() As String
            Get
                Return _EmailFormat
            End Get
            Set(ByVal value As String)
                _EmailFormat = value
            End Set
        End Property
        Property sendbody() As String
            Get
                Return _body
            End Get
            Set(ByVal value As String)
                _body = value
            End Set
        End Property
        Property sendhtml() As Boolean
            Get
                Return _html
            End Get
            Set(ByVal value As Boolean)
                _html = value
            End Set
        End Property

        Property AppendUserDetails() As Boolean
            Get
                return _isappenduserDetails
            End Get
            Set(ByVal value As Boolean)
                _isappenduserdetails = value
            End Set
        End Property
        Property AppendFormDetails() As Boolean
            Get
                Return _isappendformdetails
            End Get
            Set(ByVal value As Boolean)
                _isappendformdetails = value
            End Set
        End Property

        Property FormFieldNames() As String
            Get
                Return _formfieldnames
            End Get
            Set(ByVal value As String)
                _formfieldnames = value
            End Set
        End Property

        Property FormEmailField() As String
            Get
                Return _EmailFromField
            End Get
            Set(ByVal value As String)
                _EmailFromField = value
            End Set
        End Property

        Property SendConfirmation() As Boolean
            Get
                Return _sendconfirmation
            End Get
            Set(ByVal value As Boolean)
                _sendconfirmation = value
            End Set
        End Property


        Property ConfirmationText() As String
            Get
                Return _confirmationtext
            End Get
            Set(ByVal value As String)
                _confirmationtext = value
            End Set
        End Property

        Property showEmailsent() As Boolean
            Get
                Return _showemailsent
            End Get
            Set(ByVal value As Boolean)
                _showemailsent = value
            End Set
        End Property

        Function FindControlRecursive(ByVal ctrl As Control, ByVal id As String) As Control
            Dim c As Control = Nothing

            If ctrl.ID = id Then
                c = ctrl
            Else
                For Each childCtrl In ctrl.Controls
                    Dim resCtrl As Control = FindControlRecursive(childCtrl, id)
                    If resCtrl IsNot Nothing Then c = resCtrl
                Next
            End If

            Return c
        End Function

    End Class

End Namespace

Open in new window

0
 
LVL 19

Expert Comment

by:Amandeep Singh Bhullar
ID: 36240580
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Paging GridView 7 34
System32Int Error 8 44
dynamic menu in asp.net c# 11 29
Protecting vb6 & .Net code Obfuscation 18 51
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now